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/gql subscribe notifs (#5610)

Sean Ayed85bf9326dcd
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 4d5bd02cda..be2b51758a 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -52,6 +52,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -160,6 +161,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -228,6 +230,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -379,6 +382,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/calendar_events",
"crates/call",
"crates/channel_sender",
@@ -531,6 +535,7 @@
"crates/attachment",
"crates/bot_id",
"crates/bots",
+ "crates/broadcast",
"crates/channel_sender",
"crates/channels",
"crates/connection_gateway_client",
@@ -609,6 +614,7 @@
"calendar_events": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/broadcast",
"crates/calendar_events",
"crates/channel_sender",
"crates/cowlike",
@@ -642,6 +648,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -709,6 +716,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_bots",
"crates/channel_sender",
@@ -824,6 +832,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/channels",
"crates/connection_gateway_client",
@@ -915,6 +924,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/channels",
"crates/comms_db_client",
@@ -1218,6 +1228,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -1299,6 +1310,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -1382,6 +1394,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -1484,6 +1497,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -1813,6 +1827,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -1898,6 +1913,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -1982,6 +1998,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -2061,6 +2078,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -2133,6 +2151,7 @@
"email_formatting": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/email_formatting",
@@ -2167,6 +2186,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -2230,6 +2250,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -2293,6 +2314,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/calendar_events",
"crates/channel_sender",
"crates/connection_gateway_client",
@@ -2379,6 +2401,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -2436,6 +2459,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -2717,6 +2741,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -2812,6 +2837,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/channels",
"crates/connection_gateway_client",
@@ -2889,6 +2915,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -3073,11 +3100,14 @@
"graphql_notification": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/broadcast",
+ "crates/channel_sender",
"crates/cowlike",
"crates/document_sub_type",
"crates/filter_ast",
"crates/graphql_common",
"crates/graphql_notification",
+ "crates/invite_email",
"crates/item_filters",
"crates/kafka_util",
"crates/last_online_tracker",
@@ -3090,9 +3120,11 @@
"crates/macro_service_urls",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/mention_utils",
"crates/model-entity",
"crates/model-error-response",
"crates/model_file_type",
+ "crates/model_notifications",
"crates/model_user",
"crates/models_pagination",
"crates/models_properties",
@@ -3138,6 +3170,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/document_sub_type",
@@ -3341,6 +3374,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
@@ -3386,6 +3420,7 @@
"invite_email": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/broadcast",
"crates/cowlike",
"crates/invite_email",
"crates/kafka_util",
@@ -3446,6 +3481,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -3518,6 +3554,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -3872,6 +3909,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -3989,6 +4027,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -4145,6 +4184,7 @@
"model_notifications": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/invite_email",
@@ -4232,6 +4272,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -4311,6 +4352,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -4380,6 +4422,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/channels",
"crates/connection_gateway_client",
@@ -4446,6 +4489,7 @@
"notification": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/broadcast",
"crates/cowlike",
"crates/kafka_util",
"crates/last_online_tracker",
@@ -4470,6 +4514,7 @@
"notification_db_client": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/invite_email",
@@ -4499,6 +4544,7 @@
"notification_sandbox": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/email_formatting",
@@ -4533,6 +4579,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/database_env_vars",
@@ -4596,6 +4643,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
@@ -4659,6 +4707,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -4722,6 +4771,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -4785,6 +4835,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -4878,6 +4929,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/document_sub_type",
@@ -4923,6 +4975,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/document_sub_type",
@@ -4973,6 +5026,7 @@
"referral": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/broadcast",
"crates/cowlike",
"crates/invite_email",
"crates/ip_extractor",
@@ -5003,6 +5057,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/document_sub_type",
@@ -5074,6 +5129,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -5188,6 +5244,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -5295,6 +5352,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -5377,6 +5435,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -5488,6 +5547,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -5603,6 +5663,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -5685,6 +5746,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -5849,6 +5911,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -6037,6 +6100,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
@@ -6114,6 +6178,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/channels",
"crates/connection_gateway_client",
@@ -6198,6 +6263,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
@@ -6264,6 +6330,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
"crates/crm",
@@ -6370,6 +6437,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/broadcast",
"crates/call",
"crates/channel_sender",
"crates/channels",
diff --git a/Cargo.lock b/Cargo.lock
index 66677f2825..189b039bcf 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3108,10 +3108,12 @@ dependencies = [
"macro_authorization",
"macro_user_id",
"model-entity",
+ "model_notifications",
"model_user",
"models_pagination",
"models_properties",
"models_soup",
+ "notification",
"rootcause",
"serde",
"soup",
@@ -6418,14 +6420,19 @@ name = "graphql_notification"
version = "0.1.0"
dependencies = [
"async-graphql",
+ "async-stream",
"chrono",
+ "futures",
"graphql_common",
"macro_user_id",
"model-entity",
+ "model_notifications",
"notification",
"rootcause",
"serde_json",
"tokio",
+ "tokio-stream",
+ "tracing",
"uuid",
"workspace-hack",
]
@@ -10021,6 +10028,7 @@ dependencies = [
"aws-sdk-sns",
"aws-sdk-sqs",
"axum",
+ "broadcast",
"chrono",
"cowlike",
"either",
@@ -10029,6 +10037,7 @@ dependencies = [
"hmac 0.12.1",
"http-body-util",
"itertools 0.14.0",
+ "kafka_util",
"last_online_tracker",
"macro_authorization",
"macro_db_migrator",
@@ -10043,6 +10052,7 @@ dependencies = [
"model_user",
"models_pagination",
"rate_limit",
+ "rdkafka",
"redis",
"reqwest 0.13.4",
"rootcause",
@@ -10054,6 +10064,7 @@ dependencies = [
"strum 0.27.2",
"thiserror 2.0.18",
"tokio",
+ "tokio-retry",
"tower 0.5.3",
"tracing",
"url",
diff --git a/apps/web/src/features/notifications/notification-source.ts b/apps/web/src/features/notifications/notification-source.ts
index fec579666e..823e3b0eb2 100644
--- a/apps/web/src/features/notifications/notification-source.ts
+++ b/apps/web/src/features/notifications/notification-source.ts
@@ -11,7 +11,7 @@ import {
import type { ConnectionGatewayWebsocket } from '@service-connection/websocket';
import { notificationServiceClient } from '@service-notification/client';
import type {
- ConnGatewayInnerNotifValue,
+ ConnGatewayNotificationPayload,
NotifEvent,
UserUnsubscribe,
} from '@service-notification/generated/schemas';
@@ -256,7 +256,7 @@ export function createNotificationSource(
}
const mapWebsocketNotification = (
- raw: ConnGatewayInnerNotifValue
+ raw: ConnGatewayNotificationPayload
): UnifiedNotification => {
return {
...raw,
@@ -271,7 +271,7 @@ export function createNotificationSource(
}
let parsedNotification: UnifiedNotification;
try {
- const raw = JSON.parse(wsData.data) as ConnGatewayInnerNotifValue;
+ const raw = JSON.parse(wsData.data) as ConnGatewayNotificationPayload;
const unsafeMapped = mapWebsocketNotification(raw);
const parseResult = unifiedNotificationSchema.safeParse(unsafeMapped);
if (!parseResult.success) {
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOf.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOf.ts
deleted file mode 100644
index 91c440dd66..0000000000
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOf.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Generated by orval v7.21.0 🍺
- * Do not edit manually.
- * notification_service
- * OpenAPI spec version: 0.1.0
- */
-import type { ConnGatewayInnerNotifValueAllOfDeletedAt } from './connGatewayInnerNotifValueAllOfDeletedAt';
-import type { ConnGatewayInnerNotifValueAllOfSenderId } from './connGatewayInnerNotifValueAllOfSenderId';
-import type { ConnGatewayInnerNotifValueAllOfViewedAt } from './connGatewayInnerNotifValueAllOfViewedAt';
-import type { TaggedContentValue } from './taggedContentValue';
-
-export type ConnGatewayInnerNotifValueAllOf = {
- /** When the notification was created. */
- created_at: string;
- /** When the notification was deleted. */
- deleted_at?: ConnGatewayInnerNotifValueAllOfDeletedAt;
- /** Whether the notification is marked as done. */
- done: boolean;
- /** The notification event type string (e.g. "channel_mention").
-TODO make this a new type */
- notification_event_type: string;
- /** The notification ID. */
- notification_id: string;
- /** Deserialized notification metadata. */
- notification_metadata: TaggedContentValue;
- sender_id?: ConnGatewayInnerNotifValueAllOfSenderId;
- /** Whether the notification has been sent. */
- sent: boolean;
- /** When the notification was last updated. */
- updated_at: string;
- /** When the notification was viewed/seen. */
- viewed_at?: ConnGatewayInnerNotifValueAllOfViewedAt;
-};
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayNotificationPayload.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayNotificationPayload.ts
index b740ec547d..744db047a0 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayNotificationPayload.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayNotificationPayload.ts
@@ -4,12 +4,12 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
-import type { ConnGatewayInnerNotifValue } from './connGatewayInnerNotifValue';
+import type { RealtimeNotifTaggedContentValue } from './realtimeNotifTaggedContentValue';
/**
- * Concrete schema type for [`ConnGatewayInnerNotif`] with `serde_json::Value` metadata.
+ * Concrete schema type for [`RealtimeNotif`] with `serde_json::Value` metadata.
Used for OpenAPI schema generation — serializes identically to
-`ConnGatewayInnerNotif<serde_json::Value>`.
+`RealtimeNotif<serde_json::Value>`.
*/
-export type ConnGatewayNotificationPayload = ConnGatewayInnerNotifValue;
+export type ConnGatewayNotificationPayload = RealtimeNotifTaggedContentValue;
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
index 3dc76b6ad4..4c692282ff 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/index.ts
@@ -46,11 +46,6 @@ export * from './commentedOnDocumentMetadataFileType';
export * from './commentedOnDocumentMetadataSenderProfilePictureUrl';
export * from './commentedOnDocumentMetadataSubType';
export * from './commonChannelMetadata';
-export * from './connGatewayInnerNotifValue';
-export * from './connGatewayInnerNotifValueAllOf';
-export * from './connGatewayInnerNotifValueAllOfDeletedAt';
-export * from './connGatewayInnerNotifValueAllOfSenderId';
-export * from './connGatewayInnerNotifValueAllOfViewedAt';
export * from './connGatewayNotificationPayload';
export * from './createNotification';
export * from './createNotificationAllOf';
@@ -175,12 +170,17 @@ export * from './notificationServiceApiVersion';
export * from './notificationTypeName';
export * from './pushNotificationData';
export * from './pushNotificationDataSenderProfilePictureUrl';
+export * from './realtimeNotifTaggedContentValue';
+export * from './realtimeNotifTaggedContentValueAllOf';
+export * from './realtimeNotifTaggedContentValueAllOfDeletedAt';
+export * from './realtimeNotifTaggedContentValueAllOfNotificationMetadata';
+export * from './realtimeNotifTaggedContentValueAllOfSenderId';
+export * from './realtimeNotifTaggedContentValueAllOfViewedAt';
export * from './reminderMetadata';
export * from './repliedToDocumentCommentThreadMetadata';
export * from './repliedToDocumentCommentThreadMetadataFileType';
export * from './repliedToDocumentCommentThreadMetadataSenderProfilePictureUrl';
export * from './repliedToDocumentCommentThreadMetadataSubType';
-export * from './taggedContentValue';
export * from './taskAssignedMetadata';
export * from './taskAssignedMetadataSenderProfilePictureUrl';
export * from './taskAssignedMetadataSubType';
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValue.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValue.ts
similarity index 55%
rename from apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValue.ts
rename to apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValue.ts
index a3abae1134..63c7a1565f 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValue.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValue.ts
@@ -4,12 +4,11 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
-
-import type { ConnGatewayInnerNotifValueAllOf } from './connGatewayInnerNotifValueAllOf';
import type { Entity } from './entity';
+import type { RealtimeNotifTaggedContentValueAllOf } from './realtimeNotifTaggedContentValueAllOf';
/**
* the value of the inner payload inside [ConnGatewayNotification]
*/
-export type ConnGatewayInnerNotifValue = Entity &
- ConnGatewayInnerNotifValueAllOf;
+export type RealtimeNotifTaggedContentValue = Entity &
+ RealtimeNotifTaggedContentValueAllOf;
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOf.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOf.ts
new file mode 100644
index 0000000000..73a0e15426
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOf.ts
@@ -0,0 +1,33 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { RealtimeNotifTaggedContentValueAllOfDeletedAt } from './realtimeNotifTaggedContentValueAllOfDeletedAt';
+import type { RealtimeNotifTaggedContentValueAllOfNotificationMetadata } from './realtimeNotifTaggedContentValueAllOfNotificationMetadata';
+import type { RealtimeNotifTaggedContentValueAllOfSenderId } from './realtimeNotifTaggedContentValueAllOfSenderId';
+import type { RealtimeNotifTaggedContentValueAllOfViewedAt } from './realtimeNotifTaggedContentValueAllOfViewedAt';
+
+export type RealtimeNotifTaggedContentValueAllOf = {
+ /** When the notification was created. */
+ created_at: string;
+ /** When the notification was deleted. */
+ deleted_at?: RealtimeNotifTaggedContentValueAllOfDeletedAt;
+ /** Whether the notification is marked as done. */
+ done: boolean;
+ /** The notification event type string (e.g. "channel_mention").
+TODO make this a new type */
+ notification_event_type: string;
+ /** The notification ID. */
+ notification_id: string;
+ /** A notification metadata value tagged with the notification event type. */
+ notification_metadata: RealtimeNotifTaggedContentValueAllOfNotificationMetadata;
+ sender_id?: RealtimeNotifTaggedContentValueAllOfSenderId;
+ /** Whether the notification has been sent. */
+ sent: boolean;
+ /** When the notification was last updated. */
+ updated_at: string;
+ /** When the notification was viewed/seen. */
+ viewed_at?: RealtimeNotifTaggedContentValueAllOfViewedAt;
+};
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOfDeletedAt.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfDeletedAt.ts
similarity index 69%
rename from apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOfDeletedAt.ts
rename to apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfDeletedAt.ts
index b801b2a9b8..867d8addec 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOfDeletedAt.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfDeletedAt.ts
@@ -8,4 +8,4 @@
/**
* When the notification was deleted.
*/
-export type ConnGatewayInnerNotifValueAllOfDeletedAt = string | null;
+export type RealtimeNotifTaggedContentValueAllOfDeletedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/taggedContentValue.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfNotificationMetadata.ts
similarity index 80%
rename from apps/web/src/lib/service-clients/service-notification/generated/schemas/taggedContentValue.ts
rename to apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfNotificationMetadata.ts
index 3c058fdffa..90894e6924 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/taggedContentValue.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfNotificationMetadata.ts
@@ -9,7 +9,7 @@ import type { NotificationTypeName } from './notificationTypeName';
/**
* A notification metadata value tagged with the notification event type.
*/
-export interface TaggedContentValue {
+export type RealtimeNotifTaggedContentValueAllOfNotificationMetadata = {
content: unknown;
tag: NotificationTypeName;
-}
+};
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOfSenderId.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfSenderId.ts
similarity index 68%
rename from apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOfSenderId.ts
rename to apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfSenderId.ts
index e6309e8144..9a411ed9f8 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOfSenderId.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfSenderId.ts
@@ -6,4 +6,5 @@
*/
import type { MacroUserIdStr } from './macroUserIdStr';
-export type ConnGatewayInnerNotifValueAllOfSenderId = null | MacroUserIdStr;
+export type RealtimeNotifTaggedContentValueAllOfSenderId =
+ null | MacroUserIdStr;
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOfViewedAt.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfViewedAt.ts
similarity index 70%
rename from apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOfViewedAt.ts
rename to apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfViewedAt.ts
index 0f380b36e2..8cd22f4e2c 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/connGatewayInnerNotifValueAllOfViewedAt.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/realtimeNotifTaggedContentValueAllOfViewedAt.ts
@@ -8,4 +8,4 @@
/**
* When the notification was viewed/seen.
*/
-export type ConnGatewayInnerNotifValueAllOfViewedAt = string | null;
+export type RealtimeNotifTaggedContentValueAllOfViewedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.json
index 239c8089b6..6afb4dd3a6 100644
--- a/apps/web/src/lib/service-clients/service-notification/openapi.json
+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json
@@ -1352,84 +1352,9 @@
}
}
},
- "ConnGatewayInnerNotif_Value": {
- "allOf": [
- {
- "$ref": "#/components/schemas/Entity",
- "description": "The entity the notification is about."
- },
- {
- "type": "object",
- "required": [
- "notification_id",
- "notification_event_type",
- "sent",
- "done",
- "created_at",
- "updated_at",
- "notification_metadata"
- ],
- "properties": {
- "created_at": {
- "type": "string",
- "format": "date-time",
- "description": "When the notification was created."
- },
- "deleted_at": {
- "type": ["string", "null"],
- "format": "date-time",
- "description": "When the notification was deleted."
- },
- "done": {
- "type": "boolean",
- "description": "Whether the notification is marked as done."
- },
- "notification_event_type": {
- "type": "string",
- "description": "The notification event type string (e.g. \"channel_mention\").\nTODO make this a new type"
- },
- "notification_id": {
- "type": "string",
- "format": "uuid",
- "description": "The notification ID."
- },
- "notification_metadata": {
- "$ref": "#/components/schemas/TaggedContent_Value",
- "description": "Deserialized notification metadata."
- },
- "sender_id": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/MacroUserIdStr",
- "description": "The user who triggered the notification."
- }
- ]
- },
- "sent": {
- "type": "boolean",
- "description": "Whether the notification has been sent."
- },
- "updated_at": {
- "type": "string",
- "format": "date-time",
- "description": "When the notification was last updated."
- },
- "viewed_at": {
- "type": ["string", "null"],
- "format": "date-time",
- "description": "When the notification was viewed/seen."
- }
- }
- }
- ],
- "description": "the value of the inner payload inside [ConnGatewayNotification]"
- },
"ConnGatewayNotificationPayload": {
- "$ref": "#/components/schemas/ConnGatewayInnerNotif_Value",
- "description": "Concrete schema type for [`ConnGatewayInnerNotif`] with `serde_json::Value` metadata.\n\nUsed for OpenAPI schema generation — serializes identically to\n`ConnGatewayInnerNotif<serde_json::Value>`."
+ "$ref": "#/components/schemas/RealtimeNotif_TaggedContent_Value",
+ "description": "Concrete schema type for [`RealtimeNotif`] with `serde_json::Value` metadata.\n\nUsed for OpenAPI schema generation — serializes identically to\n`RealtimeNotif<serde_json::Value>`."
},
"CreateNotification": {
"allOf": [
@@ -2478,6 +2403,88 @@
}
}
},
+ "RealtimeNotif_TaggedContent_Value": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Entity",
+ "description": "The entity the notification is about."
+ },
+ {
+ "type": "object",
+ "required": [
+ "notification_id",
+ "notification_event_type",
+ "sent",
+ "done",
+ "created_at",
+ "updated_at",
+ "notification_metadata"
+ ],
+ "properties": {
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the notification was created."
+ },
+ "deleted_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the notification was deleted."
+ },
+ "done": {
+ "type": "boolean",
+ "description": "Whether the notification is marked as done."
+ },
+ "notification_event_type": {
+ "type": "string",
+ "description": "The notification event type string (e.g. \"channel_mention\").\nTODO make this a new type"
+ },
+ "notification_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The notification ID."
+ },
+ "notification_metadata": {
+ "type": "object",
+ "description": "A notification metadata value tagged with the notification event type.",
+ "required": ["tag", "content"],
+ "properties": {
+ "content": {},
+ "tag": {
+ "$ref": "#/components/schemas/NotificationTypeName"
+ }
+ }
+ },
+ "sender_id": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "The user who triggered the notification."
+ }
+ ]
+ },
+ "sent": {
+ "type": "boolean",
+ "description": "Whether the notification has been sent."
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the notification was last updated."
+ },
+ "viewed_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the notification was viewed/seen."
+ }
+ }
+ }
+ ],
+ "description": "the value of the inner payload inside [ConnGatewayNotification]"
+ },
"ReminderMetadata": {
"type": "object",
"description": "Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.",
@@ -2541,17 +2548,6 @@
}
}
},
- "TaggedContent_Value": {
- "type": "object",
- "description": "A notification metadata value tagged with the notification event type.",
- "required": ["tag", "content"],
- "properties": {
- "content": {},
- "tag": {
- "$ref": "#/components/schemas/NotificationTypeName"
- }
- }
- },
"TaskAssignedMetadata": {
"type": "object",
"description": "Metadata for when a user is assigned to a task",
diff --git a/crates/broadcast/src/lib.rs b/crates/broadcast/src/lib.rs
index d98eec8a29..636649c60c 100644
--- a/crates/broadcast/src/lib.rs
+++ b/crates/broadcast/src/lib.rs
@@ -58,12 +58,64 @@ pub struct BroadcastManager<T, K, V> {
channels: Arc<DashMap<K, tokio::sync::broadcast::Sender<V>>>,
}
-#[derive(Debug)]
-enum ExitReason {
+/// The reason a broadcast subscription's forwarding task stopped.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ExitReason {
+ /// The subscription receiver was dropped by its consumer.
ReceiverClosed,
+ /// The keyed broadcast sender was closed.
SenderClosed,
+ /// The subscriber's bounded buffer filled.
SlowConsumer,
- Lagging { skipped: u64 },
+ /// The subscriber fell behind the shared broadcast buffer.
+ Lagging {
+ /// Number of messages skipped by the broadcast receiver.
+ skipped: u64,
+ },
+}
+
+/// A bounded broadcast subscription and its independently reported exit reason.
+pub struct BroadcastSubscription<V> {
+ receiver: tokio::sync::mpsc::Receiver<V>,
+ exit_reason: tokio::sync::oneshot::Receiver<ExitReason>,
+}
+
+impl<V> BroadcastSubscription<V> {
+ /// Creates a subscription from its message and exit-reason receivers.
+ pub fn from_parts(
+ receiver: tokio::sync::mpsc::Receiver<V>,
+ exit_reason: tokio::sync::oneshot::Receiver<ExitReason>,
+ ) -> Self {
+ Self {
+ receiver,
+ exit_reason,
+ }
+ }
+
+ /// Splits the subscription into independently observable message and exit-reason receivers.
+ pub fn into_parts(
+ self,
+ ) -> (
+ tokio::sync::mpsc::Receiver<V>,
+ tokio::sync::oneshot::Receiver<ExitReason>,
+ ) {
+ (self.receiver, self.exit_reason)
+ }
+
+ /// Returns only the message receiver, discarding exit-reason reporting.
+ pub fn into_receiver(self) -> tokio::sync::mpsc::Receiver<V> {
+ self.receiver
+ }
+
+ /// Receives the next buffered value.
+ pub async fn recv(&mut self) -> Option<V> {
+ self.receiver.recv().await
+ }
+
+ /// Attempts to receive the next buffered value without waiting.
+ pub fn try_recv(&mut self) -> Result<V, tokio::sync::mpsc::error::TryRecvError> {
+ self.receiver.try_recv()
+ }
}
/// An error returned when a value has no active subscribers.
@@ -95,12 +147,9 @@ where
/// subscriber as a slow consumer, disconnects it, and closes the receiver
/// after its buffered values have been drained.
#[must_use]
- pub fn subscribe(
- &self,
- key: K,
- subscriber_buffer: NonZeroUsize,
- ) -> tokio::sync::mpsc::Receiver<V> {
+ pub fn subscribe(&self, key: K, subscriber_buffer: NonZeroUsize) -> BroadcastSubscription<V> {
let (subscriber_tx, subscriber_rx) = tokio::sync::mpsc::channel(subscriber_buffer.get());
+ let (exit_reason_tx, exit_reason_rx) = tokio::sync::oneshot::channel();
let entry = self
.channels
@@ -154,9 +203,10 @@ where
tracing::debug!(?reason, "broadcast subscriber task exited");
}
}
+ let _ = exit_reason_tx.send(reason);
});
- subscriber_rx
+ BroadcastSubscription::from_parts(subscriber_rx, exit_reason_rx)
}
/// Publishes `value` to every active subscriber for `key`.
diff --git a/crates/broadcast/src/test.rs b/crates/broadcast/src/test.rs
index 6872c430c0..cc2efcd308 100644
--- a/crates/broadcast/src/test.rs
+++ b/crates/broadcast/src/test.rs
@@ -70,7 +70,7 @@ async fn returns_the_unpublished_value_when_there_are_no_subscribers() {
#[tokio::test]
async fn removes_a_key_after_its_last_receiver_closes() {
let manager = BroadcastManager::<_, &str, usize>::new(TaskTracker::new(), capacity(8));
- let receiver = manager.subscribe("user", capacity(2));
+ let receiver = manager.subscribe("user", capacity(2)).into_receiver();
assert!(manager.subscriber_count(&"user") > 0);
assert_eq!(manager.subscriber_count(&"user"), 1);
@@ -87,7 +87,8 @@ async fn removes_a_key_after_its_last_receiver_closes() {
#[tokio::test]
async fn disconnects_a_subscriber_when_its_buffer_is_full() {
let manager = BroadcastManager::new(TaskTracker::new(), capacity(8));
- let mut receiver = manager.subscribe("user", capacity(1));
+ let subscription = manager.subscribe("user", capacity(1));
+ let (mut receiver, exit_reason) = subscription.into_parts();
assert_eq!(manager.publish(&"user", 1).unwrap(), 1);
wait_until(|| receiver.len() == 1).await;
@@ -97,6 +98,7 @@ async fn disconnects_a_subscriber_when_its_buffer_is_full() {
assert_eq!(receiver.recv().await, Some(1));
assert_eq!(receiver.recv().await, None);
+ assert_eq!(exit_reason.await, Ok(ExitReason::SlowConsumer));
manager.shutdown().await;
}
diff --git a/crates/complete_graph/Cargo.toml b/crates/complete_graph/Cargo.toml
index abbd0f82b2..d6b979c06f 100644
--- a/crates/complete_graph/Cargo.toml
+++ b/crates/complete_graph/Cargo.toml
@@ -32,6 +32,8 @@ macro_authorization = { path = "../macro_authorization", features = [
] }
macro_user_id = { path = "../macro_user_id" }
model-entity = { path = "../model-entity" }
+model_notifications = { path = "../model_notifications" }
+notification = { path = "../notification" }
soup = { path = "../soup", default-features = false, features = ["ports"] }
soup_realtime = { path = "../soup_realtime", default-features = false, features = [
"ports",
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 5e38b70754..e2f6b1ab0c 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -3,7 +3,7 @@ mod test;
use std::{marker::PhantomData, sync::Arc};
-use async_graphql::{Context, ID, MergedObject, Object, Schema, Subscription};
+use async_graphql::{Context, ID, MergedObject, MergedSubscription, Object, Schema, Subscription};
use axum::extract::FromRef;
use email::{
domain::ports::{EmailService, EmailUserService, NoOpEmailService},
@@ -24,7 +24,7 @@ use graphql_entity_mutation::EntityMutationRoot;
use graphql_favorite::{EntityFavoriteEdgeReader, NoOpEntityFavoriteEdgeReader};
use graphql_notification::{
NoOpNotificationMutationService, NoOpSoupNotificationEdgeReader, NotificationMutationRoot,
- NotificationMutationService, SoupNotificationEdgeReader,
+ NotificationMutationService, NotificationSubscriptionRoot, SoupNotificationEdgeReader,
};
use graphql_permission::{EntityPermissionEdgeReader, NoOpEntityPermissionEdgeReader};
use graphql_properties::{
@@ -41,6 +41,13 @@ use macro_authorization::{
MacroAuthorizationState, NoopMacroAuthJwtValidator,
};
use macro_user_id::user_id::MacroUserIdStr;
+use model_notifications::NotifEvent;
+use notification::domain::{
+ models::queue_message::RealtimeNotif,
+ ports::{
+ NoopWebSocketNotificationSubscriptionService, WebSocketNotificationSubscriptionService,
+ },
+};
use soup::domain::ports::{NoOpSoupService, SoupService};
use soup_realtime::domain::ports::{
NoOpSoupRealtimeSubscriptionService, SoupRealtimeSubscriptionService,
@@ -88,30 +95,50 @@ impl<
}
}
+/// Root subscription object combining realtime Soup and notification adapters.
+#[derive(MergedSubscription)]
+pub struct CompleteSubscriptionRoot<R, NS, Auth, St, NR, PR, ER, FR, AR>(
+ SoupSubscriptionRoot<R, Auth, St, NR, PR, ER, FR, AR>,
+ NotificationSubscriptionRoot<NS>,
+)
+where
+ R: SoupRealtimeSubscriptionService,
+ NS: WebSocketNotificationSubscriptionService<RealtimeNotif<NotifEvent>>,
+ Auth: MacroAuthorizationService,
+ St: Clone + Send + Sync + 'static,
+ MacroAuthorizationState<Auth>: FromRef<St>,
+ NR: SoupNotificationEdgeReader,
+ PR: EntityPropertyReader,
+ ER: SoupEmailContentEdgeReader,
+ FR: EntityFavoriteEdgeReader,
+ AR: EntityPermissionEdgeReader;
+
/// GraphQL Soup schema type.
///
-/// `S` is the soup query service, `R` the realtime subscription service, `E`
-/// the email service, `EAS` the entity access service, `Auth` the authorization
-/// service, `St` the embedding axum router state, `W` the property mutation
-/// writer, `M` the entity mutation service, `C` the channel activity mutation
-/// service, `N` the notification mutation service, `NR` the notification edge
-/// reader, `PR` the property edge reader, `ER` the email-content edge reader,
-/// `FR` the favorite edge reader, and `AR` the access edge reader.
-pub type SoupSchema<S, R, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR> = Schema<
+/// `S` is the soup query service, `R` the realtime Soup subscription service,
+/// `NS` the realtime notification subscription service, `E` the email service,
+/// `EAS` the entity access service, `Auth` the authorization service, `St` the
+/// embedding axum router state, `W` the property mutation writer, `M` the entity
+/// mutation service, `C` the channel activity mutation service, `N` the notification
+/// mutation service, `NR` the notification edge reader, `PR` the property edge
+/// reader, `ER` the email-content edge reader, `FR` the favorite edge reader, and
+/// `AR` the access edge reader.
+pub type SoupSchema<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR> = Schema<
SoupQueryRoot<S, E, EAS, Auth, St, NR, PR, ER, FR, AR>,
CompleteMutationRoot<W, M, SoupEdges<NR, PR, ER, FR, AR>, C, N, EAS, E>,
- SoupSubscriptionRoot<R, Auth, St, NR, PR, ER, FR, AR>,
+ CompleteSubscriptionRoot<R, NS, Auth, St, NR, PR, ER, FR, AR>,
>;
/// GraphQL Soup schema type backed by shared query and realtime services.
-pub type SharedSoupSchema<S, R, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR> =
- SoupSchema<Arc<S>, Arc<R>, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR>;
+pub type SharedSoupSchema<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR> =
+ SoupSchema<Arc<S>, Arc<R>, Arc<NS>, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR>;
/// GraphQL Soup schema type backed by the no-op services, used only for
/// SDL export or introspection.
pub type SchemaOnlySoupSchema = SoupSchema<
NoOpSoupService,
NoOpSoupRealtimeSubscriptionService,
+ NoopWebSocketNotificationSubscriptionService,
NoOpEmailService,
NoOpEntityAccessService,
SchemaOnlyAuthorizationService,
@@ -225,7 +252,11 @@ pub struct EmailThreadInput {
/// Build a GraphQL schema for Soup suitable for SDL export or introspection.
pub fn build_schema() -> SchemaOnlySoupSchema {
- build_schema_with_services(NoOpSoupService, NoOpSoupRealtimeSubscriptionService)
+ build_schema_with_services(
+ NoOpSoupService,
+ NoOpSoupRealtimeSubscriptionService,
+ NoopWebSocketNotificationSubscriptionService,
+ )
}
/// Build a GraphQL schema backed by a query service and no-op realtime service.
@@ -235,6 +266,7 @@ pub fn build_schema_with_service<S, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR
) -> SoupSchema<
S,
NoOpSoupRealtimeSubscriptionService,
+ NoopWebSocketNotificationSubscriptionService,
E,
EAS,
Auth,
@@ -268,18 +300,24 @@ where
FR: EntityFavoriteEdgeReader,
AR: EntityPermissionEdgeReader,
{
- build_schema_with_services(service, NoOpSoupRealtimeSubscriptionService)
+ build_schema_with_services(
+ service,
+ NoOpSoupRealtimeSubscriptionService,
+ NoopWebSocketNotificationSubscriptionService,
+ )
}
/// Build a GraphQL schema backed by query and realtime Soup services.
#[allow(clippy::type_complexity)]
-pub fn build_schema_with_services<S, R, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR>(
+pub fn build_schema_with_services<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR>(
service: S,
realtime_service: R,
-) -> SoupSchema<S, R, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR>
+ notification_subscription_service: NS,
+) -> SoupSchema<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR>
where
S: SoupService + Clone,
R: SoupRealtimeSubscriptionService + Clone,
+ NS: WebSocketNotificationSubscriptionService<RealtimeNotif<NotifEvent>> + Clone,
E: EmailService + EmailUserService,
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
@@ -300,7 +338,10 @@ where
Schema::build(
SoupQueryRoot::new(service),
CompleteMutationRoot::<W, M, SoupEdges<NR, PR, ER, FR, AR>, C, N, EAS, E>::new(),
- SoupSubscriptionRoot::new(realtime_service),
+ CompleteSubscriptionRoot(
+ SoupSubscriptionRoot::new(realtime_service),
+ NotificationSubscriptionRoot::new(notification_subscription_service),
+ ),
)
.finish()
}
@@ -312,6 +353,7 @@ pub fn build_schema_from_arc<S, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR
) -> SoupSchema<
Arc<S>,
NoOpSoupRealtimeSubscriptionService,
+ NoopWebSocketNotificationSubscriptionService,
E,
EAS,
Auth,
@@ -350,13 +392,15 @@ where
/// Build a GraphQL schema backed by `Arc`-shared query and realtime services.
#[allow(clippy::type_complexity)]
-pub fn build_schema_from_arcs<S, R, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR>(
+pub fn build_schema_from_arcs<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR>(
service: Arc<S>,
realtime_service: Arc<R>,
-) -> SharedSoupSchema<S, R, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR>
+ notification_subscription_service: Arc<NS>,
+) -> SharedSoupSchema<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR>
where
S: SoupService,
R: SoupRealtimeSubscriptionService,
+ NS: WebSocketNotificationSubscriptionService<RealtimeNotif<NotifEvent>>,
E: EmailService + EmailUserService,
EAS: EntityAccessService,
Auth: MacroAuthorizationService,
@@ -374,7 +418,7 @@ where
FR: EntityFavoriteEdgeReader,
AR: EntityPermissionEdgeReader,
{
- build_schema_with_services(service, realtime_service)
+ build_schema_with_services(service, realtime_service, notification_subscription_service)
}
/// Root entry point for the complete GraphQL API.
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index fe79f3c9f9..92c1467f2b 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -756,6 +756,7 @@ struct TestHarness {
schema: SoupSchema<
CountingSoupService,
NoOpSoupRealtimeSubscriptionService,
+ NoopWebSocketNotificationSubscriptionService,
CountingEmailService,
CountingEntityAccessService,
FakeAuthorizationService,
@@ -909,6 +910,7 @@ async fn soup_updates_subscribes_as_the_authenticated_user() {
let schema: SoupSchema<
CountingSoupService,
TestRealtimeSubscriptionService,
+ NoopWebSocketNotificationSubscriptionService,
NoOpEmailService,
NoOpEntityAccessService,
SchemaOnlyAuthorizationService,
@@ -922,7 +924,11 @@ async fn soup_updates_subscribes_as_the_authenticated_user() {
NoOpSoupEmailContentEdgeReader,
NoOpEntityFavoriteEdgeReader,
NoOpEntityPermissionEdgeReader,
- > = build_schema_with_services(soup_service, realtime);
+ > = build_schema_with_services(
+ soup_service,
+ realtime,
+ NoopWebSocketNotificationSubscriptionService,
+ );
let request = async_graphql::Request::new(
"subscription { soupUpdates { __typename ... on SoupUpdated { item { id } } ... on GraphqlCacheDeletion { graphqlTypeName entityId } } }",
)
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index e194e570fe..88c005db0d 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -86,11 +86,27 @@ fn soup_response_schema_exposes_frontend_fields() {
"MARK_SEEN",
"MARK_DONE",
"MARK_UNDONE",
- "type SoupSubscriptionRoot {",
+ "type CompleteSubscriptionRoot {",
"soupUpdates: [SoupPatch!]!",
+ "notificationUpdates: GraphqlSoupNotification!",
+ "type GraphqlSoupNotification {",
+ "metadata: JSON! @deprecated(reason: \"Use typedMetadata with union inline fragments\")",
+ "typedMetadata: GraphqlNotifEvent",
] {
assert_sdl_line(&sdl, expected);
}
+ assert!(
+ sdl.contains("union GraphqlNotifEvent = GraphqlChannelMentionMetadata |"),
+ "notification metadata must be represented by the typed event union"
+ );
+ assert_eq!(
+ sdl.lines()
+ .filter(|line| line.trim() == "typedMetadata: GraphqlNotifEvent")
+ .count(),
+ 1,
+ "stored and realtime notifications must share one nullable typed metadata field"
+ );
+ assert!(!sdl.contains("GraphqlRealtimeNotification"));
assert!(
!sdl.lines()
.any(|line| line.trim() == "type GraphqlEntityRef {"),
diff --git a/crates/graphql_notification/Cargo.toml b/crates/graphql_notification/Cargo.toml
index a4383a01f9..ff23a31f9a 100644
--- a/crates/graphql_notification/Cargo.toml
+++ b/crates/graphql_notification/Cargo.toml
@@ -6,15 +6,20 @@ publish = false
[dependencies]
async-graphql = { workspace = true, features = ["dataloader"] }
+async-stream = { workspace = true }
graphql_common = { path = "../graphql_common" }
macro_user_id = { path = "../macro_user_id" }
model-entity = { path = "../model-entity" }
+model_notifications = { path = "../model_notifications" }
notification = { path = "../notification" }
rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
+tokio-stream = { workspace = true }
+tracing = { workspace = true }
uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
chrono = { workspace = true }
+futures = { workspace = true }
diff --git a/crates/graphql_notification/src/lib.rs b/crates/graphql_notification/src/lib.rs
index 1cbfcaf302..d4262e1674 100644
--- a/crates/graphql_notification/src/lib.rs
+++ b/crates/graphql_notification/src/lib.rs
@@ -7,8 +7,12 @@
mod loaders;
/// GraphQL notification mutation adapter.
mod mutations;
+/// Typed GraphQL notification event output models.
+mod notification_event;
/// GraphQL notification object and edge resolver.
mod objects;
+/// GraphQL realtime notification subscription adapter.
+mod subscriptions;
pub use loaders::{
EntityNotificationsLoader, NoOpSoupNotificationEdgeReader, SoupNotificationEdgeReader,
@@ -18,4 +22,6 @@ pub use mutations::{
GraphqlNotificationUpdateOperation, NoOpNotificationMutationService, NotificationMutationRoot,
NotificationMutationService, UpdateNotificationsInput,
};
+pub use notification_event::GraphqlNotifEvent;
pub use objects::{GraphqlSoupNotification, load_entity_notifications};
+pub use subscriptions::{NotificationSubscriptionRoot, subscribe_to_notifications};
diff --git a/crates/graphql_notification/src/notification_event.rs b/crates/graphql_notification/src/notification_event.rs
new file mode 100644
index 0000000000..6703fc558d
--- /dev/null
+++ b/crates/graphql_notification/src/notification_event.rs
@@ -0,0 +1,1156 @@
+//! Typed GraphQL output models for realtime notification event metadata.
+
+use async_graphql::{Enum, ID, Object, Union};
+use model_notifications::{
+ AiResponseMetadata, CalendarEventReminderMetadata, CallStartedMetadata, ChannelInviteMetadata,
+ ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata, ChannelType,
+ CommentedOnDocumentMetadata, DocumentMentionMetadata, GithubPrCheckRun, GithubPrCheckRunState,
+ GithubPrComment, GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus,
+ GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview,
+ GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested, InboxReauthRequiredMetadata,
+ InviteToTeamMetadata, MentionedInDocumentCommentMetadata, NewEmailMetadata, NotifEvent,
+ NotificationDocumentSubType, ReminderMetadata, RepliedToDocumentCommentThreadMetadata,
+ TaskAssignedMetadata,
+};
+
+/// GraphQL channel type used by notification metadata.
+#[derive(Clone, Copy, Debug, Eq, Enum, PartialEq)]
+pub enum GraphqlNotificationChannelType {
+ /// Public channel.
+ Public,
+ /// Private channel.
+ Private,
+ /// Direct-message channel.
+ DirectMessage,
+ /// Team channel.
+ Team,
+}
+
+impl From<ChannelType> for GraphqlNotificationChannelType {
+ fn from(value: ChannelType) -> Self {
+ match value {
+ ChannelType::Public => Self::Public,
+ ChannelType::Private => Self::Private,
+ ChannelType::DirectMessage => Self::DirectMessage,
+ ChannelType::Team => Self::Team,
+ }
+ }
+}
+
+/// GraphQL document subtype used by notification metadata.
+#[derive(Clone, Copy, Debug, Eq, Enum, PartialEq)]
+pub enum GraphqlNotificationDocumentSubType {
+ /// Task document.
+ Task,
+ /// Snippet document.
+ Snippet,
+ /// Skill document.
+ Skill,
+}
+
+impl From<NotificationDocumentSubType> for GraphqlNotificationDocumentSubType {
+ fn from(value: NotificationDocumentSubType) -> Self {
+ match value {
+ NotificationDocumentSubType::Task => Self::Task,
+ NotificationDocumentSubType::Snippet => Self::Snippet,
+ NotificationDocumentSubType::Skill => Self::Skill,
+ }
+ }
+}
+
+/// GraphQL GitHub pull-request lifecycle status.
+#[derive(Clone, Copy, Debug, Eq, Enum, PartialEq)]
+pub enum GraphqlGithubPrEventStatus {
+ /// Open pull request.
+ Open,
+ /// Closed pull request.
+ Closed,
+ /// Merged pull request.
+ Merged,
+}
+
+impl From<GithubPrEventStatus> for GraphqlGithubPrEventStatus {
+ fn from(value: GithubPrEventStatus) -> Self {
+ match value {
+ GithubPrEventStatus::Open => Self::Open,
+ GithubPrEventStatus::Closed => Self::Closed,
+ GithubPrEventStatus::Merged => Self::Merged,
+ }
+ }
+}
+
+/// GraphQL GitHub pull-request action.
+#[derive(Clone, Copy, Debug, Eq, Enum, PartialEq)]
+pub enum GraphqlGithubPrEventAction {
+ /// Pull request opened.
+ Opened,
+ /// Pull request reopened.
+ Reopened,
+ /// Pull request closed.
+ Closed,
+}
+
+impl From<GithubPrEventAction> for GraphqlGithubPrEventAction {
+ fn from(value: GithubPrEventAction) -> Self {
+ match value {
+ GithubPrEventAction::Opened => Self::Opened,
+ GithubPrEventAction::Reopened => Self::Reopened,
+ GithubPrEventAction::Closed => Self::Closed,
+ }
+ }
+}
+
+/// GraphQL GitHub check-run state.
+#[derive(Clone, Copy, Debug, Eq, Enum, PartialEq)]
+pub enum GraphqlGithubPrCheckRunState {
+ /// Check completed successfully.
+ Completed,
+ /// Check completed with a failure-like result.
+ Failed,
+}
+
+impl From<GithubPrCheckRunState> for GraphqlGithubPrCheckRunState {
+ fn from(value: GithubPrCheckRunState) -> Self {
+ match value {
+ GithubPrCheckRunState::Completed => Self::Completed,
+ GithubPrCheckRunState::Failed => Self::Failed,
+ }
+ }
+}
+
+/// GraphQL GitHub pull-request comment kind.
+#[derive(Clone, Copy, Debug, Eq, Enum, PartialEq)]
+pub enum GraphqlGithubPrCommentKind {
+ /// Top-level issue comment.
+ Issue,
+ /// Inline review comment.
+ ReviewComment,
+}
+
+impl From<GithubPrCommentKind> for GraphqlGithubPrCommentKind {
+ fn from(value: GithubPrCommentKind) -> Self {
+ match value {
+ GithubPrCommentKind::Issue => Self::Issue,
+ GithubPrCommentKind::ReviewComment => Self::ReviewComment,
+ }
+ }
+}
+
+/// GraphQL location of a GitHub pull-request mention.
+#[derive(Clone, Copy, Debug, Eq, Enum, PartialEq)]
+pub enum GraphqlGithubPrMentionLocation {
+ /// Pull-request body.
+ PrBody,
+ /// Top-level comment.
+ Comment,
+ /// Review summary.
+ Review,
+ /// Inline review comment.
+ ReviewComment,
+}
+
+impl From<GithubPrMentionLocation> for GraphqlGithubPrMentionLocation {
+ fn from(value: GithubPrMentionLocation) -> Self {
+ match value {
+ GithubPrMentionLocation::PrBody => Self::PrBody,
+ GithubPrMentionLocation::Comment => Self::Comment,
+ GithubPrMentionLocation::Review => Self::Review,
+ GithubPrMentionLocation::ReviewComment => Self::ReviewComment,
+ }
+ }
+}
+
+/// GraphQL state of a GitHub pull-request review.
+#[derive(Clone, Copy, Debug, Eq, Enum, PartialEq)]
+pub enum GraphqlGithubPrReviewState {
+ /// Review approved the pull request.
+ Approved,
+ /// Review requested changes.
+ ChangesRequested,
+ /// Review left comments without an approval decision.
+ Commented,
+}
+
+impl From<GithubPrReviewState> for GraphqlGithubPrReviewState {
+ fn from(value: GithubPrReviewState) -> Self {
+ match value {
+ GithubPrReviewState::Approved => Self::Approved,
+ GithubPrReviewState::ChangesRequested => Self::ChangesRequested,
+ GithubPrReviewState::Commented => Self::Commented,
+ }
+ }
+}
+
+/// GraphQL wrapper for fields shared by channel notification metadata.
+pub struct GraphqlChannelNotificationCommon(model_notifications::CommonChannelMetadata);
+
+/// Fields shared by channel notification metadata.
+#[Object]
+impl GraphqlChannelNotificationCommon {
+ /// Channel type.
+ async fn channel_type(&self) -> GraphqlNotificationChannelType {
+ self.0.channel_type.into()
+ }
+
+ /// Channel display name.
+ async fn channel_name(&self) -> &str {
+ &self.0.channel_name
+ }
+}
+
+/// GraphQL wrapper for fields shared by GitHub pull-request notification metadata.
+pub struct GraphqlGithubPrNotificationCommon(GithubPrNotificationCommon);
+
+/// Fields shared by GitHub pull-request notification metadata.
+#[Object]
+impl GraphqlGithubPrNotificationCommon {
+ /// Internal foreign-entity identifier.
+ async fn foreign_entity_id(&self) -> ID {
+ ID(self.0.foreign_entity_id.to_string())
+ }
+
+ /// External GitHub key.
+ async fn github_key(&self) -> &str {
+ &self.0.github_key
+ }
+
+ /// Repository owner or organization.
+ async fn owner(&self) -> &str {
+ &self.0.owner
+ }
+
+ /// Repository name.
+ async fn repo(&self) -> &str {
+ &self.0.repo
+ }
+
+ /// Pull-request number.
+ async fn number(&self) -> String {
+ self.0.number.to_string()
+ }
+
+ /// Public pull-request URL.
+ async fn url(&self) -> &str {
+ &self.0.url
+ }
+
+ /// Compact pull-request display label.
+ async fn display_name(&self) -> &str {
+ &self.0.display_name
+ }
+
+ /// Pull-request title.
+ async fn title(&self) -> &str {
+ &self.0.title
+ }
+
+ /// Sender GitHub login.
+ async fn sender_github_login(&self) -> Option<&str> {
+ self.0.sender_github_login.as_deref()
+ }
+
+ /// Sender GitHub user identifier.
+ async fn sender_github_user_id(&self) -> Option<&str> {
+ self.0.sender_github_user_id.as_deref()
+ }
+
+ /// Sender GitHub avatar URL.
+ async fn sender_github_avatar_url(&self) -> Option<&str> {
+ self.0.sender_github_avatar_url.as_deref()
+ }
+}
+
+/// GraphQL wrapper for channel mention metadata.
+pub struct GraphqlChannelMentionMetadata(ChannelMentionMetadata);
+
+/// Metadata for a channel mention notification.
+#[Object]
+impl GraphqlChannelMentionMetadata {
+ /// Mentioning message identifier.
+ async fn message_id(&self) -> &str {
+ &self.0.message_id
+ }
+
+ /// Mentioning message content.
+ async fn message_content(&self) -> &str {
+ &self.0.message_content
+ }
+
+ /// Whether the message has attachments.
+ async fn has_attachments(&self) -> bool {
+ self.0.has_attachments
+ }
+
+ /// Thread identifier, when the mention is in a thread.
+ async fn thread_id(&self) -> Option<&str> {
+ self.0.thread_id.as_deref()
+ }
+
+ /// Display name for a non-user sender.
+ async fn sender_display_name(&self) -> Option<&str> {
+ self.0.sender_display_name.as_deref()
+ }
+
+ /// Channel metadata.
+ #[graphql(flatten)]
+ async fn channel(&self) -> GraphqlChannelNotificationCommon {
+ GraphqlChannelNotificationCommon(self.0.common.clone())
+ }
+
+ /// Sender profile-picture URL.
+ async fn sender_profile_picture_url(&self) -> Option<&str> {
+ self.0.sender_profile_picture_url.as_deref()
+ }
+}
+
+/// GraphQL wrapper for document mention metadata.
+pub struct GraphqlDocumentMentionMetadata(DocumentMentionMetadata);
+
+/// Metadata for a document mention notification.
+#[Object]
+impl GraphqlDocumentMentionMetadata {
+ /// Mentioned document name.
+ async fn document_name(&self) -> &str {
+ &self.0.document_name
+ }
+
+ /// Document owner identifier.
+ async fn owner(&self) -> String {
+ self.0.owner.to_string()
+ }
+
+ /// Document file type.
+ async fn file_type(&self) -> Option<&str> {
+ self.0.file_type.as_deref()
+ }
+
+ /// Document subtype.
+ async fn sub_type(&self) -> Option<GraphqlNotificationDocumentSubType> {
+ self.0.sub_type.clone().map(Into::into)
+ }
+
+ /// Channel mention that referenced the document.
+ #[graphql(flatten)]
+ async fn channel(&self) -> GraphqlChannelMentionMetadata {
+ GraphqlChannelMentionMetadata(self.0.channel.clone())
+ }
+}
+
+/// GraphQL wrapper for a mention in document comment metadata.
+pub struct GraphqlMentionedInDocumentCommentMetadata(MentionedInDocumentCommentMetadata);
+
+/// Metadata for a mention in a document comment.
+#[Object]
+impl GraphqlMentionedInDocumentCommentMetadata {
+ /// Document name.
+ async fn document_name(&self) -> &str {
+ &self.0.document_name
+ }
+
+ /// Document owner identifier.
+ async fn owner(&self) -> String {
+ self.0.owner.to_string()
+ }
+
+ /// Document file type.
+ async fn file_type(&self) -> Option<&str> {
+ self.0.file_type.as_deref()
+ }
+
+ /// Document subtype.
+ async fn sub_type(&self) -> Option<GraphqlNotificationDocumentSubType> {
+ self.0.sub_type.clone().map(Into::into)
+ }
+
+ /// Mention identifier.
+ async fn mention_id(&self) -> &str {
+ &self.0.mention_id
+ }
+
+ /// Comment identifier.
+ async fn comment_id(&self) -> i64 {
+ self.0.comment_id
+ }
+
+ /// Comment thread identifier.
+ async fn thread_id(&self) -> i64 {
+ self.0.thread_id
+ }
+
+ /// Comment text.
+ async fn text(&self) -> &str {
+ &self.0.text
+ }
+
+ /// Sender profile-picture URL.
+ async fn sender_profile_picture_url(&self) -> Option<&str> {
+ self.0.sender_profile_picture_url.as_deref()
+ }
+}
+
+/// GraphQL wrapper for document comment thread reply metadata.
+pub struct GraphqlRepliedToDocumentCommentThreadMetadata(RepliedToDocumentCommentThreadMetadata);
+
+/// Metadata for a reply to a document comment thread.
+#[Object]
+impl GraphqlRepliedToDocumentCommentThreadMetadata {
+ /// Document name.
+ async fn document_name(&self) -> &str {
+ &self.0.document_name
+ }
+
+ /// Document owner identifier.
+ async fn owner(&self) -> String {
+ self.0.owner.to_string()
+ }
+
+ /// Document file type.
+ async fn file_type(&self) -> Option<&str> {
+ self.0.file_type.as_deref()
+ }
+
+ /// Document subtype.
+ async fn sub_type(&self) -> Option<GraphqlNotificationDocumentSubType> {
+ self.0.sub_type.clone().map(Into::into)
+ }
+
+ /// Comment identifier.
+ async fn comment_id(&self) -> i64 {
+ self.0.comment_id
+ }
+
+ /// Comment thread identifier.
+ async fn thread_id(&self) -> i64 {
+ self.0.thread_id
+ }
+
+ /// Reply text.
+ async fn text(&self) -> &str {
+ &self.0.text
+ }
+
+ /// Sender profile-picture URL.
+ async fn sender_profile_picture_url(&self) -> Option<&str> {
+ self.0.sender_profile_picture_url.as_deref()
+ }
+}
+
+/// GraphQL wrapper for document comment metadata.
+pub struct GraphqlCommentedOnDocumentMetadata(CommentedOnDocumentMetadata);
+
+/// Metadata for a comment on a document.
+#[Object]
+impl GraphqlCommentedOnDocumentMetadata {
+ /// Document name.
+ async fn document_name(&self) -> &str {
+ &self.0.document_name
+ }
+
+ /// Document owner identifier.
+ async fn owner(&self) -> String {
+ self.0.owner.to_string()
+ }
+
+ /// Document file type.
+ async fn file_type(&self) -> Option<&str> {
+ self.0.file_type.as_deref()
+ }
+
+ /// Document subtype.
+ async fn sub_type(&self) -> Option<GraphqlNotificationDocumentSubType> {
+ self.0.sub_type.clone().map(Into::into)
+ }
+
+ /// Comment identifier.
+ async fn comment_id(&self) -> i64 {
+ self.0.comment_id
+ }
+
+ /// Comment thread identifier.
+ async fn thread_id(&self) -> i64 {
+ self.0.thread_id
+ }
+
+ /// Comment text.
+ async fn text(&self) -> &str {
+ &self.0.text
+ }
+
+ /// Sender profile-picture URL.
+ async fn sender_profile_picture_url(&self) -> Option<&str> {
+ self.0.sender_profile_picture_url.as_deref()
+ }
+}
+
+/// GraphQL wrapper for channel invitation metadata.
+pub struct GraphqlChannelInviteMetadata(ChannelInviteMetadata);
+
+/// Metadata for a channel invitation.
+#[Object]
+impl GraphqlChannelInviteMetadata {
+ /// Inviting user identifier.
+ async fn invited_by(&self) -> String {
+ self.0.invited_by.to_string()
+ }
+
+ /// Channel name.
+ async fn channel_name(&self) -> &str {
+ &self.0.channel_name
+ }
+
+ /// Message content associated with the invitation.
+ async fn message_content(&self) -> Option<&str> {
+ self.0.message_content.as_deref()
+ }
+
+ /// Sender profile-picture URL.
+ async fn sender_profile_picture_url(&self) -> Option<&str> {
+ self.0.sender_profile_picture_url.as_deref()
+ }
+}
+
+/// GraphQL wrapper for sent channel message metadata.
+pub struct GraphqlChannelMessageSendMetadata(ChannelMessageSendMetadata);
+
+/// Metadata for a newly sent channel message.
+#[Object]
+impl GraphqlChannelMessageSendMetadata {
+ /// Sending user identifier.
+ async fn sender(&self) -> Option<String> {
+ self.0.sender.as_ref().map(ToString::to_string)
+ }
+
+ /// Display name for a non-user sender.
+ async fn sender_display_name(&self) -> Option<&str> {
+ self.0.sender_display_name.as_deref()
+ }
+
+ /// Message content.
+ async fn message_content(&self) -> &str {
+ &self.0.message_content
+ }
+
+ /// Message identifier.
+ async fn message_id(&self) -> &str {
+ &self.0.message_id
+ }
+
+ /// Whether the message has attachments.
+ async fn has_attachments(&self) -> bool {
+ self.0.has_attachments
+ }
+
+ /// Channel metadata.
+ #[graphql(flatten)]
+ async fn channel(&self) -> GraphqlChannelNotificationCommon {
+ GraphqlChannelNotificationCommon(self.0.common.clone())
+ }
+
+ /// Sender profile-picture URL.
+ async fn sender_profile_picture_url(&self) -> Option<&str> {
+ self.0.sender_profile_picture_url.as_deref()
+ }
+}
+
+/// GraphQL wrapper for channel reply metadata.
+pub struct GraphqlChannelReplyMetadata(ChannelReplyMetadata);
+
+/// Metadata for a reply to a channel thread.
+#[Object]
+impl GraphqlChannelReplyMetadata {
+ /// Thread identifier.
+ async fn thread_id(&self) -> &str {
+ &self.0.thread_id
+ }
+
+ /// Reply message identifier.
+ async fn message_id(&self) -> &str {
+ &self.0.message_id
+ }
+
+ /// Replying user identifier.
+ async fn user_id(&self) -> Option<String> {
+ self.0.user_id.as_ref().map(ToString::to_string)
+ }
+
+ /// Display name for a non-user sender.
+ async fn sender_display_name(&self) -> Option<&str> {
+ self.0.sender_display_name.as_deref()
+ }
+
+ /// Reply content.
+ async fn message_content(&self) -> &str {
+ &self.0.message_content
+ }
+
+ /// Whether the reply has attachments.
+ async fn has_attachments(&self) -> bool {
+ self.0.has_attachments
+ }
+
+ /// Root-message sender identifier.
+ async fn thread_parent_sender_id(&self) -> Option<String> {
+ self.0
+ .thread_parent_sender_id
+ .as_ref()
+ .map(ToString::to_string)
+ }
+
+ /// Channel metadata.
+ #[graphql(flatten)]
+ async fn channel(&self) -> GraphqlChannelNotificationCommon {
+ GraphqlChannelNotificationCommon(self.0.common.clone())
+ }
+
+ /// Sender profile-picture URL.
+ async fn sender_profile_picture_url(&self) -> Option<&str> {
+ self.0.sender_profile_picture_url.as_deref()
+ }
+}
+
+/// GraphQL wrapper for started call metadata.
+pub struct GraphqlCallStartedMetadata(CallStartedMetadata);
+
+/// Metadata for a started call.
+#[Object]
+impl GraphqlCallStartedMetadata {
+ /// Channel name.
+ async fn channel_name(&self) -> Option<&str> {
+ self.0.channel_name.as_deref()
+ }
+
+ /// Sender profile-picture URL.
+ async fn sender_profile_picture_url(&self) -> Option<&str> {
+ self.0.sender_profile_picture_url.as_deref()
+ }
+}
+
+/// GraphQL wrapper for newly received email metadata.
+pub struct GraphqlNewEmailMetadata(NewEmailMetadata);
+
+/// Metadata for a newly received email.
+#[Object]
+impl GraphqlNewEmailMetadata {
+ /// Sender email address.
+ async fn sender(&self) -> Option<&str> {
+ self.0.sender.as_deref()
+ }
+
+ /// Recipient email address.
+ async fn to_email(&self) -> &str {
+ &self.0.to_email
+ }
+
+ /// Email thread identifier.
+ async fn thread_id(&self) -> &str {
+ &self.0.thread_id
+ }
+
+ /// Email subject.
+ async fn subject(&self) -> &str {
+ &self.0.subject
+ }
+
+ /// Email snippet.
+ async fn snippet(&self) -> &str {
+ &self.0.snippet
+ }
+}
+
+/// GraphQL wrapper for inbox reauthentication metadata.
+pub struct GraphqlInboxReauthRequiredMetadata(InboxReauthRequiredMetadata);
+
+/// Metadata for an inbox that requires reauthentication.
+#[Object]
+impl GraphqlInboxReauthRequiredMetadata {
+ /// Inbox email address.
+ async fn email_address(&self) -> &str {
+ &self.0.email_address
+ }
+}
+
+/// GraphQL wrapper for team invitation metadata.
+pub struct GraphqlInviteToTeamMetadata(InviteToTeamMetadata);
+
+/// Metadata for a team invitation.
+#[Object]
+impl GraphqlInviteToTeamMetadata {
+ /// Team name.
+ async fn team_name(&self) -> &str {
+ &self.0.team_name
+ }
+
+ /// Team identifier.
+ async fn team_id(&self) -> ID {
+ ID(self.0.team_id.to_string())
+ }
+
+ /// Team invitation identifier.
+ async fn team_invite_id(&self) -> ID {
+ ID(self.0.team_invite_id.to_string())
+ }
+
+ /// Inviting user identifier.
+ async fn invited_by(&self) -> String {
+ self.0.invited_by.to_string()
+ }
+
+ /// Invited role.
+ async fn role(&self) -> Option<&str> {
+ self.0.role.as_deref()
+ }
+
+ /// Sender profile-picture URL.
+ async fn sender_profile_picture_url(&self) -> Option<String> {
+ self.0
+ .sender_profile_picture_url
+ .as_ref()
+ .map(ToString::to_string)
+ }
+}
+
+/// GraphQL wrapper for task assignment metadata.
+pub struct GraphqlTaskAssignedMetadata(TaskAssignedMetadata);
+
+/// Metadata for a task assignment.
+#[Object]
+impl GraphqlTaskAssignedMetadata {
+ /// Task identifier.
+ async fn task_id(&self) -> &str {
+ &self.0.task_id
+ }
+
+ /// Task name.
+ async fn task_name(&self) -> Option<&str> {
+ self.0.task_name.as_deref()
+ }
+
+ /// Task document subtype.
+ async fn sub_type(&self) -> Option<GraphqlNotificationDocumentSubType> {
+ self.0.sub_type.clone().map(Into::into)
+ }
+
+ /// Assigning user identifier.
+ async fn assigned_by(&self) -> String {
+ self.0.assigned_by.to_string()
+ }
+
+ /// Sender profile-picture URL.
+ async fn sender_profile_picture_url(&self) -> Option<&str> {
+ self.0.sender_profile_picture_url.as_deref()
+ }
+}
+
+/// GraphQL wrapper for reminder metadata.
+pub struct GraphqlReminderMetadata(ReminderMetadata);
+
+/// Metadata for a due reminder.
+#[Object]
+impl GraphqlReminderMetadata {
+ /// Reminder identifier.
+ async fn reminder_id(&self) -> ID {
+ ID(self.0.reminder_id.to_string())
+ }
+
+ /// Reminder description.
+ async fn description(&self) -> &str {
+ &self.0.description
+ }
+}
+
+/// GraphQL wrapper for calendar event reminder metadata.
+pub struct GraphqlCalendarEventReminderMetadata(CalendarEventReminderMetadata);
+
+/// Metadata for a due calendar event reminder.
+#[Object]
+impl GraphqlCalendarEventReminderMetadata {
+ /// Calendar event identifier.
+ async fn event_id(&self) -> ID {
+ ID(self.0.event_id.to_string())
+ }
+
+ /// Stable occurrence key of the event instance.
+ async fn occurrence_key(&self) -> &str {
+ &self.0.occurrence_key
+ }
+
+ /// Event display title.
+ async fn title(&self) -> &str {
+ &self.0.title
+ }
+
+ /// Timed event start in RFC 3339 format.
+ async fn starts_at(&self) -> Option<String> {
+ self.0.starts_at.map(|timestamp| timestamp.to_rfc3339())
+ }
+
+ /// Timed event end in RFC 3339 format.
+ async fn ends_at(&self) -> Option<String> {
+ self.0.ends_at.map(|timestamp| timestamp.to_rfc3339())
+ }
+
+ /// All-day event start date in ISO 8601 format.
+ async fn start_date(&self) -> Option<String> {
+ self.0.start_date.map(|date| date.to_string())
+ }
+
+ /// IANA time zone used to render the event.
+ async fn time_zone(&self) -> Option<&str> {
+ self.0.time_zone.as_deref()
+ }
+
+ /// Minutes before the event start when the alarm fires.
+ async fn minutes_before(&self) -> i32 {
+ self.0.minutes_before
+ }
+}
+
+/// GraphQL wrapper for AI response metadata.
+pub struct GraphqlAiResponseMetadata(AiResponseMetadata);
+
+/// Metadata for an AI response.
+#[Object]
+impl GraphqlAiResponseMetadata {
+ /// AI response summary.
+ async fn summary(&self) -> &str {
+ &self.0.summary
+ }
+
+ /// Response message identifier.
+ async fn message_id(&self) -> &str {
+ &self.0.message_id
+ }
+}
+
+/// GraphQL wrapper for GitHub pull-request lifecycle metadata.
+pub struct GraphqlGithubPrStatusChangedMetadata(GithubPrStatusChanged);
+
+/// Metadata for a GitHub pull-request lifecycle change.
+#[Object]
+impl GraphqlGithubPrStatusChangedMetadata {
+ /// Shared pull-request metadata.
+ #[graphql(flatten)]
+ async fn common(&self) -> GraphqlGithubPrNotificationCommon {
+ GraphqlGithubPrNotificationCommon(self.0.common.clone())
+ }
+
+ /// Current pull-request status.
+ async fn status(&self) -> GraphqlGithubPrEventStatus {
+ self.0.status.into()
+ }
+
+ /// Triggering webhook action.
+ async fn action(&self) -> GraphqlGithubPrEventAction {
+ self.0.action.into()
+ }
+
+ /// Previous pull-request status.
+ async fn previous_status(&self) -> Option<GraphqlGithubPrEventStatus> {
+ self.0.previous_status.map(Into::into)
+ }
+
+ /// Head branch.
+ async fn head_branch(&self) -> Option<&str> {
+ self.0.head_branch.as_deref()
+ }
+
+ /// Base branch.
+ async fn base_branch(&self) -> Option<&str> {
+ self.0.base_branch.as_deref()
+ }
+
+ /// Merge timestamp in RFC 3339 format.
+ async fn merged_at(&self) -> Option<String> {
+ self.0.merged_at.map(|timestamp| timestamp.to_rfc3339())
+ }
+}
+
+/// GraphQL wrapper for GitHub pull-request check-run metadata.
+pub struct GraphqlGithubPrCheckRunMetadata(GithubPrCheckRun);
+
+/// Metadata for a completed GitHub pull-request check run.
+#[Object]
+impl GraphqlGithubPrCheckRunMetadata {
+ /// Shared pull-request metadata.
+ #[graphql(flatten)]
+ async fn common(&self) -> GraphqlGithubPrNotificationCommon {
+ GraphqlGithubPrNotificationCommon(self.0.common.clone())
+ }
+
+ /// Check-run GitHub identifier.
+ async fn check_run_github_id(&self) -> ID {
+ ID(self.0.check_run_github_id.to_string())
+ }
+
+ /// Check name.
+ async fn check_name(&self) -> &str {
+ &self.0.check_name
+ }
+
+ /// Raw check status.
+ async fn check_status(&self) -> &str {
+ &self.0.check_status
+ }
+
+ /// Raw check conclusion.
+ async fn conclusion(&self) -> &str {
+ &self.0.conclusion
+ }
+
+ /// Normalized check state.
+ async fn state(&self) -> GraphqlGithubPrCheckRunState {
+ self.0.state.into()
+ }
+
+ /// Public check URL.
+ async fn check_url(&self) -> &str {
+ &self.0.check_url
+ }
+
+ /// Completion timestamp in RFC 3339 format.
+ async fn completed_at(&self) -> String {
+ self.0.completed_at.to_rfc3339()
+ }
+}
+
+/// GraphQL wrapper for GitHub review-request metadata.
+pub struct GraphqlGithubReviewRequestedMetadata(GithubReviewRequested);
+
+/// Metadata for a GitHub pull-request review request.
+#[Object]
+impl GraphqlGithubReviewRequestedMetadata {
+ /// Shared pull-request metadata.
+ #[graphql(flatten)]
+ async fn common(&self) -> GraphqlGithubPrNotificationCommon {
+ GraphqlGithubPrNotificationCommon(self.0.common.clone())
+ }
+
+ /// Requested reviewer GitHub login.
+ async fn requested_reviewer_github_login(&self) -> Option<&str> {
+ self.0.requested_reviewer_github_login.as_deref()
+ }
+
+ /// Requested reviewer GitHub user identifier.
+ async fn requested_reviewer_github_user_id(&self) -> Option<&str> {
+ self.0.requested_reviewer_github_user_id.as_deref()
+ }
+}
+
+/// GraphQL wrapper for GitHub pull-request comment metadata.
+pub struct GraphqlGithubPrCommentMetadata(GithubPrComment);
+
+/// Metadata for a GitHub pull-request comment.
+#[Object]
+impl GraphqlGithubPrCommentMetadata {
+ /// Shared pull-request metadata.
+ #[graphql(flatten)]
+ async fn common(&self) -> GraphqlGithubPrNotificationCommon {
+ GraphqlGithubPrNotificationCommon(self.0.common.clone())
+ }
+
+ /// Comment kind.
+ async fn comment_kind(&self) -> GraphqlGithubPrCommentKind {
+ self.0.comment_kind.into()
+ }
+
+ /// Comment GitHub identifier.
+ async fn comment_github_id(&self) -> Option<ID> {
+ self.0.comment_github_id.map(|id| ID(id.to_string()))
+ }
+
+ /// Public comment URL.
+ async fn comment_url(&self) -> Option<&str> {
+ self.0.comment_url.as_deref()
+ }
+
+ /// Truncated comment body.
+ async fn comment_snippet(&self) -> &str {
+ &self.0.comment_snippet
+ }
+}
+
+/// GraphQL wrapper for GitHub pull-request mention metadata.
+pub struct GraphqlGithubPrMentionMetadata(GithubPrMention);
+
+/// Metadata for a GitHub pull-request mention.
+#[Object]
+impl GraphqlGithubPrMentionMetadata {
+ /// Shared pull-request metadata.
+ #[graphql(flatten)]
+ async fn common(&self) -> GraphqlGithubPrNotificationCommon {
+ GraphqlGithubPrNotificationCommon(self.0.common.clone())
+ }
+
+ /// Mention location.
+ async fn location(&self) -> GraphqlGithubPrMentionLocation {
+ self.0.location.into()
+ }
+
+ /// Comment or review GitHub identifier.
+ async fn comment_github_id(&self) -> Option<ID> {
+ self.0.comment_github_id.map(|id| ID(id.to_string()))
+ }
+
+ /// Public URL for the mentioning text.
+ async fn comment_url(&self) -> Option<&str> {
+ self.0.comment_url.as_deref()
+ }
+
+ /// Truncated mentioning text.
+ async fn text_snippet(&self) -> &str {
+ &self.0.text_snippet
+ }
+}
+
+/// GraphQL wrapper for GitHub pull-request review metadata.
+pub struct GraphqlGithubPrReviewMetadata(GithubPrReview);
+
+/// Metadata for a GitHub pull-request review.
+#[Object]
+impl GraphqlGithubPrReviewMetadata {
+ /// Shared pull-request metadata.
+ #[graphql(flatten)]
+ async fn common(&self) -> GraphqlGithubPrNotificationCommon {
+ GraphqlGithubPrNotificationCommon(self.0.common.clone())
+ }
+
+ /// Review GitHub identifier.
+ async fn review_github_id(&self) -> Option<ID> {
+ self.0.review_github_id.map(|id| ID(id.to_string()))
+ }
+
+ /// Public review URL.
+ async fn review_url(&self) -> Option<&str> {
+ self.0.review_url.as_deref()
+ }
+
+ /// Review state.
+ async fn state(&self) -> GraphqlGithubPrReviewState {
+ self.0.state.into()
+ }
+
+ /// Truncated review body.
+ async fn review_snippet(&self) -> Option<&str> {
+ self.0.review_snippet.as_deref()
+ }
+}
+
+/// Typed GraphQL union containing every supported notification event payload.
+#[derive(Union)]
+pub enum GraphqlNotifEvent {
+ /// Channel mention metadata.
+ ChannelMention(GraphqlChannelMentionMetadata),
+ /// Document mention metadata.
+ DocumentMention(GraphqlDocumentMentionMetadata),
+ /// Document-comment mention metadata.
+ MentionedInDocumentComment(GraphqlMentionedInDocumentCommentMetadata),
+ /// Document-comment thread reply metadata.
+ RepliedToDocumentCommentThread(GraphqlRepliedToDocumentCommentThreadMetadata),
+ /// Document comment metadata.
+ CommentedOnDocument(GraphqlCommentedOnDocumentMetadata),
+ /// Channel invitation metadata.
+ ChannelInvite(GraphqlChannelInviteMetadata),
+ /// Channel message metadata.
+ ChannelMessageSend(GraphqlChannelMessageSendMetadata),
+ /// Channel reply metadata.
+ ChannelMessageReply(GraphqlChannelReplyMetadata),
+ /// Started-call metadata.
+ CallStarted(GraphqlCallStartedMetadata),
+ /// New-email metadata.
+ NewEmail(GraphqlNewEmailMetadata),
+ /// Inbox reauthentication metadata.
+ InboxReauthRequired(GraphqlInboxReauthRequiredMetadata),
+ /// Team invitation metadata.
+ InviteToTeam(GraphqlInviteToTeamMetadata),
+ /// Task assignment metadata.
+ TaskAssigned(GraphqlTaskAssignedMetadata),
+ /// Reminder metadata.
+ Reminder(GraphqlReminderMetadata),
+ /// Calendar event reminder metadata.
+ CalendarEventReminder(GraphqlCalendarEventReminderMetadata),
+ /// AI response metadata.
+ AiResponse(GraphqlAiResponseMetadata),
+ /// GitHub pull-request lifecycle metadata.
+ GithubPrStatusChanged(GraphqlGithubPrStatusChangedMetadata),
+ /// GitHub pull-request check-run metadata.
+ GithubPrCheckRun(GraphqlGithubPrCheckRunMetadata),
+ /// GitHub review-request metadata.
+ GithubReviewRequested(GraphqlGithubReviewRequestedMetadata),
+ /// GitHub pull-request comment metadata.
+ GithubPrComment(GraphqlGithubPrCommentMetadata),
+ /// GitHub pull-request mention metadata.
+ GithubPrMention(GraphqlGithubPrMentionMetadata),
+ /// GitHub pull-request review metadata.
+ GithubPrReview(GraphqlGithubPrReviewMetadata),
+}
+
+impl From<NotifEvent> for GraphqlNotifEvent {
+ fn from(value: NotifEvent) -> Self {
+ match value {
+ NotifEvent::ChannelMention(metadata) => {
+ Self::ChannelMention(GraphqlChannelMentionMetadata(metadata))
+ }
+ NotifEvent::DocumentMention(metadata) => {
+ Self::DocumentMention(GraphqlDocumentMentionMetadata(metadata))
+ }
+ NotifEvent::MentionedInDocumentComment(metadata) => Self::MentionedInDocumentComment(
+ GraphqlMentionedInDocumentCommentMetadata(metadata),
+ ),
+ NotifEvent::RepliedToDocumentCommentThread(metadata) => {
+ Self::RepliedToDocumentCommentThread(GraphqlRepliedToDocumentCommentThreadMetadata(
+ metadata,
+ ))
+ }
+ NotifEvent::CommentedOnDocument(metadata) => {
+ Self::CommentedOnDocument(GraphqlCommentedOnDocumentMetadata(metadata))
+ }
+ NotifEvent::ChannelInvite(metadata) => {
+ Self::ChannelInvite(GraphqlChannelInviteMetadata(metadata))
+ }
+ NotifEvent::ChannelMessageSend(metadata) => {
+ Self::ChannelMessageSend(GraphqlChannelMessageSendMetadata(metadata))
+ }
+ NotifEvent::ChannelMessageReply(metadata) => {
+ Self::ChannelMessageReply(GraphqlChannelReplyMetadata(metadata))
+ }
+ NotifEvent::CallStarted(metadata) => {
+ Self::CallStarted(GraphqlCallStartedMetadata(metadata))
+ }
+ NotifEvent::NewEmail(metadata) => Self::NewEmail(GraphqlNewEmailMetadata(metadata)),
+ NotifEvent::InboxReauthRequired(metadata) => {
+ Self::InboxReauthRequired(GraphqlInboxReauthRequiredMetadata(metadata))
+ }
+ NotifEvent::InviteToTeam(metadata) => {
+ Self::InviteToTeam(GraphqlInviteToTeamMetadata(metadata))
+ }
+ NotifEvent::TaskAssigned(metadata) => {
+ Self::TaskAssigned(GraphqlTaskAssignedMetadata(metadata))
+ }
+ NotifEvent::Reminder(metadata) => Self::Reminder(GraphqlReminderMetadata(metadata)),
+ NotifEvent::CalendarEventReminder(metadata) => {
+ Self::CalendarEventReminder(GraphqlCalendarEventReminderMetadata(metadata))
+ }
+ NotifEvent::AiResponse(metadata) => {
+ Self::AiResponse(GraphqlAiResponseMetadata(metadata))
+ }
+ NotifEvent::GithubPrStatusChanged(metadata) => {
+ Self::GithubPrStatusChanged(GraphqlGithubPrStatusChangedMetadata(metadata))
+ }
+ NotifEvent::GithubPrCheckRun(metadata) => {
+ Self::GithubPrCheckRun(GraphqlGithubPrCheckRunMetadata(metadata))
+ }
+ NotifEvent::GithubReviewRequested(metadata) => {
+ Self::GithubReviewRequested(GraphqlGithubReviewRequestedMetadata(metadata))
+ }
+ NotifEvent::GithubPrComment(metadata) => {
+ Self::GithubPrComment(GraphqlGithubPrCommentMetadata(metadata))
+ }
+ NotifEvent::GithubPrMention(metadata) => {
+ Self::GithubPrMention(GraphqlGithubPrMentionMetadata(metadata))
+ }
+ NotifEvent::GithubPrReview(metadata) => {
+ Self::GithubPrReview(GraphqlGithubPrReviewMetadata(metadata))
+ }
+ }
+ }
+}
diff --git a/crates/graphql_notification/src/objects.rs b/crates/graphql_notification/src/objects.rs
index b3320e1d84..94cc54cb9e 100644
--- a/crates/graphql_notification/src/objects.rs
+++ b/crates/graphql_notification/src/objects.rs
@@ -1,9 +1,15 @@
use async_graphql::{Context, ID, Json, Object, dataloader::DataLoader};
use graphql_common::GraphqlSoupEntityType;
+use model_notifications::NotifEvent;
use notification::domain::models::UserNotificationRow;
-use serde_json::Value;
-use crate::loaders::{EntityNotificationsLoader, SoupNotificationEdgeReader};
+#[cfg(test)]
+mod test;
+
+use crate::{
+ GraphqlNotifEvent,
+ loaders::{EntityNotificationsLoader, SoupNotificationEdgeReader},
+};
/// GraphQL notification attached to a Soup entity.
pub struct GraphqlSoupNotification(UserNotificationRow<serde_json::Value>);
@@ -14,6 +20,54 @@ impl From<UserNotificationRow<serde_json::Value>> for GraphqlSoupNotification {
}
}
+impl GraphqlSoupNotification {
+ /// Converts a recipient-scoped realtime payload into the shared notification GraphQL type.
+ pub(crate) fn from_realtime(
+ owner_id: macro_user_id::user_id::MacroUserIdStr<'static>,
+ value: notification::domain::models::queue_message::RealtimeNotif<NotifEvent>,
+ ) -> Self {
+ let notification::domain::models::queue_message::RealtimeNotif {
+ notification_id,
+ notification_event_type,
+ entity,
+ sent,
+ done,
+ created_at,
+ viewed_at,
+ updated_at,
+ deleted_at,
+ notification_metadata,
+ sender_id,
+ } = value;
+ let mut tagged = serde_json::to_value(notification_metadata).unwrap_or_else(|error| {
+ tracing::error!(
+ error = ?error,
+ "failed to serialize realtime notification metadata"
+ );
+ serde_json::Value::Null
+ });
+ let notification_metadata = tagged
+ .get_mut("content")
+ .map(serde_json::Value::take)
+ .unwrap_or(serde_json::Value::Null);
+
+ Self(UserNotificationRow {
+ owner_id,
+ notification_id,
+ notification_event_type,
+ entity,
+ sent,
+ done,
+ created_at,
+ viewed_at,
+ updated_at,
+ deleted_at,
+ notification_metadata,
+ sender_id,
+ })
+ }
+}
+
/// A notification associated with a Soup entity.
#[Object]
impl GraphqlSoupNotification {
@@ -72,9 +126,24 @@ impl GraphqlSoupNotification {
self.0.sender_id.as_ref().map(|sender| sender.to_string())
}
- /// Event-specific notification metadata.
- async fn metadata(&self) -> Json<Value> {
- Json(self.0.notification_metadata.clone())
+ /// Raw event-specific notification metadata.
+ #[graphql(deprecation = "Use typedMetadata with union inline fragments")]
+ async fn metadata(&self) -> Json<&serde_json::Value> {
+ Json(&self.0.notification_metadata)
+ }
+
+ /// Typed event-specific notification metadata.
+ async fn typed_metadata(&self) -> async_graphql::Result<Option<GraphqlNotifEvent>> {
+ self.0
+ .deserialize_metadata_ref::<NotifEvent>()
+ .map(|metadata| Some(metadata.into()))
+ .map_err(|error| {
+ tracing::error!(
+ error = ?error,
+ "failed to deserialize notification metadata"
+ );
+ async_graphql::Error::new("notification metadata is unavailable")
+ })
}
}
diff --git a/crates/graphql_notification/src/objects/test.rs b/crates/graphql_notification/src/objects/test.rs
new file mode 100644
index 0000000000..8ca32779ba
--- /dev/null
+++ b/crates/graphql_notification/src/objects/test.rs
@@ -0,0 +1,65 @@
+use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema};
+use chrono::Utc;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType;
+use notification::domain::models::UserNotificationRow;
+use serde_json::json;
+
+use super::GraphqlSoupNotification;
+
+struct Query {
+ notification: GraphqlSoupNotification,
+}
+
+#[Object]
+impl Query {
+ async fn notification(&self) -> &GraphqlSoupNotification {
+ &self.notification
+ }
+}
+
+fn notification(metadata: serde_json::Value) -> GraphqlSoupNotification {
+ UserNotificationRow {
+ owner_id: MacroUserIdStr::try_from("macro|[email protected]".to_string()).unwrap(),
+ notification_id: uuid::Uuid::from_u128(1),
+ notification_event_type: "unknown_notification".to_string(),
+ entity: EntityType::Document.with_entity_string("document-1".to_string()),
+ sent: true,
+ done: false,
+ created_at: Utc::now(),
+ viewed_at: None,
+ updated_at: Utc::now(),
+ deleted_at: None,
+ notification_metadata: metadata,
+ sender_id: None,
+ }
+ .into()
+}
+
+#[tokio::test]
+async fn malformed_typed_metadata_is_nullable_and_returns_a_client_safe_error() {
+ let schema = Schema::new(
+ Query {
+ notification: notification(json!({"secret": "do not expose"})),
+ },
+ EmptyMutation,
+ EmptySubscription,
+ );
+
+ let response = schema
+ .execute("{ notification { id typedMetadata { __typename } } }")
+ .await;
+
+ assert_eq!(response.errors.len(), 1);
+ assert_eq!(
+ response.errors[0].message,
+ "notification metadata is unavailable"
+ );
+ assert!(!response.errors[0].message.contains("unknown_notification"));
+ let data = response.data.into_json().unwrap();
+ assert_eq!(
+ data["notification"]["id"],
+ uuid::Uuid::from_u128(1).to_string()
+ );
+ assert!(data["notification"]["typedMetadata"].is_null());
+}
diff --git a/crates/graphql_notification/src/subscriptions.rs b/crates/graphql_notification/src/subscriptions.rs
new file mode 100644
index 0000000000..77d5224d82
--- /dev/null
+++ b/crates/graphql_notification/src/subscriptions.rs
@@ -0,0 +1,79 @@
+#[cfg(test)]
+mod test;
+
+use std::sync::Arc;
+
+use async_graphql::{Context, Subscription};
+use graphql_common::require_authenticated_user;
+use model_notifications::NotifEvent;
+use notification::domain::{
+ models::queue_message::RealtimeNotif,
+ ports::{WebSocketNotificationSubscriptionExit, WebSocketNotificationSubscriptionService},
+};
+use tokio_stream::Stream;
+
+use crate::GraphqlSoupNotification;
+
+/// Subscribe to realtime notifications addressed to the authenticated user.
+pub fn subscribe_to_notifications<S>(
+ service: &S,
+ ctx: &Context<'_>,
+) -> async_graphql::Result<
+ impl Stream<Item = async_graphql::Result<GraphqlSoupNotification>> + Send + 'static,
+>
+where
+ S: WebSocketNotificationSubscriptionService<RealtimeNotif<NotifEvent>>,
+{
+ let user_id = require_authenticated_user(ctx)?;
+ let mut subscription = service.subscribe(user_id.clone());
+
+ Ok(async_stream::stream! {
+ while let Some(notification) = subscription.recv().await {
+ let notification = Arc::unwrap_or_clone(notification);
+ yield Ok(GraphqlSoupNotification::from_realtime(user_id.clone(), notification));
+ }
+
+ match subscription.exit_reason().await {
+ WebSocketNotificationSubscriptionExit::SlowConsumer => {
+ yield Err(async_graphql::Error::new(
+ "notification subscription closed because the client was too slow",
+ ));
+ }
+ WebSocketNotificationSubscriptionExit::Lagging { .. } => {
+ yield Err(async_graphql::Error::new(
+ "notification subscription closed after falling behind",
+ ));
+ }
+ WebSocketNotificationSubscriptionExit::Closed => {}
+ }
+ })
+}
+
+/// Root GraphQL adapter for realtime notification subscriptions.
+pub struct NotificationSubscriptionRoot<S> {
+ /// User-scoped notification subscription service.
+ service: S,
+}
+
+impl<S> NotificationSubscriptionRoot<S> {
+ /// Creates a notification subscription root backed by `service`.
+ pub fn new(service: S) -> Self {
+ Self { service }
+ }
+}
+
+#[Subscription]
+impl<S> NotificationSubscriptionRoot<S>
+where
+ S: WebSocketNotificationSubscriptionService<RealtimeNotif<NotifEvent>>,
+{
+ /// Subscribe to realtime notifications for the authenticated user.
+ async fn notification_updates(
+ &self,
+ ctx: &Context<'_>,
+ ) -> async_graphql::Result<
+ impl Stream<Item = async_graphql::Result<GraphqlSoupNotification>> + 'static,
+ > {
+ subscribe_to_notifications(&self.service, ctx)
+ }
+}
diff --git a/crates/graphql_notification/src/subscriptions/test.rs b/crates/graphql_notification/src/subscriptions/test.rs
new file mode 100644
index 0000000000..937c211e29
--- /dev/null
+++ b/crates/graphql_notification/src/subscriptions/test.rs
@@ -0,0 +1,179 @@
+use std::{collections::VecDeque, sync::Mutex};
+
+use async_graphql::{EmptyMutation, Object, Schema};
+use chrono::Utc;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType;
+use model_notifications::{NotifEvent, TaskAssignedMetadata};
+use notification::domain::{
+ models::queue_message::RealtimeNotif,
+ ports::{
+ WebSocketNotificationSubscription, WebSocketNotificationSubscriptionExit,
+ WebSocketNotificationSubscriptionService,
+ },
+};
+
+use super::*;
+
+struct Query;
+
+#[Object]
+impl Query {
+ async fn value(&self) -> bool {
+ true
+ }
+}
+
+struct TestSubscriptionService {
+ subscriptions:
+ Mutex<VecDeque<WebSocketNotificationSubscription<Arc<RealtimeNotif<NotifEvent>>>>>,
+}
+
+impl WebSocketNotificationSubscriptionService<RealtimeNotif<NotifEvent>>
+ for TestSubscriptionService
+{
+ fn subscribe(
+ &self,
+ _user_id: MacroUserIdStr<'static>,
+ ) -> WebSocketNotificationSubscription<Arc<RealtimeNotif<NotifEvent>>> {
+ self.subscriptions
+ .lock()
+ .expect("subscription lock")
+ .pop_front()
+ .expect("subscription opened once")
+ }
+}
+
+fn subscription(
+ exit: WebSocketNotificationSubscriptionExit,
+) -> (
+ tokio::sync::mpsc::Sender<Arc<RealtimeNotif<NotifEvent>>>,
+ WebSocketNotificationSubscription<Arc<RealtimeNotif<NotifEvent>>>,
+) {
+ let (sender, receiver) = tokio::sync::mpsc::channel(1);
+ let (exit_sender, exit_receiver) = tokio::sync::oneshot::channel();
+ exit_sender.send(exit).expect("exit receiver remains open");
+ (
+ sender,
+ WebSocketNotificationSubscription::from_parts(receiver, exit_receiver),
+ )
+}
+
+#[tokio::test]
+async fn notification_updates_streams_realtime_notifications() {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let assigned_by = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let (sender, subscription) = subscription(WebSocketNotificationSubscriptionExit::Closed);
+ let service = TestSubscriptionService {
+ subscriptions: Mutex::new(VecDeque::from([subscription])),
+ };
+ let schema = Schema::new(
+ Query,
+ EmptyMutation,
+ NotificationSubscriptionRoot::new(service),
+ );
+ let mut responses = Box::pin(schema.execute_stream(
+ async_graphql::Request::new(
+ "subscription { notificationUpdates { id eventType entityType entityId typedMetadata { __typename ... on GraphqlTaskAssignedMetadata { taskId taskName assignedBy } } } }",
+ )
+ .data(user_id),
+ ));
+
+ let notification_id = uuid::Uuid::from_u128(42);
+ sender
+ .send(Arc::new(RealtimeNotif {
+ notification_id,
+ notification_event_type: "task_assigned".to_string(),
+ entity: EntityType::Document.with_entity_string("task-1".to_string()),
+ sent: true,
+ done: false,
+ created_at: Utc::now(),
+ viewed_at: None,
+ updated_at: Utc::now(),
+ deleted_at: None,
+ notification_metadata: NotifEvent::TaskAssigned(TaskAssignedMetadata {
+ task_id: "task-1".to_string(),
+ task_name: Some("Test task".to_string()),
+ sub_type: None,
+ assigned_by,
+ sender_profile_picture_url: None,
+ }),
+ sender_id: None,
+ }))
+ .await
+ .expect("subscription remains open");
+
+ let response = futures::StreamExt::next(&mut responses)
+ .await
+ .expect("subscription response");
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().expect("response data is JSON");
+ assert_eq!(
+ data["notificationUpdates"]["id"],
+ notification_id.to_string()
+ );
+ assert_eq!(data["notificationUpdates"]["eventType"], "task_assigned");
+ assert_eq!(data["notificationUpdates"]["entityType"], "DOCUMENT");
+ assert_eq!(data["notificationUpdates"]["entityId"], "task-1");
+ assert_eq!(
+ data["notificationUpdates"]["typedMetadata"]["__typename"],
+ "GraphqlTaskAssignedMetadata"
+ );
+ assert_eq!(
+ data["notificationUpdates"]["typedMetadata"]["taskId"],
+ "task-1"
+ );
+ assert_eq!(
+ data["notificationUpdates"]["typedMetadata"]["taskName"],
+ "Test task"
+ );
+ assert_eq!(
+ data["notificationUpdates"]["typedMetadata"]["assignedBy"],
+ );
+}
+
+#[tokio::test]
+async fn notification_updates_reports_slow_consumers() {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let (sender, subscription) = subscription(WebSocketNotificationSubscriptionExit::SlowConsumer);
+ drop(sender);
+ let service = TestSubscriptionService {
+ subscriptions: Mutex::new(VecDeque::from([subscription])),
+ };
+ let schema = Schema::new(
+ Query,
+ EmptyMutation,
+ NotificationSubscriptionRoot::new(service),
+ );
+ let mut responses = Box::pin(schema.execute_stream(
+ async_graphql::Request::new("subscription { notificationUpdates { id } }").data(user_id),
+ ));
+
+ let response = futures::StreamExt::next(&mut responses)
+ .await
+ .expect("terminal subscription response");
+ assert_eq!(
+ response.errors[0].message,
+ "notification subscription closed because the client was too slow"
+ );
+}
+
+#[tokio::test]
+async fn notification_updates_requires_an_authenticated_user() {
+ let service = TestSubscriptionService {
+ subscriptions: Mutex::new(VecDeque::new()),
+ };
+ let schema = Schema::new(
+ Query,
+ EmptyMutation,
+ NotificationSubscriptionRoot::new(service),
+ );
+ let mut responses =
+ Box::pin(schema.execute_stream("subscription { notificationUpdates { id } }"));
+
+ let response = futures::StreamExt::next(&mut responses)
+ .await
+ .expect("subscription response");
+ assert_eq!(response.errors[0].message, "authentication required");
+}
diff --git a/crates/notification/Cargo.toml b/crates/notification/Cargo.toml
index 3456f2e44c..23ec7549b7 100644
--- a/crates/notification/Cargo.toml
+++ b/crates/notification/Cargo.toml
@@ -28,6 +28,7 @@ aws-sdk-sesv2 = { workspace = true }
aws-sdk-sns = { workspace = true }
aws-sdk-sqs = { workspace = true }
axum = { workspace = true, optional = true }
+broadcast = { path = "../broadcast" }
chrono = { workspace = true }
cowlike = { path = "../cowlike" }
either = { workspace = true }
@@ -35,8 +36,9 @@ futures = { workspace = true }
hex = { workspace = true }
hmac = { workspace = true }
itertools = { workspace = true }
+kafka_util = { path = "../kafka_util" }
last_online_tracker = { path = "../last_online_tracker" }
-macro_event_broker = { path = "../macro_event_broker", default-features = false }
+macro_event_broker = { path = "../macro_event_broker" }
macro_event_topics = { path = "../macro_event_topics" }
macro_authorization = { path = "../macro_authorization", default-features = false, features = [
"axum",
@@ -55,6 +57,7 @@ redis = { workspace = true, features = [
"tokio-comp",
"tokio-rustls-comp",
] }
+rdkafka = { workspace = true }
reqwest = { workspace = true }
rootcause = { workspace = true }
schemars = { workspace = true, optional = true }
@@ -65,6 +68,7 @@ sqlx = { workspace = true }
strum = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["time"] }
+tokio-retry = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }
utoipa = { workspace = true, optional = true }
diff --git a/crates/notification/src/domain/models.rs b/crates/notification/src/domain/models.rs
index 65eb68bee9..65dd6d85bf 100644
--- a/crates/notification/src/domain/models.rs
+++ b/crates/notification/src/domain/models.rs
@@ -272,6 +272,27 @@ impl<T: Notification> TaggedContent<T> {
}
impl UserNotificationRow<serde_json::Value> {
+ /// Deserialize the row's tagged metadata without cloning or consuming the row.
+ pub fn deserialize_metadata_ref<T: DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
+ let mut encoded = Vec::new();
+ {
+ let mut serializer = serde_json::Serializer::new(&mut encoded);
+ let mut map = serde::Serializer::serialize_map(&mut serializer, Some(2))?;
+ serde::ser::SerializeMap::serialize_entry(
+ &mut map,
+ "tag",
+ &self.notification_event_type,
+ )?;
+ serde::ser::SerializeMap::serialize_entry(
+ &mut map,
+ "content",
+ &self.notification_metadata,
+ )?;
+ serde::ser::SerializeMap::end(map)?;
+ }
+ serde_json::from_slice(&encoded)
+ }
+
/// Wrap the raw JSON metadata in a [`TaggedContent`] using the row's
/// `notification_event_type` as the tag. This produces the adjacently-tagged
/// shape produced by [`UserNotificationRow::into_tagged`] +
diff --git a/crates/notification/src/domain/models/queue_message.rs b/crates/notification/src/domain/models/queue_message.rs
index 3760077c44..22341124e8 100644
--- a/crates/notification/src/domain/models/queue_message.rs
+++ b/crates/notification/src/domain/models/queue_message.rs
@@ -114,7 +114,7 @@ impl<'a> EmailNotification<'a> {
/// the value of the inner payload inside [ConnGatewayNotification]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-pub struct ConnGatewayInnerNotif<T> {
+pub struct RealtimeNotif<T> {
/// The notification ID.
pub notification_id: uuid::Uuid,
/// The notification event type string (e.g. "channel_mention").
@@ -136,26 +136,26 @@ pub struct ConnGatewayInnerNotif<T> {
/// When the notification was deleted.
pub deleted_at: Option<DateTime<Utc>>,
/// Deserialized notification metadata.
- pub notification_metadata: TaggedContent<T>,
+ pub notification_metadata: T,
/// The user who triggered the notification.
pub sender_id: Option<MacroUserIdStr<'static>>,
}
-/// Concrete schema type for [`ConnGatewayInnerNotif`] with `serde_json::Value` metadata.
+/// Concrete schema type for [`RealtimeNotif`] with `serde_json::Value` metadata.
///
/// Used for OpenAPI schema generation — serializes identically to
-/// `ConnGatewayInnerNotif<serde_json::Value>`.
+/// `RealtimeNotif<serde_json::Value>`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(transparent)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
-pub struct ConnGatewayNotificationPayload(pub ConnGatewayInnerNotif<serde_json::Value>);
+pub struct ConnGatewayNotificationPayload(pub RealtimeNotif<TaggedContent<serde_json::Value>>);
/// Connection gateway (WebSocket) notification payload.
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
pub(crate) struct ConnGatewayNotification<'a, T> {
/// The notification payload to send.
- pub(crate) notif: ConnGatewayInnerNotif<T>,
+ pub(crate) notif: RealtimeNotif<TaggedContent<T>>,
/// The recipients to deliver to.
pub(crate) recipients: Vec<MacroUserIdStr<'a>>,
}
@@ -163,7 +163,7 @@ pub(crate) struct ConnGatewayNotification<'a, T> {
impl<'a, T: Clone> ConnGatewayNotification<'a, T> {
pub(crate) fn clone_from_request<U>(id: Uuid, req: &SendNotificationRequest<'a, T, U>) -> Self {
ConnGatewayNotification {
- notif: ConnGatewayInnerNotif {
+ notif: RealtimeNotif {
notification_id: id,
notification_event_type: req.req.notification.tag.as_ref().to_string(),
entity: req.req.notification_entity.clone().into_owned(),
@@ -187,7 +187,7 @@ impl<'a, T: Notification> ConnGatewayNotification<'a, T> {
pub fn testing_to_value(self) -> ConnGatewayNotification<'a, serde_json::Value> {
let ConnGatewayNotification {
notif:
- ConnGatewayInnerNotif {
+ RealtimeNotif {
notification_id,
notification_event_type,
entity,
@@ -204,7 +204,7 @@ impl<'a, T: Notification> ConnGatewayNotification<'a, T> {
} = self;
ConnGatewayNotification {
- notif: ConnGatewayInnerNotif {
+ notif: RealtimeNotif {
notification_id,
notification_event_type,
entity,
@@ -245,7 +245,7 @@ impl<'a, T, U> NotificationChannel<'a, T, U> {
}
NotificationChannel::ConnGateway(ConnGatewayNotification {
notif:
- ConnGatewayInnerNotif {
+ RealtimeNotif {
notification_id,
notification_event_type,
entity,
@@ -260,7 +260,7 @@ impl<'a, T, U> NotificationChannel<'a, T, U> {
},
recipients,
}) => NotificationChannel::ConnGateway(ConnGatewayNotification {
- notif: ConnGatewayInnerNotif {
+ notif: RealtimeNotif {
notification_id,
notification_event_type,
entity,
diff --git a/crates/notification/src/domain/models/websocket_notification_event.rs b/crates/notification/src/domain/models/websocket_notification_event.rs
index 6178d6ee5b..03d614560c 100644
--- a/crates/notification/src/domain/models/websocket_notification_event.rs
+++ b/crates/notification/src/domain/models/websocket_notification_event.rs
@@ -55,6 +55,13 @@ impl<T: Serialize + DeserializeOwned + Send + Sync> NotificationMacroEvent<T> {
event,
}
}
+
+ /// Returns the WebSocket delivery request carried by this event.
+ pub fn into_message(self) -> WebSocketNotificationMetadata<T> {
+ match self.event.event {
+ NotificationTopicEvent::WebSocketDeliveryRequested(metadata) => metadata,
+ }
+ }
}
impl<T: Serialize + DeserializeOwned + Send + Sync> MacroEvent for NotificationMacroEvent<T> {
@@ -72,3 +79,6 @@ impl<T: Serialize + DeserializeOwned + Send + Sync> MacroEvent for NotificationM
Self::with_event(key, event)
}
}
+
+/// WebSocket notification event decoded with an arbitrary JSON payload.
+pub type JsonNotificationMacroEvent = NotificationMacroEvent<serde_json::Value>;
diff --git a/crates/notification/src/domain/ports.rs b/crates/notification/src/domain/ports.rs
index d14673517e..6c52a12dfb 100644
--- a/crates/notification/src/domain/ports.rs
+++ b/crates/notification/src/domain/ports.rs
@@ -301,6 +301,103 @@ pub trait WebSocketSender: Send + Sync + 'static {
) -> impl Future<Output = Result<HashSet<MacroUserIdStr<'static>>, Report>> + Send;
}
+/// Receives WebSocket notification delivery requests with payloads decoded as `T`.
+pub trait WebSocketNotificationConsumer<T>: Send + Sync + 'static {
+ /// Waits for and returns the next WebSocket notification delivery request.
+ fn recv(
+ &self,
+ ) -> impl Future<
+ Output = Result<
+ crate::domain::models::websocket_notification_event::WebSocketNotificationMetadata<T>,
+ Report,
+ >,
+ > + Send;
+}
+
+/// Why a WebSocket notification subscription ended after its messages were drained.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum WebSocketNotificationSubscriptionExit {
+ /// The subscription closed normally.
+ Closed,
+ /// The subscriber's bounded buffer filled.
+ SlowConsumer,
+ /// The subscriber fell behind the shared broadcast buffer.
+ Lagging {
+ /// Number of messages skipped by the broadcast receiver.
+ skipped: u64,
+ },
+}
+
+/// A WebSocket notification receiver with independently observable completion status.
+pub struct WebSocketNotificationSubscription<T> {
+ receiver: tokio::sync::mpsc::Receiver<T>,
+ exit_reason: tokio::sync::oneshot::Receiver<WebSocketNotificationSubscriptionExit>,
+}
+
+impl<T> WebSocketNotificationSubscription<T> {
+ /// Creates a subscription from its message and exit-reason receivers.
+ pub fn from_parts(
+ receiver: tokio::sync::mpsc::Receiver<T>,
+ exit_reason: tokio::sync::oneshot::Receiver<WebSocketNotificationSubscriptionExit>,
+ ) -> Self {
+ Self {
+ receiver,
+ exit_reason,
+ }
+ }
+
+ /// Receives the next buffered notification.
+ pub async fn recv(&mut self) -> Option<T> {
+ self.receiver.recv().await
+ }
+
+ /// Returns why the forwarding task stopped after buffered notifications are drained.
+ pub async fn exit_reason(self) -> WebSocketNotificationSubscriptionExit {
+ self.exit_reason
+ .await
+ .unwrap_or(WebSocketNotificationSubscriptionExit::Closed)
+ }
+}
+
+/// Provides user-scoped subscriptions to received WebSocket notifications decoded as `T`.
+pub trait WebSocketNotificationSubscriptionService<T>: Send + Sync + 'static {
+ /// Subscribes to WebSocket notifications addressed to `user_id`.
+ fn subscribe(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> WebSocketNotificationSubscription<std::sync::Arc<T>>;
+}
+
+impl<S, T> WebSocketNotificationSubscriptionService<T> for std::sync::Arc<S>
+where
+ S: WebSocketNotificationSubscriptionService<T>,
+{
+ fn subscribe(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> WebSocketNotificationSubscription<std::sync::Arc<T>> {
+ self.as_ref().subscribe(user_id)
+ }
+}
+
+/// No-op WebSocket notification subscription service for schema-only consumers.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct NoopWebSocketNotificationSubscriptionService;
+
+impl<T: Send + Sync + 'static> WebSocketNotificationSubscriptionService<T>
+ for NoopWebSocketNotificationSubscriptionService
+{
+ fn subscribe(
+ &self,
+ _user_id: MacroUserIdStr<'static>,
+ ) -> WebSocketNotificationSubscription<std::sync::Arc<T>> {
+ let (_sender, receiver) = tokio::sync::mpsc::channel(1);
+ let (exit_reason_sender, exit_reason) = tokio::sync::oneshot::channel();
+ let _ = exit_reason_sender.send(WebSocketNotificationSubscriptionExit::Closed);
+ WebSocketNotificationSubscription::from_parts(receiver, exit_reason)
+ }
+}
+
use crate::domain::models::queue_message::EmailContent;
/// Port for email delivery.
diff --git a/crates/notification/src/domain/service.rs b/crates/notification/src/domain/service.rs
index 14924f9420..bb77bf9ad8 100644
--- a/crates/notification/src/domain/service.rs
+++ b/crates/notification/src/domain/service.rs
@@ -8,6 +8,7 @@ pub mod device;
mod egress;
mod ingress;
mod push_notification_event;
+mod realtime;
#[cfg(test)]
mod test;
mod voip;
@@ -23,6 +24,7 @@ pub use ingress::PlatformArnConfig;
pub use ingress::SqsNotificationIngress;
pub use push_notification_event::PushNotificationEventHandler;
pub use push_notification_event::PushNotificationEventService;
+pub use realtime::WebSocketNotificationConsumerService;
pub use voip::VoipPushServiceImpl;
/// Error returned when sending a notification fails.
diff --git a/crates/notification/src/domain/service/realtime.rs b/crates/notification/src/domain/service/realtime.rs
new file mode 100644
index 0000000000..b9e5c6e882
--- /dev/null
+++ b/crates/notification/src/domain/service/realtime.rs
@@ -0,0 +1,140 @@
+//! WebSocket notification consumer orchestration.
+
+#[cfg(test)]
+mod test;
+
+use std::{num::NonZeroUsize, sync::Arc, time::Duration};
+
+use broadcast::{BroadcastManager, GlobalSpawner};
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::prelude::{Report, ResultExt as _};
+use tokio_retry::{Retry, strategy::ExponentialBackoff};
+
+use crate::domain::{
+ models::websocket_notification_event::WebSocketNotificationMetadata,
+ ports::{
+ WebSocketNotificationConsumer, WebSocketNotificationSubscription,
+ WebSocketNotificationSubscriptionService,
+ },
+};
+
+/// Number of messages retained by each user-keyed broadcast channel.
+const BROADCAST_BUFFER_CAPACITY: NonZeroUsize = NonZeroUsize::new(64).unwrap();
+/// Number of messages buffered for each individual subscriber.
+const SUBSCRIBER_BUFFER_CAPACITY: NonZeroUsize = NonZeroUsize::new(16).unwrap();
+/// Total receive attempts before the consumer returns for supervision.
+const MAX_RECEIVE_ATTEMPTS: usize = 5;
+
+/// Retries after one, two, four, and eight seconds.
+fn receive_retry_strategy() -> impl Iterator<Item = Duration> {
+ ExponentialBackoff::from_millis(2)
+ .factor(500)
+ .take(MAX_RECEIVE_ATTEMPTS - 1)
+}
+
+/// Service for distributing received WebSocket notifications decoded as `T` to user-scoped
+/// subscribers.
+pub struct WebSocketNotificationConsumerService<C, T>
+where
+ C: WebSocketNotificationConsumer<T>,
+ T: Send + Sync + 'static,
+{
+ consumer: C,
+ broadcasts: BroadcastManager<GlobalSpawner, MacroUserIdStr<'static>, Arc<T>>,
+}
+
+impl<C, T> WebSocketNotificationConsumerService<C, T>
+where
+ C: WebSocketNotificationConsumer<T>,
+ T: Send + Sync + 'static,
+{
+ /// Creates a WebSocket notification consumer service backed by `consumer`.
+ pub fn new(consumer: C) -> Self {
+ Self {
+ consumer,
+ broadcasts: BroadcastManager::new(GlobalSpawner, BROADCAST_BUFFER_CAPACITY),
+ }
+ }
+
+ /// Subscribes to WebSocket notifications addressed to `user_id`.
+ ///
+ /// The returned subscription reports if its buffer fills, ensuring a slow subscriber cannot
+ /// delay the shared consumer or other subscribers.
+ #[must_use]
+ pub fn subscribe(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> WebSocketNotificationSubscription<Arc<T>> {
+ let (receiver, broadcast_exit_reason) = self
+ .broadcasts
+ .subscribe(user_id, SUBSCRIBER_BUFFER_CAPACITY)
+ .into_parts();
+ let (exit_reason_sender, exit_reason) = tokio::sync::oneshot::channel();
+ tokio::spawn(async move {
+ use crate::domain::ports::WebSocketNotificationSubscriptionExit;
+
+ let reason = match broadcast_exit_reason.await {
+ Ok(broadcast::ExitReason::SlowConsumer) => {
+ WebSocketNotificationSubscriptionExit::SlowConsumer
+ }
+ Ok(broadcast::ExitReason::Lagging { skipped }) => {
+ WebSocketNotificationSubscriptionExit::Lagging { skipped }
+ }
+ Ok(broadcast::ExitReason::ReceiverClosed | broadcast::ExitReason::SenderClosed)
+ | Err(_) => WebSocketNotificationSubscriptionExit::Closed,
+ };
+ let _ = exit_reason_sender.send(reason);
+ });
+ WebSocketNotificationSubscription::from_parts(receiver, exit_reason)
+ }
+
+ /// Receives notifications and distributes them to subscribers until reception fails.
+ ///
+ /// Callers should run this future in a supervised task. Notifications for users without active
+ /// subscribers are intentionally dropped.
+ #[tracing::instrument(skip(self), err)]
+ pub async fn run(&self) -> Result<(), Report> {
+ loop {
+ let WebSocketNotificationMetadata {
+ recipients,
+ notification,
+ } = Retry::start(receive_retry_strategy(), || self.consumer.recv())
+ .await
+ .context(format!(
+ "failed to receive WebSocket notification after {MAX_RECEIVE_ATTEMPTS} attempts"
+ ))?;
+ let notification = Arc::new(notification);
+
+ for recipient in recipients {
+ match self
+ .broadcasts
+ .publish(&recipient, Arc::clone(&notification))
+ {
+ Ok(subscriber_count) => tracing::trace!(
+ subscriber_count,
+ user_id = %recipient,
+ "distributed WebSocket notification"
+ ),
+ Err(_) => tracing::trace!(
+ user_id = %recipient,
+ "dropping WebSocket notification without subscribers"
+ ),
+ }
+ }
+ }
+ }
+}
+
+impl<C, T> WebSocketNotificationSubscriptionService<T>
+ for WebSocketNotificationConsumerService<C, T>
+where
+ C: WebSocketNotificationConsumer<T>,
+ T: Send + Sync + 'static,
+{
+ fn subscribe(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ) -> WebSocketNotificationSubscription<Arc<T>> {
+ WebSocketNotificationConsumerService::subscribe(self, user_id)
+ }
+}
diff --git a/crates/notification/src/domain/service/realtime/test.rs b/crates/notification/src/domain/service/realtime/test.rs
new file mode 100644
index 0000000000..4a1dccbd8f
--- /dev/null
+++ b/crates/notification/src/domain/service/realtime/test.rs
@@ -0,0 +1,133 @@
+use std::collections::VecDeque;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+
+use serde::{Deserialize, Serialize};
+
+use super::*;
+
+#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
+struct TestNotification {
+ kind: String,
+}
+
+struct FakeConsumer {
+ messages: Mutex<VecDeque<Result<WebSocketNotificationMetadata<TestNotification>, Report>>>,
+ calls: Arc<AtomicUsize>,
+}
+
+impl WebSocketNotificationConsumer<TestNotification> for FakeConsumer {
+ async fn recv(&self) -> Result<WebSocketNotificationMetadata<TestNotification>, Report> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ self.messages
+ .lock()
+ .expect("consumer messages lock")
+ .pop_front()
+ .unwrap_or_else(|| Err(rootcause::report!("consumer stopped")))
+ }
+}
+
+fn user(local: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(format!("macro|{local}@example.com")).expect("valid user ID")
+}
+
+#[tokio::test(start_paused = true)]
+async fn distributes_notifications_to_every_recipient_subscription() {
+ let one = user("one");
+ let two = user("two");
+ let notification = TestNotification {
+ kind: "channel_mention".to_string(),
+ };
+ let receive_calls = Arc::new(AtomicUsize::new(0));
+ let consumer = FakeConsumer {
+ messages: Mutex::new(VecDeque::from([
+ Err(rootcause::report!("transient receive failure")),
+ Ok(WebSocketNotificationMetadata {
+ recipients: vec![one.clone(), two.clone()],
+ notification,
+ }),
+ ])),
+ calls: Arc::clone(&receive_calls),
+ };
+ let service = Arc::new(WebSocketNotificationConsumerService::new(consumer));
+ let mut one_first = service.subscribe(one.clone());
+ let mut one_second = service.subscribe(one);
+ let mut two_receiver = service.subscribe(two);
+
+ let run_error = tokio::spawn({
+ let service = Arc::clone(&service);
+ async move { service.run().await }
+ })
+ .await
+ .expect("consumer task joins")
+ .expect_err("fake consumer eventually stops");
+
+ assert!(run_error.to_string().contains("failed to receive"));
+ assert_eq!(
+ receive_calls.load(Ordering::SeqCst),
+ 2 + MAX_RECEIVE_ATTEMPTS,
+ "a successful notification resets the receive retry strategy"
+ );
+ let one_first = one_first.recv().await.expect("first subscriber receives");
+ let one_second = one_second.recv().await.expect("second subscriber receives");
+ let two = two_receiver.recv().await.expect("other user receives");
+ assert_eq!(one_first.kind, "channel_mention");
+ assert!(Arc::ptr_eq(&one_first, &one_second));
+ assert!(Arc::ptr_eq(&one_first, &two));
+}
+
+#[tokio::test(start_paused = true)]
+async fn reports_slow_consumer_subscription_exit() {
+ let subscribed = user("subscribed");
+ let consumer = FakeConsumer {
+ messages: Mutex::new(VecDeque::new()),
+ calls: Arc::new(AtomicUsize::new(0)),
+ };
+ let service = WebSocketNotificationConsumerService::new(consumer);
+ let subscription = service.subscribe(subscribed.clone());
+
+ for index in 0..=SUBSCRIBER_BUFFER_CAPACITY.get() {
+ let notification = Arc::new(TestNotification {
+ kind: index.to_string(),
+ });
+ service
+ .broadcasts
+ .publish(&subscribed, notification)
+ .expect("subscriber remains until its buffer fills");
+ tokio::task::yield_now().await;
+ }
+
+ assert_eq!(
+ subscription.exit_reason().await,
+ crate::domain::ports::WebSocketNotificationSubscriptionExit::SlowConsumer
+ );
+}
+
+#[tokio::test(start_paused = true)]
+async fn ignores_recipients_without_subscribers() {
+ let subscribed = user("subscribed");
+ let consumer = FakeConsumer {
+ messages: Mutex::new(VecDeque::from([Ok(WebSocketNotificationMetadata {
+ recipients: vec![user("unsubscribed"), subscribed.clone()],
+ notification: TestNotification {
+ kind: "test".to_string(),
+ },
+ })])),
+ calls: Arc::new(AtomicUsize::new(0)),
+ };
+ let service = Arc::new(WebSocketNotificationConsumerService::new(consumer));
+ let mut receiver = service.subscribe(subscribed);
+
+ let _ = tokio::spawn({
+ let service = Arc::clone(&service);
+ async move { service.run().await }
+ })
+ .await
+ .expect("consumer task joins")
+ .expect_err("fake consumer eventually stops");
+
+ assert_eq!(
+ receiver.recv().await.expect("subscriber receives").kind,
+ "test"
+ );
+}
diff --git a/crates/notification/src/domain/service/test.rs b/crates/notification/src/domain/service/test.rs
index 1df04bc69c..1e2c1c8802 100644
--- a/crates/notification/src/domain/service/test.rs
+++ b/crates/notification/src/domain/service/test.rs
@@ -7,8 +7,8 @@ use crate::domain::models::email_notification_digest::ports::DigestBatch;
use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatcher};
use crate::domain::models::mobile::NotifCollapseKey;
use crate::domain::models::queue_message::{
- ConnGatewayInnerNotif, ConnGatewayNotification, EmailContent, EmailCreateBundle,
- NotificationChannel, QueueMessage, RawQueueMessage,
+ ConnGatewayNotification, EmailContent, EmailCreateBundle, NotificationChannel, QueueMessage,
+ RawQueueMessage, RealtimeNotif,
};
use crate::domain::models::request::{NotificationStatus, UpdateNotificationsRequest};
use crate::domain::models::{
@@ -1415,8 +1415,8 @@ fn create_egress_service<R: rate_limit::RateLimitService>(
}
}
-fn create_mock_notif<T: Notification>(meta: T) -> ConnGatewayInnerNotif<T> {
- ConnGatewayInnerNotif {
+fn create_mock_notif<T: Notification>(meta: T) -> RealtimeNotif<TaggedContent<T>> {
+ RealtimeNotif {
notification_id: Uuid::nil(),
notification_event_type: "testing".to_string(),
entity: EntityType::Document.with_entity_str("testing"),
diff --git a/crates/notification/src/outbound.rs b/crates/notification/src/outbound.rs
index 4a8e1270ed..7d67caf0a2 100644
--- a/crates/notification/src/outbound.rs
+++ b/crates/notification/src/outbound.rs
@@ -13,6 +13,8 @@ pub mod kafka_websocket;
pub mod last_online_checker;
pub mod message_receipt_repository;
pub mod mobile;
+/// Independent Kafka consumer for WebSocket notification delivery requests.
+pub mod notification_consumer;
/// Postgres LISTEN adapter for notification database events.
pub mod notification_events;
pub mod push_notification_checker;
diff --git a/crates/notification/src/outbound/notification_consumer.rs b/crates/notification/src/outbound/notification_consumer.rs
new file mode 100644
index 0000000000..3870454f87
--- /dev/null
+++ b/crates/notification/src/outbound/notification_consumer.rs
@@ -0,0 +1,135 @@
+//! Independent Kafka consumer for WebSocket notification delivery requests.
+//!
+//! Every process receives every message published after it starts because this adapter manually
+//! assigns all `macro.notifications` partitions without joining a durable consumer group. It does
+//! not commit offsets.
+
+#[cfg(test)]
+mod test;
+
+use std::{marker::PhantomData, time::Duration};
+
+use kafka_util::{InitialOffset, KafkaEventConsumer, Ungrouped};
+use macro_event_broker::{
+ EventBrokerError, KafkaConsumerAdapter, MacroEventCollection, MacroEventConsumerService,
+};
+use rdkafka::message::Message as _;
+use rootcause::prelude::{Report, ResultExt as _};
+use serde::{Serialize, de::DeserializeOwned};
+
+use crate::domain::{
+ models::websocket_notification_event::{
+ JsonNotificationMacroEvent, WebSocketNotificationMetadata,
+ },
+ ports::WebSocketNotificationConsumer,
+};
+
+/// Maximum time to wait for notification topic metadata during partition assignment.
+const TOPIC_METADATA_TIMEOUT: Duration = Duration::from_secs(10);
+
+type IndependentKafkaConsumer = KafkaConsumerAdapter<Ungrouped, DeclaredMacroEvent>;
+type NotificationEventConsumer =
+ MacroEventConsumerService<DeclaredMacroEvent, IndependentKafkaConsumer>;
+
+macro_event_broker::declare_topics!(DeclaredMacroEvent: JsonNotificationMacroEvent);
+
+/// Independent consumer of WebSocket notification delivery requests decoded as `T`.
+///
+/// This consumer starts at the end of every current `macro.notifications` partition, so it receives
+/// only messages published after construction. It does not join a durable consumer group or persist
+/// offsets. Partitions added after construction require a new consumer so they can be assigned.
+pub struct NotificationTopicConsumer<T>
+where
+ T: Serialize + DeserializeOwned + Send + Sync + 'static,
+{
+ consumer: NotificationEventConsumer,
+ payload: PhantomData<fn() -> T>,
+}
+
+impl<T> NotificationTopicConsumer<T>
+where
+ T: Serialize + DeserializeOwned + Send + Sync + 'static,
+{
+ /// Creates a consumer and assigns every current notification topic partition.
+ #[tracing::instrument(fields(brokers), err)]
+ pub fn from_env(brokers: &str) -> Result<Self, Report> {
+ let consumer = KafkaEventConsumer::<Ungrouped>::from_env(brokers)
+ .context("failed to create independent WebSocket notification consumer")?;
+ let consumer =
+ IndependentKafkaConsumer::new(consumer, InitialOffset::Latest, TOPIC_METADATA_TIMEOUT)
+ .context("failed to assign WebSocket notification topic partitions")?;
+
+ tracing::info!(
+ topics = ?DeclaredMacroEvent::topics(),
+ "independent WebSocket notification consumer listening"
+ );
+
+ Ok(Self {
+ consumer: NotificationEventConsumer::new(consumer),
+ payload: PhantomData,
+ })
+ }
+
+ /// Receives and decodes the next typed WebSocket notification event.
+ ///
+ /// This operation is cancel-safe. Unsupported schema versions are poison records and are
+ /// skipped. Other missing or malformed payload data is returned as an error.
+ pub async fn recv(&self) -> Result<WebSocketNotificationMetadata<T>, Report> {
+ loop {
+ let message = self
+ .consumer
+ .recv()
+ .await
+ .context("failed to receive WebSocket notification event")?;
+ let event = match message.decode_payload() {
+ Ok(event) => event,
+ Err(EventBrokerError::UnsupportedSchemaVersion {
+ topic,
+ expected,
+ actual,
+ }) => {
+ let kafka_message = message.inner();
+ tracing::warn!(
+ topic,
+ expected,
+ actual,
+ partition = kafka_message.partition(),
+ offset = kafka_message.offset(),
+ "dropping WebSocket notification event with unsupported schema version"
+ );
+ continue;
+ }
+ Err(error) => {
+ return Err(Report::new(error)
+ .context("failed to decode WebSocket notification event")
+ .into_dynamic());
+ }
+ };
+
+ return match event {
+ DeclaredMacroEvent::JsonNotificationMacroEvent(event) => {
+ let WebSocketNotificationMetadata {
+ recipients,
+ notification,
+ } = event.into_message();
+ let notification = serde_json::from_value(notification)
+ .context("failed to decode WebSocket notification payload")?;
+ Ok(WebSocketNotificationMetadata {
+ recipients,
+ notification,
+ })
+ }
+ };
+ }
+ }
+}
+
+impl<T> WebSocketNotificationConsumer<T> for NotificationTopicConsumer<T>
+where
+ T: Serialize + DeserializeOwned + Send + Sync + 'static,
+{
+ #[tracing::instrument(err, skip(self))]
+ async fn recv(&self) -> Result<WebSocketNotificationMetadata<T>, Report> {
+ NotificationTopicConsumer::recv(self).await
+ }
+}
diff --git a/crates/notification/src/outbound/notification_consumer/test.rs b/crates/notification/src/outbound/notification_consumer/test.rs
new file mode 100644
index 0000000000..fb644079b6
--- /dev/null
+++ b/crates/notification/src/outbound/notification_consumer/test.rs
@@ -0,0 +1,53 @@
+use macro_event_broker::{
+ EventBrokerError, MacroEventCollection as _, MessageParts, MessageWrapper,
+};
+
+use super::DeclaredMacroEvent;
+
+struct TestMessage {
+ payload: Vec<u8>,
+}
+
+impl MessageParts for TestMessage {
+ fn key(&self) -> Option<&str> {
+ Some("00000000-0000-0000-0000-000000000001")
+ }
+
+ fn payload(&self) -> Option<&[u8]> {
+ Some(&self.payload)
+ }
+
+ fn topic(&self) -> &str {
+ "macro.notifications"
+ }
+}
+
+#[test]
+fn assigns_only_the_typed_notifications_topic() {
+ assert_eq!(DeclaredMacroEvent::topics(), ["macro.notifications"]);
+}
+
+#[test]
+fn declared_topic_decoder_rejects_unsupported_schema_versions() {
+ let message = MessageWrapper::<_, DeclaredMacroEvent>::new(TestMessage {
+ payload: serde_json::to_vec(&serde_json::json!({
+ "event_id": "00000000-0000-0000-0000-000000000001",
+ "schema_version": 2,
+ "event_type": "notification.websocket_delivery_requested",
+ "metadata": {
+ "recipients": [],
+ "notification": {}
+ }
+ }))
+ .expect("serializable event"),
+ });
+
+ assert!(matches!(
+ message.decode_payload(),
+ Err(EventBrokerError::UnsupportedSchemaVersion {
+ expected: 1,
+ actual: 2,
+ ..
+ })
+ ));
+}
diff --git a/crates/soup_realtime/src/domain/service.rs b/crates/soup_realtime/src/domain/service.rs
index 91d5aa1e78..529d896140 100644
--- a/crates/soup_realtime/src/domain/service.rs
+++ b/crates/soup_realtime/src/domain/service.rs
@@ -67,6 +67,7 @@ where
) -> tokio::sync::mpsc::Receiver<Patch<Entity<'static>>> {
self.broadcasts
.subscribe(user_id, SUBSCRIBER_BUFFER_CAPACITY)
+ .into_receiver()
}
/// Receives patches and distributes them to subscribers until reception fails.
diff --git a/crates/soup_realtime/src/outbound/soup_consumer.rs b/crates/soup_realtime/src/outbound/soup_consumer.rs
index 4275130545..578cb53f62 100644
--- a/crates/soup_realtime/src/outbound/soup_consumer.rs
+++ b/crates/soup_realtime/src/outbound/soup_consumer.rs
@@ -11,15 +11,13 @@ use std::time::Duration;
use kafka_util::{InitialOffset, KafkaEventConsumer, Ungrouped};
use macro_event_broker::{
- Event, EventBrokerError, KafkaConsumerAdapter, MacroEventCollection, MacroEventConsumerService,
- MessageParts, Topic, TopicEvent,
+ EventBrokerError, KafkaConsumerAdapter, MacroEventCollection, MacroEventConsumerService,
};
use rdkafka::message::Message as _;
use rootcause::prelude::{Report, ResultExt as _};
-use serde::{Deserialize, Serialize};
use crate::domain::{
- models::{SoupMacroEvent, SoupRealtimeMessage, SoupTopicEvent},
+ models::{SoupMacroEvent, SoupRealtimeMessage},
ports::SoupRealtimeConsumer,
};
@@ -31,31 +29,6 @@ type SoupEventConsumer = MacroEventConsumerService<DeclaredMacroEvent, Independe
macro_event_broker::declare_topics!(DeclaredMacroEvent: SoupMacroEvent);
-#[derive(Deserialize, Serialize)]
-struct SchemaVersionPayload {}
-
-impl TopicEvent for SchemaVersionPayload {
- type Topic = <SoupTopicEvent as TopicEvent>::Topic;
-
- const SCHEMA_VERSION: u8 = SoupTopicEvent::SCHEMA_VERSION;
-}
-
-fn validate_soup_schema(message: &impl MessageParts) -> Result<(), EventBrokerError> {
- let payload = message
- .payload()
- .ok_or(EventBrokerError::MissingMessagePayload)?;
- let actual = Event::<SchemaVersionPayload>::decode(payload)?.schema_version;
- let expected = SoupTopicEvent::SCHEMA_VERSION;
- if actual != expected {
- return Err(EventBrokerError::UnsupportedSchemaVersion {
- topic: <<SoupTopicEvent as TopicEvent>::Topic as Topic>::TOPIC_STR,
- expected,
- actual,
- });
- }
- Ok(())
-}
-
/// Independent consumer of recipient-targeted Soup messages.
///
/// This consumer starts at the end of every current `macro.soup` partition, so
@@ -98,14 +71,14 @@ impl SoupTopicConsumer {
.recv()
.await
.context("failed to receive realtime Soup event")?;
- let kafka_message = message.inner();
- match validate_soup_schema(kafka_message) {
- Ok(()) => {}
+ let event = match message.decode_payload() {
+ Ok(event) => event,
Err(EventBrokerError::UnsupportedSchemaVersion {
topic,
expected,
actual,
}) => {
+ let kafka_message = message.inner();
tracing::warn!(
topic,
expected,
@@ -118,14 +91,11 @@ impl SoupTopicConsumer {
}
Err(error) => {
return Err(Report::new(error)
- .context("failed to decode realtime Soup event envelope")
+ .context("failed to decode realtime Soup event")
.into_dynamic());
}
- }
+ };
- let event = message
- .decode_payload()
- .context("failed to decode realtime Soup event")?;
return match event {
DeclaredMacroEvent::SoupMacroEvent(event) => Ok(event.into_message()),
};
diff --git a/crates/soup_realtime/src/outbound/soup_consumer/test.rs b/crates/soup_realtime/src/outbound/soup_consumer/test.rs
index 3c154722a3..b985568204 100644
--- a/crates/soup_realtime/src/outbound/soup_consumer/test.rs
+++ b/crates/soup_realtime/src/outbound/soup_consumer/test.rs
@@ -1,6 +1,8 @@
-use macro_event_broker::{EventBrokerError, MacroEventCollection as _, MessageParts};
+use macro_event_broker::{
+ EventBrokerError, MacroEventCollection as _, MessageParts, MessageWrapper,
+};
-use super::{DeclaredMacroEvent, validate_soup_schema};
+use super::DeclaredMacroEvent;
struct TestMessage {
payload: Vec<u8>,
@@ -26,19 +28,25 @@ fn assigns_only_the_typed_soup_topic() {
}
#[test]
-fn classifies_v1_soup_events_as_unsupported_before_decoding_the_old_payload() {
- let message = TestMessage {
+fn declared_topic_decoder_rejects_unsupported_schema_versions() {
+ let message = MessageWrapper::<_, DeclaredMacroEvent>::new(TestMessage {
payload: serde_json::to_vec(&serde_json::json!({
"event_id": "00000000-0000-0000-0000-000000000001",
"schema_version": 1,
- "event_type": "soup.item.updated",
- "metadata": {}
+ "event_type": "soup.updated",
+ "metadata": [
+ {
+ "entity_type": "document",
+ "entity_id": "00000000-0000-0000-0000-000000000001"
+ }
+ ]
}))
.expect("serializable event"),
- };
+ });
assert!(matches!(
- validate_soup_schema(&message),
+ message.decode_payload(),
Err(EventBrokerError::UnsupportedSchemaVersion {
expected: 2,
actual: 1,
diff --git a/packages/sdk/generated/notification/index.ts b/packages/sdk/generated/notification/index.ts
index 6bfb74761f..2c57fb7350 100644
--- a/packages/sdk/generated/notification/index.ts
+++ b/packages/sdk/generated/notification/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AiResponseMetadata, ApiUserNotification, BulkDeleteUserNotificationsV2Data, BulkDeleteUserNotificationsV2Error, BulkDeleteUserNotificationsV2Errors, BulkDeleteUserNotificationsV2Responses, BulkGetByEventItemIdsRequest, BulkGetTypedNotificationsByEventItemIdsData, BulkGetTypedNotificationsByEventItemIdsError, BulkGetTypedNotificationsByEventItemIdsErrors, BulkGetTypedNotificationsByEventItemIdsResponse, BulkGetTypedNotificationsByEventItemIdsResponses, BulkMarkNotificationsDoneData, BulkMarkNotificationsDoneError, BulkMarkNotificationsDoneErrors, BulkMarkNotificationsDoneResponses, BulkMarkNotificationsSeenData, BulkMarkNotificationsSeenError, BulkMarkNotificationsSeenErrors, BulkMarkNotificationsSeenResponses, BulkMarkNotificationsUndoneData, BulkMarkNotificationsUndoneError, BulkMarkNotificationsUndoneErrors, BulkMarkNotificationsUndoneResponses, CalendarEventReminderMetadata, CallStartedMetadata, ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata, ChannelType, ClientOptions, CommentedOnDocumentMetadata, CommonChannelMetadata, ConnGatewayInnerNotifValue, ConnGatewayNotificationPayload, CreateNotification, DeleteUserNotificationV2Data, DeleteUserNotificationV2Error, DeleteUserNotificationV2Errors, DeleteUserNotificationV2Responses, DeviceRequest, DeviceType, DisableNotificationTypeData, DisableNotificationTypeError, DisableNotificationTypeErrors, DisableNotificationTypeResponses, DocumentMentionMetadata, EmptyResponse, EnableNotificationTypeData, EnableNotificationTypeError, EnableNotificationTypeErrors, EnableNotificationTypeResponses, Entity, EntityType, ErrorResponse, GetAllUserNotificationsResponse, GetNotificationTypePreferencesData, GetNotificationTypePreferencesError, GetNotificationTypePreferencesErrors, GetNotificationTypePreferencesResponse, GetNotificationTypePreferencesResponse2, GetNotificationTypePreferencesResponses, GetTypedNotificationByIdData, GetTypedNotificationByIdError, GetTypedNotificationByIdErrors, GetTypedNotificationByIdResponse, GetTypedNotificationByIdResponses, GetTypedNotificationsByEventItemIdData, GetTypedNotificationsByEventItemIdError, GetTypedNotificationsByEventItemIdErrors, GetTypedNotificationsByEventItemIdResponse, GetTypedNotificationsByEventItemIdResponses, GetUnsubscribesData, GetUnsubscribesError, GetUnsubscribesErrors, GetUnsubscribesResponse, GetUnsubscribesResponses, GithubPrCheckRun, GithubPrCheckRunState, GithubPrComment, GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus, GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview, GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InboxReauthRequiredMetadata, InviteToTeamMetadata, ItemSharedMetadata, ListTypedNotificationsData, ListTypedNotificationsError, ListTypedNotificationsErrors, ListTypedNotificationsResponse, ListTypedNotificationsResponses, MacroUserIdStr, MentionedInDocumentCommentMetadata, NewEmailMetadata, NotifEvent, NotificationBulkRequest, NotificationDocumentSubType, NotificationServiceApiVersion, NotificationTypeName, PushNotificationData, ReminderMetadata, RemoveUnsubscribeAllData, RemoveUnsubscribeAllError, RemoveUnsubscribeAllErrors, RemoveUnsubscribeAllResponse, RemoveUnsubscribeAllResponses, RemoveUnsubscribeItemData, RemoveUnsubscribeItemError, RemoveUnsubscribeItemErrors, RemoveUnsubscribeItemResponse, RemoveUnsubscribeItemResponses, RepliedToDocumentCommentThreadMetadata, TaggedContentValue, TaskAssignedMetadata, UnsubscribeAllData, UnsubscribeAllError, UnsubscribeAllErrors, UnsubscribeAllResponse, UnsubscribeAllResponses, UnsubscribeEmailData, UnsubscribeEmailError, UnsubscribeEmailErrors, UnsubscribeEmailResponse, UnsubscribeEmailResponses, UnsubscribeItemData, UnsubscribeItemError, UnsubscribeItemErrors, UnsubscribeItemPathParams, UnsubscribeItemResponse, UnsubscribeItemResponses, UserUnsubscribe } from './types.gen';
+export type { AiResponseMetadata, ApiUserNotification, BulkDeleteUserNotificationsV2Data, BulkDeleteUserNotificationsV2Error, BulkDeleteUserNotificationsV2Errors, BulkDeleteUserNotificationsV2Responses, BulkGetByEventItemIdsRequest, BulkGetTypedNotificationsByEventItemIdsData, BulkGetTypedNotificationsByEventItemIdsError, BulkGetTypedNotificationsByEventItemIdsErrors, BulkGetTypedNotificationsByEventItemIdsResponse, BulkGetTypedNotificationsByEventItemIdsResponses, BulkMarkNotificationsDoneData, BulkMarkNotificationsDoneError, BulkMarkNotificationsDoneErrors, BulkMarkNotificationsDoneResponses, BulkMarkNotificationsSeenData, BulkMarkNotificationsSeenError, BulkMarkNotificationsSeenErrors, BulkMarkNotificationsSeenResponses, BulkMarkNotificationsUndoneData, BulkMarkNotificationsUndoneError, BulkMarkNotificationsUndoneErrors, BulkMarkNotificationsUndoneResponses, CalendarEventReminderMetadata, CallStartedMetadata, ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata, ChannelReplyMetadata, ChannelType, ClientOptions, CommentedOnDocumentMetadata, CommonChannelMetadata, ConnGatewayNotificationPayload, CreateNotification, DeleteUserNotificationV2Data, DeleteUserNotificationV2Error, DeleteUserNotificationV2Errors, DeleteUserNotificationV2Responses, DeviceRequest, DeviceType, DisableNotificationTypeData, DisableNotificationTypeError, DisableNotificationTypeErrors, DisableNotificationTypeResponses, DocumentMentionMetadata, EmptyResponse, EnableNotificationTypeData, EnableNotificationTypeError, EnableNotificationTypeErrors, EnableNotificationTypeResponses, Entity, EntityType, ErrorResponse, GetAllUserNotificationsResponse, GetNotificationTypePreferencesData, GetNotificationTypePreferencesError, GetNotificationTypePreferencesErrors, GetNotificationTypePreferencesResponse, GetNotificationTypePreferencesResponse2, GetNotificationTypePreferencesResponses, GetTypedNotificationByIdData, GetTypedNotificationByIdError, GetTypedNotificationByIdErrors, GetTypedNotificationByIdResponse, GetTypedNotificationByIdResponses, GetTypedNotificationsByEventItemIdData, GetTypedNotificationsByEventItemIdError, GetTypedNotificationsByEventItemIdErrors, GetTypedNotificationsByEventItemIdResponse, GetTypedNotificationsByEventItemIdResponses, GetUnsubscribesData, GetUnsubscribesError, GetUnsubscribesErrors, GetUnsubscribesResponse, GetUnsubscribesResponses, GithubPrCheckRun, GithubPrCheckRunState, GithubPrComment, GithubPrCommentKind, GithubPrEventAction, GithubPrEventStatus, GithubPrMention, GithubPrMentionLocation, GithubPrNotificationCommon, GithubPrReview, GithubPrReviewState, GithubPrStatusChanged, GithubReviewRequested, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InboxReauthRequiredMetadata, InviteToTeamMetadata, ItemSharedMetadata, ListTypedNotificationsData, ListTypedNotificationsError, ListTypedNotificationsErrors, ListTypedNotificationsResponse, ListTypedNotificationsResponses, MacroUserIdStr, MentionedInDocumentCommentMetadata, NewEmailMetadata, NotifEvent, NotificationBulkRequest, NotificationDocumentSubType, NotificationServiceApiVersion, NotificationTypeName, PushNotificationData, RealtimeNotifTaggedContentValue, ReminderMetadata, RemoveUnsubscribeAllData, RemoveUnsubscribeAllError, RemoveUnsubscribeAllErrors, RemoveUnsubscribeAllResponse, RemoveUnsubscribeAllResponses, RemoveUnsubscribeItemData, RemoveUnsubscribeItemError, RemoveUnsubscribeItemErrors, RemoveUnsubscribeItemResponse, RemoveUnsubscribeItemResponses, RepliedToDocumentCommentThreadMetadata, TaskAssignedMetadata, UnsubscribeAllData, UnsubscribeAllError, UnsubscribeAllErrors, UnsubscribeAllResponse, UnsubscribeAllResponses, UnsubscribeEmailData, UnsubscribeEmailError, UnsubscribeEmailErrors, UnsubscribeEmailResponse, UnsubscribeEmailResponses, UnsubscribeItemData, UnsubscribeItemError, UnsubscribeItemErrors, UnsubscribeItemPathParams, UnsubscribeItemResponse, UnsubscribeItemResponses, UserUnsubscribe } from './types.gen';
diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.ts
index 436a121d63..0171a47b3a 100644
--- a/packages/sdk/generated/notification/types.gen.ts
+++ b/packages/sdk/generated/notification/types.gen.ts
@@ -265,56 +265,12 @@ export type CommonChannelMetadata = {
};
/**
- * the value of the inner payload inside [ConnGatewayNotification]
- */
-export type ConnGatewayInnerNotifValue = Entity & {
- /**
- * When the notification was created.
- */
- created_at: string;
- /**
- * When the notification was deleted.
- */
- deleted_at?: string | null;
- /**
- * Whether the notification is marked as done.
- */
- done: boolean;
- /**
- * The notification event type string (e.g. "channel_mention").
- * TODO make this a new type
- */
- notification_event_type: string;
- /**
- * The notification ID.
- */
- notification_id: string;
- /**
- * Deserialized notification metadata.
- */
- notification_metadata: TaggedContentValue;
- sender_id?: null | MacroUserIdStr;
- /**
- * Whether the notification has been sent.
- */
- sent: boolean;
- /**
- * When the notification was last updated.
- */
- updated_at: string;
- /**
- * When the notification was viewed/seen.
- */
- viewed_at?: string | null;
-};
-
-/**
- * Concrete schema type for [`ConnGatewayInnerNotif`] with `serde_json::Value` metadata.
+ * Concrete schema type for [`RealtimeNotif`] with `serde_json::Value` metadata.
*
* Used for OpenAPI schema generation — serializes identically to
- * `ConnGatewayInnerNotif<serde_json::Value>`.
+ * `RealtimeNotif<serde_json::Value>`.
*/
-export type ConnGatewayNotificationPayload = ConnGatewayInnerNotifValue;
+export type ConnGatewayNotificationPayload = RealtimeNotifTaggedContentValue;
export type CreateNotification = Entity & {
/**
@@ -956,6 +912,53 @@ export type PushNotificationData = {
senderProfilePictureUrl?: string | null;
};
+/**
+ * the value of the inner payload inside [ConnGatewayNotification]
+ */
+export type RealtimeNotifTaggedContentValue = Entity & {
+ /**
+ * When the notification was created.
+ */
+ created_at: string;
+ /**
+ * When the notification was deleted.
+ */
+ deleted_at?: string | null;
+ /**
+ * Whether the notification is marked as done.
+ */
+ done: boolean;
+ /**
+ * The notification event type string (e.g. "channel_mention").
+ * TODO make this a new type
+ */
+ notification_event_type: string;
+ /**
+ * The notification ID.
+ */
+ notification_id: string;
+ /**
+ * A notification metadata value tagged with the notification event type.
+ */
+ notification_metadata: {
+ content: unknown;
+ tag: NotificationTypeName;
+ };
+ sender_id?: null | MacroUserIdStr;
+ /**
+ * Whether the notification has been sent.
+ */
+ sent: boolean;
+ /**
+ * When the notification was last updated.
+ */
+ updated_at: string;
+ /**
+ * When the notification was viewed/seen.
+ */
+ viewed_at?: string | null;
+};
+
/**
* Metadata for a reminder the user set for themselves coming due.
*
@@ -1011,14 +1014,6 @@ export type RepliedToDocumentCommentThreadMetadata = {
threadId: number;
};
-/**
- * A notification metadata value tagged with the notification event type.
- */
-export type TaggedContentValue = {
- content: unknown;
- tag: NotificationTypeName;
-};
-
/**
* Metadata for when a user is assigned to a task
*/
diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.json
index 239c8089b6..6afb4dd3a6 100644
--- a/packages/sdk/specs/notification.json
+++ b/packages/sdk/specs/notification.json
@@ -1352,84 +1352,9 @@
}
}
},
- "ConnGatewayInnerNotif_Value": {
- "allOf": [
- {
- "$ref": "#/components/schemas/Entity",
- "description": "The entity the notification is about."
- },
- {
- "type": "object",
- "required": [
- "notification_id",
- "notification_event_type",
- "sent",
- "done",
- "created_at",
- "updated_at",
- "notification_metadata"
- ],
- "properties": {
- "created_at": {
- "type": "string",
- "format": "date-time",
- "description": "When the notification was created."
- },
- "deleted_at": {
- "type": ["string", "null"],
- "format": "date-time",
- "description": "When the notification was deleted."
- },
- "done": {
- "type": "boolean",
- "description": "Whether the notification is marked as done."
- },
- "notification_event_type": {
- "type": "string",
- "description": "The notification event type string (e.g. \"channel_mention\").\nTODO make this a new type"
- },
- "notification_id": {
- "type": "string",
- "format": "uuid",
- "description": "The notification ID."
- },
- "notification_metadata": {
- "$ref": "#/components/schemas/TaggedContent_Value",
- "description": "Deserialized notification metadata."
- },
- "sender_id": {
- "oneOf": [
- {
- "type": "null"
- },
- {
- "$ref": "#/components/schemas/MacroUserIdStr",
- "description": "The user who triggered the notification."
- }
- ]
- },
- "sent": {
- "type": "boolean",
- "description": "Whether the notification has been sent."
- },
- "updated_at": {
- "type": "string",
- "format": "date-time",
- "description": "When the notification was last updated."
- },
- "viewed_at": {
- "type": ["string", "null"],
- "format": "date-time",
- "description": "When the notification was viewed/seen."
- }
- }
- }
- ],
- "description": "the value of the inner payload inside [ConnGatewayNotification]"
- },
"ConnGatewayNotificationPayload": {
- "$ref": "#/components/schemas/ConnGatewayInnerNotif_Value",
- "description": "Concrete schema type for [`ConnGatewayInnerNotif`] with `serde_json::Value` metadata.\n\nUsed for OpenAPI schema generation — serializes identically to\n`ConnGatewayInnerNotif<serde_json::Value>`."
+ "$ref": "#/components/schemas/RealtimeNotif_TaggedContent_Value",
+ "description": "Concrete schema type for [`RealtimeNotif`] with `serde_json::Value` metadata.\n\nUsed for OpenAPI schema generation — serializes identically to\n`RealtimeNotif<serde_json::Value>`."
},
"CreateNotification": {
"allOf": [
@@ -2478,6 +2403,88 @@
}
}
},
+ "RealtimeNotif_TaggedContent_Value": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Entity",
+ "description": "The entity the notification is about."
+ },
+ {
+ "type": "object",
+ "required": [
+ "notification_id",
+ "notification_event_type",
+ "sent",
+ "done",
+ "created_at",
+ "updated_at",
+ "notification_metadata"
+ ],
+ "properties": {
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the notification was created."
+ },
+ "deleted_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the notification was deleted."
+ },
+ "done": {
+ "type": "boolean",
+ "description": "Whether the notification is marked as done."
+ },
+ "notification_event_type": {
+ "type": "string",
+ "description": "The notification event type string (e.g. \"channel_mention\").\nTODO make this a new type"
+ },
+ "notification_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The notification ID."
+ },
+ "notification_metadata": {
+ "type": "object",
+ "description": "A notification metadata value tagged with the notification event type.",
+ "required": ["tag", "content"],
+ "properties": {
+ "content": {},
+ "tag": {
+ "$ref": "#/components/schemas/NotificationTypeName"
+ }
+ }
+ },
+ "sender_id": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "The user who triggered the notification."
+ }
+ ]
+ },
+ "sent": {
+ "type": "boolean",
+ "description": "Whether the notification has been sent."
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When the notification was last updated."
+ },
+ "viewed_at": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the notification was viewed/seen."
+ }
+ }
+ }
+ ],
+ "description": "the value of the inner payload inside [ConnGatewayNotification]"
+ },
"ReminderMetadata": {
"type": "object",
"description": "Metadata for a reminder the user set for themselves coming due.\n\nThere is no sender: a reminder is self-set, so the dispatcher sends it with\n`sender_id: None` (a recipient who is also the sender is filtered out of\ntheir own notification). Every formatter here must therefore work without\none.\n\nThe associated entity, when there is one, lives on the notification row\nrather than in here, and clients resolve its name from that — so the\ndispatcher does not have to look up a name across five entity types.",
@@ -2541,17 +2548,6 @@
}
}
},
- "TaggedContent_Value": {
- "type": "object",
- "description": "A notification metadata value tagged with the notification event type.",
- "required": ["tag", "content"],
- "properties": {
- "content": {},
- "tag": {
- "$ref": "#/components/schemas/NotificationTypeName"
- }
- }
- },
"TaskAssignedMetadata": {
"type": "object",
"description": "Metadata for when a user is assigned to a task",
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 6e6a8e142b..d952e02beb 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -164,12 +164,24 @@ type DssSoupState =
/// Realtime Soup consumer service used by GraphQL subscriptions.
pub(crate) type DssSoupRealtimeService = SoupRealtimeConsumerService<SoupTopicConsumer>;
+/// Realtime notification consumer service used by GraphQL subscriptions.
+pub(crate) type DssNotificationRealtimeService =
+ notification::domain::service::WebSocketNotificationConsumerService<
+ notification::outbound::notification_consumer::NotificationTopicConsumer<
+ notification::domain::models::queue_message::RealtimeNotif<
+ model_notifications::NotifEvent,
+ >,
+ >,
+ notification::domain::models::queue_message::RealtimeNotif<model_notifications::NotifEvent>,
+ >;
+
/// GraphQL Soup schema wired to the DSS services; the `ApiContext` state
/// parameter lets GraphQL resolvers run the same axum extractors as the REST
/// routes, lazily, against the stored request parts.
pub(crate) type DssGraphqlSoupSchema = complete_graph::SharedSoupSchema<
DssSoupService,
DssSoupRealtimeService,
+ DssNotificationRealtimeService,
DssEmailService,
EntityAccessService,
AuthorizationService,
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index fe99c7d261..c830c7cfcc 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -93,9 +93,14 @@ use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
use macro_service_urls::AiEditingWorkerUrl;
use macro_service_urls::{ConnectionGatewayUrl, LexicalServiceUrl, SyncServiceUrl};
use macro_sha_count_client::Redis;
-use notification::domain::service::SqsNotificationIngress;
-use notification::domain::service::{NotificationReaderService, PlatformArnConfig};
-use notification::outbound::queue::SqsQueue;
+use notification::domain::{
+ models::queue_message::RealtimeNotif,
+ service::{
+ NotificationReaderService, PlatformArnConfig, SqsNotificationIngress,
+ WebSocketNotificationConsumerService,
+ },
+};
+use notification::outbound::{notification_consumer::NotificationTopicConsumer, queue::SqsQueue};
use opensearch_client::OpensearchClient;
use projects_hex::{
domain::service::ProjectServiceImpl,
@@ -950,6 +955,46 @@ async fn main() -> anyhow::Result<()> {
reminders_service.clone(),
));
+ let websocket_notification_consumer_service =
+ Arc::new(WebSocketNotificationConsumerService::new(
+ NotificationTopicConsumer::<RealtimeNotif<model_notifications::NotifEvent>>::from_env(
+ config.kafka_brokers.as_ref(),
+ )
+ .map_err(|error| {
+ anyhow::anyhow!("failed to create WebSocket notification topic consumer: {error:?}")
+ })?,
+ ));
+ consumer_tracker.spawn({
+ let service = Arc::clone(&websocket_notification_consumer_service);
+ let cancellation_token = consumer_cancellation_token.clone();
+ async move {
+ loop {
+ let result = tokio::select! {
+ biased;
+ _ = cancellation_token.cancelled() => break,
+ result = service.run() => result,
+ };
+
+ if cancellation_token.is_cancelled() {
+ break;
+ }
+
+ let _ = result.inspect_err(|error| {
+ tracing::error!(
+ error = ?error,
+ "WebSocket notification consumer stopped"
+ );
+ });
+
+ tokio::select! {
+ biased;
+ _ = cancellation_token.cancelled() => break,
+ _ = tokio::time::sleep(Duration::from_secs(1)) => {}
+ }
+ }
+ }
+ });
+
let soup_realtime_service = Arc::new(SoupRealtimeConsumerService::new(
SoupTopicConsumer::from_env(config.kafka_brokers.as_ref()).map_err(|error| {
anyhow::anyhow!("failed to create realtime Soup topic consumer: {error:?}")
@@ -1161,6 +1206,7 @@ async fn main() -> anyhow::Result<()> {
graphql_soup_schema: complete_graph::build_schema_from_arcs(
soup_service,
soup_realtime_service,
+ websocket_notification_consumer_service,
),
graphql_notification_reader,
graphql_entity_mutation_service,
diff --git a/services/notification_service/src/api/user_notification/test.rs b/services/notification_service/src/api/user_notification/test.rs
index ba729b6ea7..eafa5a4b02 100644
--- a/services/notification_service/src/api/user_notification/test.rs
+++ b/services/notification_service/src/api/user_notification/test.rs
@@ -300,13 +300,13 @@ fn to_typed_row_preserves_row_fields() {
}
/// Verifies that the `notification_metadata` field serializes identically between
-/// `ApiUserNotification` and `ConnGatewayInnerNotif`.
+/// `ApiUserNotification` and `RealtimeNotif`.
/// This ensures frontend code can use the same parsing logic for both HTTP API and WebSocket delivery.
#[test]
-fn api_user_notification_and_conn_gateway_inner_notif_metadata_serialize_identically() {
+fn api_user_notification_and_realtime_notif_metadata_serialize_identically() {
use chrono::{TimeZone, Utc};
use notification::domain::models::TaggedContent;
- use notification::domain::models::queue_message::ConnGatewayInnerNotif;
+ use notification::domain::models::queue_message::RealtimeNotif;
let created_at = Utc.with_ymd_and_hms(2025, 1, 15, 12, 0, 0).unwrap();
let notification_id = uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
@@ -347,8 +347,8 @@ fn api_user_notification_and_conn_gateway_inner_notif_metadata_serialize_identic
),
};
- // Create ConnGatewayInnerNotif (used by WebSocket delivery)
- let conn_gateway_notif = ConnGatewayInnerNotif {
+ // Create RealtimeNotif (used by WebSocket delivery)
+ let conn_gateway_notif = RealtimeNotif {
notification_id,
notification_event_type: "channel_mention".to_string(),
entity,
@@ -378,17 +378,17 @@ fn api_user_notification_and_conn_gateway_inner_notif_metadata_serialize_identic
conn_gateway_metadata,
"notification_metadata should serialize identically.\n\
ApiUserNotification (HTTP API): {}\n\
- ConnGatewayInnerNotif (WebSocket): {}",
+ RealtimeNotif (WebSocket): {}",
serde_json::to_string_pretty(api_metadata).unwrap(),
serde_json::to_string_pretty(conn_gateway_metadata).unwrap(),
);
}
-/// Verifies that `TaggedContent<T>` (used by ConnGatewayInnerNotif for WebSocket delivery)
+/// Verifies that `TaggedContent<T>` (used by RealtimeNotif for WebSocket delivery)
/// and `NotifEvent` (used by ApiUserNotification for HTTP API) serialize identically.
/// This ensures frontend code can use the same parsing logic for both delivery methods.
#[test]
-fn conn_gateway_inner_val_has_identical_serialization() {
+fn realtime_notif_has_identical_serialization() {
use notification::domain::models::TaggedContent;
// Create test notification metadata
@@ -405,7 +405,7 @@ fn conn_gateway_inner_val_has_identical_serialization() {
sender_profile_picture_url: None,
};
- // TaggedContent<T> is what ConnGatewayInnerNotif uses for notification_metadata
+ // TaggedContent<T> is what RealtimeNotif uses for notification_metadata
// when sending via WebSocket
let tagged_content = TaggedContent::new(notif_metadata.clone());
let tagged_content_json = serde_json::to_value(&tagged_content).unwrap();
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 2fde55adc3..886b9c0e0e 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -88,6 +88,20 @@ type CompleteMutationRoot {
updateEmailThreadLabel(input: UpdateEmailThreadLabelInput!): GraphqlSoupEmailThread!
}
+"""
+Root subscription object combining realtime Soup and notification adapters.
+"""
+type CompleteSubscriptionRoot {
+ """
+ Subscribe to realtime Soup updates for the authenticated user.
+ """
+ soupUpdates: [SoupPatch!]!
+ """
+ Subscribe to realtime notifications for the authenticated user.
+ """
+ notificationUpdates: GraphqlSoupNotification!
+}
+
"""
One entity duplication in a batch.
"""
@@ -164,6 +178,20 @@ type GraphqlAccessLevelPermission {
accessLevel: GraphqlEntityAccessLevel!
}
+"""
+Metadata for an AI response.
+"""
+type GraphqlAiResponseMetadata {
+ """
+ AI response summary.
+ """
+ summary: String!
+ """
+ Response message identifier.
+ """
+ messageId: String!
+}
+
"""
A Boolean property value.
"""
@@ -262,6 +290,44 @@ input GraphqlCalendarEventLiteral @oneOf {
notificationSeen: Boolean
}
+"""
+Metadata for a due calendar event reminder.
+"""
+type GraphqlCalendarEventReminderMetadata {
+ """
+ Calendar event identifier.
+ """
+ eventId: ID!
+ """
+ Stable occurrence key of the event instance.
+ """
+ occurrenceKey: String!
+ """
+ Event display title.
+ """
+ title: String!
+ """
+ Timed event start in RFC 3339 format.
+ """
+ startsAt: String
+ """
+ Timed event end in RFC 3339 format.
+ """
+ endsAt: String
+ """
+ All-day event start date in ISO 8601 format.
+ """
+ startDate: String
+ """
+ IANA time zone used to render the event.
+ """
+ timeZone: String
+ """
+ Minutes before the event start when the alarm fires.
+ """
+ minutesBefore: Int!
+}
+
"""
The two operands of a recursive `CallFilterExpr` binary expression.
"""
@@ -324,6 +390,20 @@ input GraphqlCallLiteral @oneOf {
attended: Boolean
}
+"""
+Metadata for a started call.
+"""
+type GraphqlCallStartedMetadata {
+ """
+ Channel name.
+ """
+ channelName: String
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
"""
GraphQL input representing the call status.
"""
@@ -412,6 +492,28 @@ input GraphqlChannelExpr @oneOf {
literal: GraphqlChannelLiteral
}
+"""
+Metadata for a channel invitation.
+"""
+type GraphqlChannelInviteMetadata {
+ """
+ Inviting user identifier.
+ """
+ invitedBy: String!
+ """
+ Channel name.
+ """
+ channelName: String!
+ """
+ Message content associated with the invitation.
+ """
+ messageContent: String
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
"""
GraphQL input representing the channel literal.
"""
@@ -464,6 +566,82 @@ input GraphqlChannelLiteral @oneOf {
notificationSeen: Boolean
}
+"""
+Metadata for a channel mention notification.
+"""
+type GraphqlChannelMentionMetadata {
+ """
+ Mentioning message identifier.
+ """
+ messageId: String!
+ """
+ Mentioning message content.
+ """
+ messageContent: String!
+ """
+ Whether the message has attachments.
+ """
+ hasAttachments: Boolean!
+ """
+ Thread identifier, when the mention is in a thread.
+ """
+ threadId: String
+ """
+ Display name for a non-user sender.
+ """
+ senderDisplayName: String
+ """
+ Channel type.
+ """
+ channelType: GraphqlNotificationChannelType!
+ """
+ Channel display name.
+ """
+ channelName: String!
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
+"""
+Metadata for a newly sent channel message.
+"""
+type GraphqlChannelMessageSendMetadata {
+ """
+ Sending user identifier.
+ """
+ sender: String
+ """
+ Display name for a non-user sender.
+ """
+ senderDisplayName: String
+ """
+ Message content.
+ """
+ messageContent: String!
+ """
+ Message identifier.
+ """
+ messageId: String!
+ """
+ Whether the message has attachments.
+ """
+ hasAttachments: Boolean!
+ """
+ Channel type.
+ """
+ channelType: GraphqlNotificationChannelType!
+ """
+ Channel display name.
+ """
+ channelName: String!
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
"""
Channel role resolved for the current viewer.
"""
@@ -482,6 +660,52 @@ enum GraphqlChannelParticipantRole {
MEMBER
}
+"""
+Metadata for a reply to a channel thread.
+"""
+type GraphqlChannelReplyMetadata {
+ """
+ Thread identifier.
+ """
+ threadId: String!
+ """
+ Reply message identifier.
+ """
+ messageId: String!
+ """
+ Replying user identifier.
+ """
+ userId: String
+ """
+ Display name for a non-user sender.
+ """
+ senderDisplayName: String
+ """
+ Reply content.
+ """
+ messageContent: String!
+ """
+ Whether the reply has attachments.
+ """
+ hasAttachments: Boolean!
+ """
+ Root-message sender identifier.
+ """
+ threadParentSenderId: String
+ """
+ Channel type.
+ """
+ channelType: GraphqlNotificationChannelType!
+ """
+ Channel display name.
+ """
+ channelName: String!
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
"""
Channel permission represented by the viewer's participant role.
"""
@@ -686,6 +910,44 @@ enum GraphqlChatRole {
ASSISTANT
}
+"""
+Metadata for a comment on a document.
+"""
+type GraphqlCommentedOnDocumentMetadata {
+ """
+ Document name.
+ """
+ documentName: String!
+ """
+ Document owner identifier.
+ """
+ owner: String!
+ """
+ Document file type.
+ """
+ fileType: String
+ """
+ Document subtype.
+ """
+ subType: GraphqlNotificationDocumentSubType
+ """
+ Comment identifier.
+ """
+ commentId: Int!
+ """
+ Comment thread identifier.
+ """
+ threadId: Int!
+ """
+ Comment text.
+ """
+ text: String!
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
"""
The two operands of a recursive `CrmCompanyFilterExpr` binary expression.
"""
@@ -876,6 +1138,60 @@ input GraphqlDocumentLiteral @oneOf {
updatedAt: GraphqlDateLiteral
}
+"""
+Metadata for a document mention notification.
+"""
+type GraphqlDocumentMentionMetadata {
+ """
+ Mentioned document name.
+ """
+ documentName: String!
+ """
+ Document owner identifier.
+ """
+ owner: String!
+ """
+ Document file type.
+ """
+ fileType: String
+ """
+ Document subtype.
+ """
+ subType: GraphqlNotificationDocumentSubType
+ """
+ Mentioning message identifier.
+ """
+ messageId: String!
+ """
+ Mentioning message content.
+ """
+ messageContent: String!
+ """
+ Whether the message has attachments.
+ """
+ hasAttachments: Boolean!
+ """
+ Thread identifier, when the mention is in a thread.
+ """
+ threadId: String
+ """
+ Display name for a non-user sender.
+ """
+ senderDisplayName: String
+ """
+ Channel type.
+ """
+ channelType: GraphqlNotificationChannelType!
+ """
+ Channel display name.
+ """
+ channelName: String!
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
"""
GraphQL input representing the document sub type.
"""
@@ -1330,163 +1646,675 @@ Input identifying an entity referenced by a property value.
"""
input GraphqlEntityReferenceInput {
"""
- Type of the referenced entity.
+ Type of the referenced entity.
+ """
+ entityType: GraphqlPropertyEntityType!
+ """
+ Identifier of the referenced entity.
+ """
+ entityId: String!
+ """
+ Specific message when the reference targets a thread message.
+ """
+ specificMessageId: ID
+}
+
+"""
+An entity-reference property value.
+"""
+type GraphqlEntityReferencePropertyValue {
+ """
+ The referenced entities.
+ """
+ references: [GraphqlPropertyEntityReference!]!
+}
+
+"""
+Canonical entity types accepted by cross-entity APIs.
+"""
+enum GraphqlEntityType {
+ """
+ Document entity.
+ """
+ DOCUMENT
+ """
+ Chat entity.
+ """
+ CHAT
+ """
+ Project entity.
+ """
+ PROJECT
+ """
+ Email thread entity.
+ """
+ EMAIL_THREAD
+ """
+ Channel entity.
+ """
+ CHANNEL
+ """
+ Channel message entity.
+ """
+ CHANNEL_MESSAGE
+ """
+ Call entity.
+ """
+ CALL
+ """
+ Calendar event entity.
+ """
+ CALENDAR_EVENT
+ """
+ CRM company entity.
+ """
+ CRM_COMPANY
+ """
+ Foreign entity.
+ """
+ FOREIGN_ENTITY
+ """
+ User entity.
+ """
+ USER
+ """
+ Team entity.
+ """
+ TEAM
+ """
+ Static file entity.
+ """
+ STATIC_FILE
+ """
+ CRM contact entity.
+ """
+ CRM_CONTACT
+ """
+ Reminder entity.
+ """
+ REMINDER
+ """
+ AI skill entity (skill document or built-in system skill).
+ """
+ SKILL
+}
+
+"""
+The two operands of a recursive `ForeignEntityFilterExpr` binary expression.
+"""
+input GraphqlForeignEntityBinaryExpr {
+ """
+ The left-hand expression.
+ """
+ left: GraphqlForeignEntityExpr!
+ """
+ The right-hand expression.
+ """
+ right: GraphqlForeignEntityExpr!
+}
+
+"""
+A recursive `ForeignEntityFilterExpr` filter expression.
+"""
+input GraphqlForeignEntityExpr @oneOf {
+ """
+ Matches when both expressions match.
+ """
+ and: GraphqlForeignEntityBinaryExpr
+ """
+ Matches when either expression matches.
+ """
+ or: GraphqlForeignEntityBinaryExpr
+ """
+ Negates an expression.
+ """
+ not: GraphqlForeignEntityExpr
+ """
+ Matches a domain-specific literal condition.
+ """
+ literal: GraphqlForeignEntityLiteral
+}
+
+"""
+GraphQL input representing the foreign entity literal.
+"""
+input GraphqlForeignEntityLiteral @oneOf {
+ """
+ The id option.
+ """
+ id: ID
+ """
+ The foreign entity id option.
+ """
+ foreignEntityId: String
+ """
+ The foreign entity source option.
+ """
+ foreignEntitySource: String
+ """
+ The includes me option.
+ """
+ includesMe: Boolean
+ """
+ The notification done option.
+ """
+ notificationDone: Boolean
+ """
+ The notification seen option.
+ """
+ notificationSeen: Boolean
+}
+
+"""
+Metadata for a completed GitHub pull-request check run.
+"""
+type GraphqlGithubPrCheckRunMetadata {
+ """
+ Internal foreign-entity identifier.
+ """
+ foreignEntityId: ID!
+ """
+ External GitHub key.
+ """
+ githubKey: String!
+ """
+ Repository owner or organization.
+ """
+ owner: String!
+ """
+ Repository name.
+ """
+ repo: String!
+ """
+ Pull-request number.
+ """
+ number: String!
+ """
+ Public pull-request URL.
+ """
+ url: String!
+ """
+ Compact pull-request display label.
+ """
+ displayName: String!
+ """
+ Pull-request title.
+ """
+ title: String!
+ """
+ Sender GitHub login.
+ """
+ senderGithubLogin: String
+ """
+ Sender GitHub user identifier.
+ """
+ senderGithubUserId: String
+ """
+ Sender GitHub avatar URL.
+ """
+ senderGithubAvatarUrl: String
+ """
+ Check-run GitHub identifier.
+ """
+ checkRunGithubId: ID!
+ """
+ Check name.
+ """
+ checkName: String!
+ """
+ Raw check status.
+ """
+ checkStatus: String!
+ """
+ Raw check conclusion.
+ """
+ conclusion: String!
+ """
+ Normalized check state.
+ """
+ state: GraphqlGithubPrCheckRunState!
+ """
+ Public check URL.
+ """
+ checkUrl: String!
+ """
+ Completion timestamp in RFC 3339 format.
+ """
+ completedAt: String!
+}
+
+"""
+GraphQL GitHub check-run state.
+"""
+enum GraphqlGithubPrCheckRunState {
+ """
+ Check completed successfully.
+ """
+ COMPLETED
+ """
+ Check completed with a failure-like result.
+ """
+ FAILED
+}
+
+"""
+GraphQL GitHub pull-request comment kind.
+"""
+enum GraphqlGithubPrCommentKind {
+ """
+ Top-level issue comment.
+ """
+ ISSUE
+ """
+ Inline review comment.
+ """
+ REVIEW_COMMENT
+}
+
+"""
+Metadata for a GitHub pull-request comment.
+"""
+type GraphqlGithubPrCommentMetadata {
+ """
+ Internal foreign-entity identifier.
+ """
+ foreignEntityId: ID!
+ """
+ External GitHub key.
+ """
+ githubKey: String!
+ """
+ Repository owner or organization.
+ """
+ owner: String!
+ """
+ Repository name.
+ """
+ repo: String!
+ """
+ Pull-request number.
+ """
+ number: String!
+ """
+ Public pull-request URL.
+ """
+ url: String!
+ """
+ Compact pull-request display label.
+ """
+ displayName: String!
+ """
+ Pull-request title.
+ """
+ title: String!
+ """
+ Sender GitHub login.
+ """
+ senderGithubLogin: String
+ """
+ Sender GitHub user identifier.
+ """
+ senderGithubUserId: String
+ """
+ Sender GitHub avatar URL.
+ """
+ senderGithubAvatarUrl: String
+ """
+ Comment kind.
+ """
+ commentKind: GraphqlGithubPrCommentKind!
+ """
+ Comment GitHub identifier.
+ """
+ commentGithubId: ID
+ """
+ Public comment URL.
+ """
+ commentUrl: String
+ """
+ Truncated comment body.
+ """
+ commentSnippet: String!
+}
+
+"""
+GraphQL GitHub pull-request action.
+"""
+enum GraphqlGithubPrEventAction {
+ """
+ Pull request opened.
+ """
+ OPENED
+ """
+ Pull request reopened.
+ """
+ REOPENED
+ """
+ Pull request closed.
+ """
+ CLOSED
+}
+
+"""
+GraphQL GitHub pull-request lifecycle status.
+"""
+enum GraphqlGithubPrEventStatus {
+ """
+ Open pull request.
+ """
+ OPEN
+ """
+ Closed pull request.
+ """
+ CLOSED
+ """
+ Merged pull request.
+ """
+ MERGED
+}
+
+"""
+GraphQL location of a GitHub pull-request mention.
+"""
+enum GraphqlGithubPrMentionLocation {
+ """
+ Pull-request body.
+ """
+ PR_BODY
+ """
+ Top-level comment.
+ """
+ COMMENT
+ """
+ Review summary.
+ """
+ REVIEW
+ """
+ Inline review comment.
+ """
+ REVIEW_COMMENT
+}
+
+"""
+Metadata for a GitHub pull-request mention.
+"""
+type GraphqlGithubPrMentionMetadata {
+ """
+ Internal foreign-entity identifier.
+ """
+ foreignEntityId: ID!
+ """
+ External GitHub key.
+ """
+ githubKey: String!
+ """
+ Repository owner or organization.
+ """
+ owner: String!
+ """
+ Repository name.
+ """
+ repo: String!
+ """
+ Pull-request number.
+ """
+ number: String!
+ """
+ Public pull-request URL.
+ """
+ url: String!
+ """
+ Compact pull-request display label.
+ """
+ displayName: String!
+ """
+ Pull-request title.
+ """
+ title: String!
+ """
+ Sender GitHub login.
+ """
+ senderGithubLogin: String
+ """
+ Sender GitHub user identifier.
+ """
+ senderGithubUserId: String
+ """
+ Sender GitHub avatar URL.
+ """
+ senderGithubAvatarUrl: String
+ """
+ Mention location.
+ """
+ location: GraphqlGithubPrMentionLocation!
+ """
+ Comment or review GitHub identifier.
+ """
+ commentGithubId: ID
+ """
+ Public URL for the mentioning text.
+ """
+ commentUrl: String
+ """
+ Truncated mentioning text.
+ """
+ textSnippet: String!
+}
+
+"""
+Metadata for a GitHub pull-request review.
+"""
+type GraphqlGithubPrReviewMetadata {
+ """
+ Internal foreign-entity identifier.
+ """
+ foreignEntityId: ID!
+ """
+ External GitHub key.
+ """
+ githubKey: String!
+ """
+ Repository owner or organization.
+ """
+ owner: String!
+ """
+ Repository name.
+ """
+ repo: String!
+ """
+ Pull-request number.
+ """
+ number: String!
+ """
+ Public pull-request URL.
+ """
+ url: String!
+ """
+ Compact pull-request display label.
+ """
+ displayName: String!
+ """
+ Pull-request title.
"""
- entityType: GraphqlPropertyEntityType!
+ title: String!
"""
- Identifier of the referenced entity.
+ Sender GitHub login.
"""
- entityId: String!
+ senderGithubLogin: String
"""
- Specific message when the reference targets a thread message.
+ Sender GitHub user identifier.
"""
- specificMessageId: ID
+ senderGithubUserId: String
+ """
+ Sender GitHub avatar URL.
+ """
+ senderGithubAvatarUrl: String
+ """
+ Review GitHub identifier.
+ """
+ reviewGithubId: ID
+ """
+ Public review URL.
+ """
+ reviewUrl: String
+ """
+ Review state.
+ """
+ state: GraphqlGithubPrReviewState!
+ """
+ Truncated review body.
+ """
+ reviewSnippet: String
}
"""
-An entity-reference property value.
+GraphQL state of a GitHub pull-request review.
"""
-type GraphqlEntityReferencePropertyValue {
+enum GraphqlGithubPrReviewState {
"""
- The referenced entities.
+ Review approved the pull request.
"""
- references: [GraphqlPropertyEntityReference!]!
+ APPROVED
+ """
+ Review requested changes.
+ """
+ CHANGES_REQUESTED
+ """
+ Review left comments without an approval decision.
+ """
+ COMMENTED
}
"""
-Canonical entity types accepted by cross-entity APIs.
+Metadata for a GitHub pull-request lifecycle change.
"""
-enum GraphqlEntityType {
+type GraphqlGithubPrStatusChangedMetadata {
"""
- Document entity.
+ Internal foreign-entity identifier.
"""
- DOCUMENT
+ foreignEntityId: ID!
"""
- Chat entity.
+ External GitHub key.
"""
- CHAT
+ githubKey: String!
"""
- Project entity.
+ Repository owner or organization.
"""
- PROJECT
+ owner: String!
"""
- Email thread entity.
+ Repository name.
"""
- EMAIL_THREAD
+ repo: String!
"""
- Channel entity.
+ Pull-request number.
"""
- CHANNEL
+ number: String!
"""
- Channel message entity.
+ Public pull-request URL.
"""
- CHANNEL_MESSAGE
+ url: String!
"""
- Call entity.
+ Compact pull-request display label.
"""
- CALL
+ displayName: String!
"""
- Calendar event entity.
+ Pull-request title.
"""
- CALENDAR_EVENT
+ title: String!
"""
- CRM company entity.
+ Sender GitHub login.
"""
- CRM_COMPANY
+ senderGithubLogin: String
"""
- Foreign entity.
+ Sender GitHub user identifier.
"""
- FOREIGN_ENTITY
+ senderGithubUserId: String
"""
- User entity.
+ Sender GitHub avatar URL.
"""
- USER
+ senderGithubAvatarUrl: String
"""
- Team entity.
+ Current pull-request status.
"""
- TEAM
+ status: GraphqlGithubPrEventStatus!
"""
- Static file entity.
+ Triggering webhook action.
"""
- STATIC_FILE
+ action: GraphqlGithubPrEventAction!
"""
- CRM contact entity.
+ Previous pull-request status.
"""
- CRM_CONTACT
+ previousStatus: GraphqlGithubPrEventStatus
"""
- Reminder entity.
+ Head branch.
"""
- REMINDER
+ headBranch: String
"""
- AI skill entity (skill document or built-in system skill).
+ Base branch.
"""
- SKILL
+ baseBranch: String
+ """
+ Merge timestamp in RFC 3339 format.
+ """
+ mergedAt: String
}
"""
-The two operands of a recursive `ForeignEntityFilterExpr` binary expression.
+Metadata for a GitHub pull-request review request.
"""
-input GraphqlForeignEntityBinaryExpr {
+type GraphqlGithubReviewRequestedMetadata {
"""
- The left-hand expression.
+ Internal foreign-entity identifier.
"""
- left: GraphqlForeignEntityExpr!
+ foreignEntityId: ID!
"""
- The right-hand expression.
+ External GitHub key.
"""
- right: GraphqlForeignEntityExpr!
-}
-
-"""
-A recursive `ForeignEntityFilterExpr` filter expression.
-"""
-input GraphqlForeignEntityExpr @oneOf {
+ githubKey: String!
"""
- Matches when both expressions match.
+ Repository owner or organization.
"""
- and: GraphqlForeignEntityBinaryExpr
+ owner: String!
"""
- Matches when either expression matches.
+ Repository name.
"""
- or: GraphqlForeignEntityBinaryExpr
+ repo: String!
"""
- Negates an expression.
+ Pull-request number.
"""
- not: GraphqlForeignEntityExpr
+ number: String!
"""
- Matches a domain-specific literal condition.
+ Public pull-request URL.
"""
- literal: GraphqlForeignEntityLiteral
-}
-
-"""
-GraphQL input representing the foreign entity literal.
-"""
-input GraphqlForeignEntityLiteral @oneOf {
+ url: String!
"""
- The id option.
+ Compact pull-request display label.
"""
- id: ID
+ displayName: String!
"""
- The foreign entity id option.
+ Pull-request title.
"""
- foreignEntityId: String
+ title: String!
"""
- The foreign entity source option.
+ Sender GitHub login.
"""
- foreignEntitySource: String
+ senderGithubLogin: String
"""
- The includes me option.
+ Sender GitHub user identifier.
"""
- includesMe: Boolean
+ senderGithubUserId: String
"""
- The notification done option.
+ Sender GitHub avatar URL.
"""
- notificationDone: Boolean
+ senderGithubAvatarUrl: String
"""
- The notification seen option.
+ Requested reviewer GitHub login.
"""
- notificationSeen: Boolean
+ requestedReviewerGithubLogin: String
+ """
+ Requested reviewer GitHub user identifier.
+ """
+ requestedReviewerGithubUserId: String
}
"""
@@ -1529,6 +2357,46 @@ input GraphqlGroupByInput {
entityType: GraphqlPropertyEntityType
}
+"""
+Metadata for an inbox that requires reauthentication.
+"""
+type GraphqlInboxReauthRequiredMetadata {
+ """
+ Inbox email address.
+ """
+ emailAddress: String!
+}
+
+"""
+Metadata for a team invitation.
+"""
+type GraphqlInviteToTeamMetadata {
+ """
+ Team name.
+ """
+ teamName: String!
+ """
+ Team identifier.
+ """
+ teamId: ID!
+ """
+ Team invitation identifier.
+ """
+ teamInviteId: ID!
+ """
+ Inviting user identifier.
+ """
+ invitedBy: String!
+ """
+ Invited role.
+ """
+ role: String
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
"""
A link property value.
"""
@@ -1539,6 +2407,48 @@ type GraphqlLinkPropertyValue {
urls: [String!]!
}
+"""
+Metadata for a mention in a document comment.
+"""
+type GraphqlMentionedInDocumentCommentMetadata {
+ """
+ Document name.
+ """
+ documentName: String!
+ """
+ Document owner identifier.
+ """
+ owner: String!
+ """
+ Document file type.
+ """
+ fileType: String
+ """
+ Document subtype.
+ """
+ subType: GraphqlNotificationDocumentSubType
+ """
+ Mention identifier.
+ """
+ mentionId: String!
+ """
+ Comment identifier.
+ """
+ commentId: Int!
+ """
+ Comment thread identifier.
+ """
+ threadId: Int!
+ """
+ Comment text.
+ """
+ text: String!
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
"""
User-safe failure for one requested entity mutation.
"""
@@ -1563,6 +2473,77 @@ type GraphqlMutationSuccess {
effects: [SoupPatch!]!
}
+"""
+Metadata for a newly received email.
+"""
+type GraphqlNewEmailMetadata {
+ """
+ Sender email address.
+ """
+ sender: String
+ """
+ Recipient email address.
+ """
+ toEmail: String!
+ """
+ Email thread identifier.
+ """
+ threadId: String!
+ """
+ Email subject.
+ """
+ subject: String!
+ """
+ Email snippet.
+ """
+ snippet: String!
+}
+
+"""
+Typed GraphQL union containing every supported notification event payload.
+"""
+union GraphqlNotifEvent = GraphqlChannelMentionMetadata | GraphqlDocumentMentionMetadata | GraphqlMentionedInDocumentCommentMetadata | GraphqlRepliedToDocumentCommentThreadMetadata | GraphqlCommentedOnDocumentMetadata | GraphqlChannelInviteMetadata | GraphqlChannelMessageSendMetadata | GraphqlChannelReplyMetadata | GraphqlCallStartedMetadata | GraphqlNewEmailMetadata | GraphqlInboxReauthRequiredMetadata | GraphqlInviteToTeamMetadata | GraphqlTaskAssignedMetadata | GraphqlReminderMetadata | GraphqlCalendarEventReminderMetadata | GraphqlAiResponseMetadata | GraphqlGithubPrStatusChangedMetadata | GraphqlGithubPrCheckRunMetadata | GraphqlGithubReviewRequestedMetadata | GraphqlGithubPrCommentMetadata | GraphqlGithubPrMentionMetadata | GraphqlGithubPrReviewMetadata
+
+"""
+GraphQL channel type used by notification metadata.
+"""
+enum GraphqlNotificationChannelType {
+ """
+ Public channel.
+ """
+ PUBLIC
+ """
+ Private channel.
+ """
+ PRIVATE
+ """
+ Direct-message channel.
+ """
+ DIRECT_MESSAGE
+ """
+ Team channel.
+ """
+ TEAM
+}
+
+"""
+GraphQL document subtype used by notification metadata.
+"""
+enum GraphqlNotificationDocumentSubType {
+ """
+ Task document.
+ """
+ TASK
+ """
+ Snippet document.
+ """
+ SNIPPET
+ """
+ Skill document.
+ """
+ SKILL
+}
+
"""
A numeric property value.
"""
@@ -1971,6 +2952,20 @@ input GraphqlReminderLiteral @oneOf {
fired: Boolean
}
+"""
+Metadata for a due reminder.
+"""
+type GraphqlReminderMetadata {
+ """
+ Reminder identifier.
+ """
+ reminderId: ID!
+ """
+ Reminder description.
+ """
+ description: String!
+}
+
"""
How often a reminder fires.
"""
@@ -1985,6 +2980,44 @@ enum GraphqlReminderScheduleType {
RECURRING
}
+"""
+Metadata for a reply to a document comment thread.
+"""
+type GraphqlRepliedToDocumentCommentThreadMetadata {
+ """
+ Document name.
+ """
+ documentName: String!
+ """
+ Document owner identifier.
+ """
+ owner: String!
+ """
+ Document file type.
+ """
+ fileType: String
+ """
+ Document subtype.
+ """
+ subType: GraphqlNotificationDocumentSubType
+ """
+ Comment identifier.
+ """
+ commentId: Int!
+ """
+ Comment thread identifier.
+ """
+ threadId: Int!
+ """
+ Reply text.
+ """
+ text: String!
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
"""
A select-option property value.
"""
@@ -3552,9 +4585,13 @@ type GraphqlSoupNotification {
"""
senderId: String
"""
- Event-specific notification metadata.
+ Raw event-specific notification metadata.
+ """
+ metadata: JSON! @deprecated(reason: "Use typedMetadata with union inline fragments")
+ """
+ Typed event-specific notification metadata.
"""
- metadata: JSON!
+ typedMetadata: GraphqlNotifEvent
}
"""
@@ -3756,6 +4793,32 @@ type GraphqlStringPropertyValue {
value: String!
}
+"""
+Metadata for a task assignment.
+"""
+type GraphqlTaskAssignedMetadata {
+ """
+ Task identifier.
+ """
+ taskId: String!
+ """
+ Task name.
+ """
+ taskName: String
+ """
+ Task document subtype.
+ """
+ subType: GraphqlNotificationDocumentSubType
+ """
+ Assigning user identifier.
+ """
+ assignedBy: String!
+ """
+ Sender profile-picture URL.
+ """
+ senderProfilePictureUrl: String
+}
+
"""
represents the task subtype fields
"""
@@ -4084,16 +5147,6 @@ type SoupQueryRoot {
user: GraphqlUser!
}
-"""
-Root entry point for realtime Soup subscriptions.
-"""
-type SoupSubscriptionRoot {
- """
- Subscribe to realtime Soup updates for the authenticated user.
- """
- soupUpdates: [SoupPatch!]!
-}
-
"""
GraphQL representation of a created or updated Soup entity.
"""
@@ -4150,6 +5203,10 @@ input UpdateNotificationsInput {
operation: NotificationUpdateOperation!
}
+"""
+Marks an element of a GraphQL schema as no longer supported.
+"""
+directive @deprecated(reason: String = "No longer supported") on FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION | ENUM_VALUE
"""
Directs the executor to include this field or fragment only when the `if` argument is true.
"""
@@ -4165,6 +5222,6 @@ directive @skip(if: Boolean!) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
schema {
query: SoupQueryRoot
mutation: CompleteMutationRoot
- subscription: SoupSubscriptionRoot
+ subscription: CompleteSubscriptionRoot
}