Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
Seanaye/feat/gql (#4236)
Sean Ayefc500e8f5a3d
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 881a1c772d..3269751794 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -1332,6 +1332,7 @@"frecency","fusionauth","github",+ "graphql_soup","invite_email","ip_extractor","item_filters",@@ -2218,6 +2219,82 @@"models_pagination","workspace-hack"],+ "graphql_soup": [+ "agent",+ "ai_toolset",+ "ai_usage",+ "attachment",+ "authentication_service_client",+ "bot_id",+ "call",+ "channels",+ "connection",+ "connection_gateway_client",+ "connection_gateway_models",+ "contacts",+ "cowlike",+ "crm",+ "decode_jwt",+ "document_sub_type",+ "email",+ "email_db_client",+ "email_utils",+ "entity_access",+ "entity_access_db_utils",+ "filter_ast",+ "foreign_entity",+ "frecency",+ "graphql_soup",+ "invite_email",+ "ip_extractor",+ "item_filters",+ "last_online_tracker",+ "macro_auth",+ "macro_aws_config",+ "macro_db_client",+ "macro_env",+ "macro_env_var",+ "macro_middleware",+ "macro_service_urls",+ "macro_user_id",+ "macro_uuid",+ "mention_utils",+ "model",+ "model-entity",+ "model-error-response",+ "model_file_type",+ "model_notifications",+ "model_user",+ "models_ai_projection",+ "models_bulk_upload",+ "models_dcs",+ "models_email",+ "models_entity_access_management",+ "models_grouping",+ "models_opensearch",+ "models_pagination",+ "models_permissions",+ "models_properties",+ "models_soup",+ "models_team",+ "non_empty",+ "notification",+ "prompt",+ "properties",+ "properties_db_client",+ "rate_limit",+ "readonly_pool",+ "remote_env_var",+ "s3_key",+ "share_permission_db_utils",+ "soup",+ "sqs_client",+ "sqs_worker",+ "system_properties",+ "unfurl",+ "user_quota",+ "workspace-hack"+ ],"image_optimizer": ["image_optimizer","macro_aws_config",@@ -3378,6 +3455,7 @@"notification","prompt","properties",+ "properties_db_client","rate_limit","remote_env_var","system_properties",diff --git a/plan.md b/plan.mdnew file mode 100644index 0000000000..e40347f307--- /dev/null+++ b/plan.md@@ -0,0 +1,260 @@+# Plan: Move GraphQL Soup document properties to a DataLoader edge++## Context++The `graphql_soup` crate currently exposes typed GraphQL Soup entities. `GraphqlSoupDocument` exposes `subType` and `properties` directly from the inline `models_soup::document::SoupDocument` payload.++We want `properties` to become a GraphQL edge resolved via DataLoader instead of reading the inline Soup payload. This decouples GraphQL property hydration from Soup item hydration and prepares the schema for reusable entity property edges.++Keep `subType` inline for now. It is intrinsic document metadata and does not need a DataLoader edge.++## Target GraphQL behavior++Frontend query should continue to look like:++```graphql+... on GraphqlSoupDocument {+ id+ name+ subType {+ kind+ isCompleted+ }+ properties {+ id+ displayName+ dataType+ value {+ kind+ stringValue+ selectOptionIds+ }+ }+}+```++But implementation should resolve `properties` through a DataLoader, not `SoupDocument.properties`.++## Design++### 1. Add reusable property edge key in `graphql_soup`++Use an entity-key shape, not document-only, so this can later support project/chat/email properties.++```rust+#[derive(Debug, Clone, Hash, PartialEq, Eq)]+pub struct EntityPropertiesKey {+ pub entity_type: String,+ pub entity_id: String,+}+```++For documents, build this from:++```rust+EntityPropertiesKey {+ entity_id: self.0.id.to_string(),+ entity_type: self.0.entity_type().to_string(),+}+```++Important: `SoupDocument::entity_type()` returns `Task` for task documents and `Document` otherwise, so this correctly supports task properties.++### 2. Add object-safe property reader trait in `graphql_soup`++Use `async_trait` to avoid pushing generics through every GraphQL type.++```rust+#[async_trait::async_trait]+pub trait SoupPropertyEdgeReader: Send + Sync + 'static {+ async fn get_properties(+ &self,+ keys: Vec<EntityPropertiesKey>,+ ) -> Result<HashMap<EntityPropertiesKey, Vec<SoupProperty>>, rootcause::Report>;+}+```++Add dependencies if needed:++```toml+async-trait = { workspace = true }+rootcause = { workspace = true }+```++### 3. Add DataLoader in `graphql_soup`++Enable async-graphql dataloader feature if needed. Current crate uses `async-graphql = "7.2.1"`; change to include dataloader support if required by this version.++Example shape:++```rust+use async_graphql::dataloader::{DataLoader, Loader};++pub struct EntityPropertiesLoader {+ reader: Arc<dyn SoupPropertyEdgeReader>,+}++impl EntityPropertiesLoader {+ pub fn new(reader: Arc<dyn SoupPropertyEdgeReader>) -> Self {+ Self { reader }+ }+}++#[async_trait::async_trait]+impl Loader<EntityPropertiesKey> for EntityPropertiesLoader {+ type Value = Vec<SoupProperty>;+ type Error = Arc<rootcause::Report>;++ async fn load(+ &self,+ keys: &[EntityPropertiesKey],+ ) -> Result<HashMap<EntityPropertiesKey, Self::Value>, Self::Error> {+ self.reader+ .get_properties(keys.to_vec())+ .await+ .map_err(Arc::new)+ }+}+```++Add a helper:++```rust+pub fn entity_properties_loader(+ reader: Arc<dyn SoupPropertyEdgeReader>,+) -> DataLoader<EntityPropertiesLoader> {+ DataLoader::new(EntityPropertiesLoader::new(reader), tokio::spawn)+}+```++This may require `tokio` as a dependency in `graphql_soup`.++### 4. Change `GraphqlSoupDocument.properties` resolver++Current resolver reads inline properties:++```rust+async fn properties(&self) -> Vec<GraphqlSoupProperty> {+ self.0.properties.iter().cloned().map(GraphqlSoupProperty).collect()+}+```++Change to use DataLoader:++```rust+async fn properties(&self, ctx: &Context<'_>) -> async_graphql::Result<Vec<GraphqlSoupProperty>> {+ let loader = ctx.data::<DataLoader<EntityPropertiesLoader>>()?;+ let key = EntityPropertiesKey {+ entity_id: self.0.id.to_string(),+ entity_type: self.0.entity_type().to_string(),+ };++ let properties = loader.load_one(key).await?.unwrap_or_default();+ Ok(properties.into_iter().map(GraphqlSoupProperty).collect())+}+```++Transition option: If wiring is incomplete, temporarily fall back to inline properties when loader is absent. Preferred final state is strict loader requirement.++### 5. Implement reader in `document_storage_service`++Implement `SoupPropertyEdgeReader` behind the existing `graphql` feature. The implementation should live in DSS or a DSS GraphQL module, not in `soup`.++Possible shape:++```rust+#[cfg(feature = "graphql")]+pub struct DssSoupPropertyEdgeReader {+ // Prefer existing properties service/repo if it has batch APIs.+ // Otherwise use PgPool/read-only pool and add/query a repository method.+}+```++Implementation target:++```rust+#[async_trait::async_trait]+impl graphql_soup::SoupPropertyEdgeReader for DssSoupPropertyEdgeReader {+ async fn get_properties(+ &self,+ keys: Vec<EntityPropertiesKey>,+ ) -> Result<HashMap<EntityPropertiesKey, Vec<SoupProperty>>, rootcause::Report> {+ // Batch fetch properties by entity_type/entity_id.+ // Return empty Vec for keys with no properties.+ }+}+```++Need to inspect existing `properties`, `properties_db_client`, or `system_properties` APIs for an appropriate batch lookup. If none exists, add a batch repo function to the appropriate properties crate.++### 6. Wire loader into DSS GraphQL request handler++Current GraphQL handler is in:++```text+rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs+```++It currently injects:++```rust+request.data(GraphqlSoupRequestContext { ... })+```++Add:++```rust+.data(graphql_soup::entity_properties_loader(+ state.graphql_soup_property_reader.clone(),+))+```++This requires adding a property reader field to `ApiContext` under `#[cfg(feature = "graphql")]`, or including it in a small GraphQL state struct.++Example:++```rust+#[cfg(feature = "graphql")]+pub graphql_soup_property_reader: Arc<dyn graphql_soup::SoupPropertyEdgeReader>,+```++Construct it in `main.rs` when building `ApiContext`.++### 7. Keep crate boundaries clean++Dependency direction should remain:++```text+document_storage_service -> graphql_soup+document_storage_service -> properties/properties_db_client+graphql_soup -> models_soup/models_properties+soup -X-> graphql_soup+soup -X-> properties edge implementation+```++Do not make `soup` aware of GraphQL or the properties edge.++### 8. Validation++Run:++```bash+cd rust/cloud-storage+SQLX_OFFLINE=true cargo check -p graphql_soup+SQLX_OFFLINE=true cargo check -p document_storage_service --features graphql+SQLX_OFFLINE=true just check+SQLX_OFFLINE=true just clippy+just format+```++Note: `just clippy` has recently failed in this environment with an unrelated `sqlx_macros` / `aws_lc` undefined symbol. If it still fails, report that clearly and include successful checks.++## Acceptance criteria++- `GraphqlSoupDocument.properties` resolves via DataLoader.+- DataLoader batches property requests by `(entity_type, entity_id)`.+- Task documents use `entity_type = task`, normal documents use `entity_type = document`.+- Frontend GraphQL field shape remains `properties { ... }`.+- `SoupDocument.properties` is no longer read by the GraphQL resolver.+- Existing REST Soup API remains unchanged.+- GraphQL remains behind `document_storage_service` feature `graphql`, default off.diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex be99653aa2..81501df919 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2,6 +2,12 @@# It is not intended for manual editing.version = 4+[[package]]+name = "Inflector"+version = "0.11.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3"+[[package]]name = "adler2"version = "2.0.1"@@ -482,6 +488,12 @@ dependencies = ["stable_deref_trait",]+[[package]]+name = "ascii_utils"+version = "0.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "71938f30533e4d95a6d17aa530939da3842c2ab6f4f84b9dae68447e4129f74a"+[[package]]name = "askama"version = "0.14.0"@@ -547,6 +559,117 @@ dependencies = ["tokio",]+[[package]]+name = "async-graphql"+version = "7.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1057a9f7ccf2404d94571dec3451ade1cb524790df6f1ada0d19c2a49f6b0f40"+dependencies = [+ "async-graphql-derive",+ "async-graphql-parser",+ "async-graphql-value",+ "async-io",+ "async-trait",+ "asynk-strim",+ "base64 0.22.1",+ "bytes",+ "fast_chemail",+ "fnv",+ "futures-channel",+ "futures-util",+ "handlebars",+ "http 1.4.0",+ "indexmap 2.14.0",+ "lru",+ "mime",+ "multer",+ "num-traits",+ "pin-project-lite",+ "regex",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "static_assertions_next",+ "tempfile",+ "thiserror 2.0.18",+]++[[package]]+name = "async-graphql-axum"+version = "7.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1e37c5532e4b686acf45e7162bc93da91fc2c702fb0d465efc2c20c8f973795"+dependencies = [+ "async-graphql",+ "axum",+ "bytes",+ "futures-util",+ "serde_json",+ "tokio",+ "tokio-stream",+ "tokio-util",+ "tower-service",+]++[[package]]+name = "async-graphql-derive"+version = "7.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e6cbeadc8515e66450fba0985ce722192e28443697799988265d86304d7cc68"+dependencies = [+ "Inflector",+ "async-graphql-parser",+ "darling 0.23.0",+ "proc-macro-crate 3.5.0",+ "proc-macro2",+ "quote",+ "strum",+ "syn 2.0.117",+ "thiserror 2.0.18",+]++[[package]]+name = "async-graphql-parser"+version = "7.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e64ef70f77a1c689111e52076da1cd18f91834bcb847de0a9171f83624b07fbf"+dependencies = [+ "async-graphql-value",+ "pest",+ "serde",+ "serde_json",+]++[[package]]+name = "async-graphql-value"+version = "7.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e3ef112905abea9dea592fc868a6873b10ebd3f983e83308f995d6284e9ba41"+dependencies = [+ "bytes",+ "indexmap 2.14.0",+ "serde",+ "serde_json",+]++[[package]]+name = "async-io"+version = "2.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"+dependencies = [+ "autocfg",+ "cfg-if",+ "concurrent-queue",+ "futures-io",+ "futures-lite 2.6.1",+ "parking",+ "polling",+ "rustix 1.1.4",+ "slab",+ "windows-sys 0.61.2",+]+[[package]]name = "async-lock"version = "3.4.2"@@ -703,6 +826,16 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "asynk-strim"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52697735bdaac441a29391a9e97102c74c6ef0f9b60a40cf109b1b404e29d2f6"+dependencies = [+ "futures-core",+ "pin-project-lite",+]+[[package]]name = "atoi"version = "2.0.0"@@ -3689,6 +3822,8 @@ dependencies = ["ai_usage","analytics_client","anyhow",+ "async-graphql",+ "async-graphql-axum","aws-sdk-dynamodb","aws-sdk-s3","aws-sdk-secretsmanager",@@ -3726,6 +3861,7 @@ dependencies = ["frecency","futures","github",+ "graphql_soup","hex","http-body-util","jsonwebtoken 10.3.0",@@ -4694,6 +4830,15 @@ dependencies = ["regex",]+[[package]]+name = "fast_chemail"+version = "0.9.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "495a39d30d624c2caabe6312bfead73e7717692b44e0b32df168c275a2e8e9e4"+dependencies = [+ "ascii_utils",+]+[[package]]name = "fastrand"version = "1.9.0"@@ -4990,6 +5135,16 @@ dependencies = ["waker-fn",]+[[package]]+name = "futures-lite"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"+dependencies = [+ "futures-core",+ "pin-project-lite",+]+[[package]]name = "futures-macro"version = "0.3.32"@@ -5261,6 +5416,32 @@ dependencies = ["workspace-hack",]+[[package]]+name = "graphql_soup"+version = "0.1.0"+dependencies = [+ "async-graphql",+ "async-trait",+ "either",+ "entity_access",+ "filter_ast",+ "item_filters",+ "macro_user_id",+ "model-entity",+ "models_pagination",+ "models_properties",+ "models_soup",+ "notification",+ "properties",+ "rootcause",+ "serde",+ "serde_json",+ "soup",+ "tokio",+ "uuid",+ "workspace-hack",+]+[[package]]name = "group"version = "0.13.0"@@ -5401,6 +5582,22 @@ dependencies = ["zerocopy",]+[[package]]+name = "handlebars"+version = "6.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d43ccdfe15a81ab0a8af639e90254227c9a46afd9c5f5b6ec7efaa345c4b0f00"+dependencies = [+ "derive_builder",+ "log",+ "num-order",+ "pest",+ "pest_derive",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+]+[[package]]name = "hashbrown"version = "0.12.3"@@ -5495,6 +5692,12 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "hermit-abi"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"+[[package]]name = "hex"version = "0.4.3"@@ -5733,7 +5936,7 @@ dependencies = ["anyhow","async-channel","base64 0.13.1",- "futures-lite",+ "futures-lite 1.13.0","http 0.2.12","infer 0.2.3","pin-project-lite",@@ -8436,6 +8639,21 @@ dependencies = ["num-traits",]+[[package]]+name = "num-modular"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc41a1374056e9672221567958a66c16be12d0e2c1b408761e14d901c237d5e0"++[[package]]+name = "num-order"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "537b596b97c40fcf8056d153049eb22f481c17ebce72a513ec9286e4986d1bb6"+dependencies = [+ "num-modular",+]+[[package]]name = "num-rational"version = "0.4.2"@@ -9040,6 +9258,49 @@ version = "2.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+[[package]]+name = "pest"+version = "2.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e0848c601009d37dfa3430c4666e147e49cdcf1b92ecd3e63657d8a5f19da662"+dependencies = [+ "memchr",+ "ucd-trie",+]++[[package]]+name = "pest_derive"+version = "2.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11f486f1ea21e6c10ed15d5a7c77165d0ee443402f0780849d1768e7d9d6fe77"+dependencies = [+ "pest",+ "pest_generator",+]++[[package]]+name = "pest_generator"+version = "2.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8040c4647b13b210a963c1ed407c1ff4fdfa01c31d6d2a098218702e6664f94f"+dependencies = [+ "pest",+ "pest_meta",+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "pest_meta"+version = "2.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "89815c69d36021a140146f26659a81d6c2afa33d216d736dd4be5381a7362220"+dependencies = [+ "pest",+ "sha2 0.10.9",+]+[[package]]name = "petgraph"version = "0.6.5"@@ -9317,6 +9578,20 @@ dependencies = ["miniz_oxide",]+[[package]]+name = "polling"+version = "3.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"+dependencies = [+ "cfg-if",+ "concurrent-queue",+ "hermit-abi",+ "pin-project-lite",+ "rustix 1.1.4",+ "windows-sys 0.61.2",+]+[[package]]name = "polyval"version = "0.6.2"@@ -9560,6 +9835,7 @@ dependencies = ["models_permissions","models_properties","notification",+ "properties_db_client","schemars 1.2.1","serde","serde_json",@@ -11982,6 +12258,12 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"+[[package]]+name = "static_assertions_next"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7beae5182595e9a8b683fa98c4317f956c9a2dec3b9716990d20023cc60c766"+[[package]]name = "static_file"version = "0.1.0"@@ -12647,6 +12929,7 @@ checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"dependencies = ["bytes","futures-core",+ "futures-io","futures-sink","pin-project-lite","tokio",@@ -13047,6 +13330,12 @@ version = "1.20.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"+[[package]]+name = "ucd-trie"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"+[[package]]name = "unfurl"version = "0.1.0"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 1ea5465520..ab342039f2 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -63,6 +63,7 @@ members = ["prompt","workspace-hack","tools/xtask",+ "graphql_soup",][workspace.dependencies]@@ -74,6 +75,7 @@ async-openai = { version = "0.36.1", features = ["completions","embedding",] }+async-graphql = "7.2.1"async-stream = "0.3.6"async-trait = "0.1.86"aws-config = { version = "1.8.16", features = ["behavior-version-latest"] }diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 2092ef1b55..94642b184b 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -20,7 +20,9 @@ path = "src/doppler_config.rs"[features]connection_gateway = []-default = ["connection_gateway", "location_check"]+default = ["connection_gateway", "delete_document_worker", "location_check"]+delete_document_worker = []+graphql = ["dep:async-graphql", "dep:async-graphql-axum", "dep:graphql_soup"]local = ["local_auth"]local_auth = ["macro_middleware/local_auth"]location_check = []@@ -28,6 +30,8 @@ location_check = [][dependencies]anyhow = { workspace = true }ai_tools = { path = "../ai_tools" }+async-graphql = { workspace = true, optional = true }+async-graphql-axum = { version = "7.0.17", optional = true }aws-sdk-dynamodb = { workspace = true }aws-sdk-s3 = { workspace = true }aws-sdk-secretsmanager = { workspace = true }@@ -69,6 +73,7 @@ entity_access_management = { path = "../entity_access_management" }foreign_entity = { path = "../foreign_entity", features = ["inbound"] }frecency = { path = "../frecency", features = ["postgres"] }futures = { workspace = true }+graphql_soup = { path = "../graphql_soup", optional = true }github = { path = "../github", default-features = false, features = ["axum","inbound",diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex e2b28ef42a..bb4b39411a 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -103,20 +103,18 @@ type DssEmailService = EmailServiceImpl<pub(crate) type DssCrmState =crm::inbound::axum_router::CrmRouterState<DssCrmService, EntityAccessService>;-type DssSoupState = SoupRouterState<- SoupImpl<- PgSoupRepo,- FrecencyQueryServiceImpl<FrecencyPgStorage>,- ReadonlyEmailPreviewAdapter<DssEmailService>,- ChannelListServiceImpl<PgChannelsRepo, PgChannelsRepo, FrecencyPgStorage>,- call::domain::service::CallRecordQueryServiceImpl<call::outbound::pg_call_repo::PgCallRepo>,- DssCrmService,- ForeignEntityServiceType,- >,- DssEmailService,- EntityAccessService,+pub(crate) type DssSoupService = SoupImpl<+ PgSoupRepo,+ FrecencyQueryServiceImpl<FrecencyPgStorage>,+ ReadonlyEmailPreviewAdapter<DssEmailService>,+ ChannelListServiceImpl<PgChannelsRepo, PgChannelsRepo, FrecencyPgStorage>,+ call::domain::service::CallRecordQueryServiceImpl<call::outbound::pg_call_repo::PgCallRepo>,+ DssCrmService,+ ForeignEntityServiceType,>;+type DssSoupState = SoupRouterState<DssSoupService, DssEmailService, EntityAccessService>;+type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;pub(crate) type PropertiesService = PropertiesServiceImpl<@@ -306,6 +304,10 @@ pub(crate) struct ApiContext {pub dynamodb_client: Arc<DynamodbClient>,pub dynamo_db: aws_sdk_dynamodb::Client,pub soup_router_state: DssSoupState,+ #[cfg(feature = "graphql")]+ pub graphql_soup_schema: graphql_soup::SharedSoupSchema<DssSoupService>,+ #[cfg(feature = "graphql")]+ pub graphql_notification_reader: Arc<dyn graphql_soup::SoupNotificationEdgeReader>,pub foreign_entity_state: DssForeignEntityState,pub sqs_client: Arc<sqs_client::SQS>,pub contacts_ingress: Arc<SqsContactsIngress<SqsContactsQueue>>,diff --git a/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs b/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rsnew file mode 100644index 0000000000..4f01b29587--- /dev/null+++ b/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs@@ -0,0 +1,124 @@+use crate::api::context::ApiContext;+use async_graphql::{Response, ServerError, http::GraphiQLSource};+use async_graphql_axum::{GraphQLRequest, GraphQLResponse};+use axum::{+ Router,+ extract::{OriginalUri, State},+ response::Html,+ routing::get,+};+use axum_extra::extract::Cached;+use email::domain::ports::EmailService;+use entity_access::domain::{+ models::{Entity, EntityAccessReceipt, EntityPermission, EntityType, MemberTeamRole},+ ports::EntityAccessService as _,+};+use graphql_soup::GraphqlSoupRequestContext;+use model_user::axum_extractor::OptionalMacroUserExtractor;++pub(crate) fn router() -> Router<ApiContext> {+ Router::new().route("/soup/graphql", get(graphiql).post(handler))+}++async fn graphiql(OriginalUri(uri): OriginalUri) -> Html<String> {+ Html(GraphiQLSource::build().endpoint(uri.path()).finish())+}++async fn handler(+ State(state): State<ApiContext>,+ Cached(OptionalMacroUserExtractor { macro_user_id, .. }): Cached<OptionalMacroUserExtractor>,+ request: GraphQLRequest,+) -> GraphQLResponse {+ let request = request.into_inner();++ let Some(macro_user_id) = macro_user_id else {+ if is_introspection_query(&request.query) {+ return state.graphql_soup_schema.execute(request).await.into();+ }+ return Response::from_errors(vec![ServerError::new(+ "authentication required for GraphQL Soup queries",+ None,+ )])+ .into();+ };++ let link_ids = match state+ .soup_router_state+ .email_service()+ .get_inboxes_for_macro_id(macro_user_id.clone())+ .await+ {+ Ok(links) => links.into_iter().map(|link| link.id).collect(),+ Err(err) => {+ return Response::from_errors(vec![ServerError::new(+ format!("failed to load caller inboxes: {err}"),+ None,+ )])+ .into();+ }+ };++ let team_receipt = match load_team_receipt(&state, ¯o_user_id).await {+ Ok(team_receipt) => team_receipt,+ Err(err) => {+ return Response::from_errors(vec![ServerError::new(+ format!("failed to load caller team: {err:?}"),+ None,+ )])+ .into();+ }+ };++ let property_reader: std::sync::Arc<dyn graphql_soup::SoupPropertyEdgeReader> =+ state.properties_service.clone();+ let request = request+ .data(GraphqlSoupRequestContext {+ macro_user_id: macro_user_id.clone(),+ link_ids,+ team_receipt,+ })+ .data(graphql_soup::entity_properties_loader(property_reader))+ .data(graphql_soup::entity_notifications_loader(+ macro_user_id,+ state.graphql_notification_reader.clone(),+ ));++ state.graphql_soup_schema.execute(request).await.into()+}++fn is_introspection_query(query: &str) -> bool {+ query.contains("__schema") || query.contains("__type")+}++async fn load_team_receipt(+ state: &ApiContext,+ macro_user_id: ¯o_user_id::user_id::MacroUserIdStr<'static>,+) -> async_graphql::Result<Option<EntityAccessReceipt<MemberTeamRole>>> {+ let Some(team_info) = state+ .entity_access_service+ .get_user_team(macro_user_id)+ .await+ .map_err(|err| async_graphql::Error::new(err.to_string()))?+ else {+ return Ok(None);+ };++ let permission = EntityPermission::TeamRole {+ role: team_info.role,+ };++ if !permission.satisfies::<MemberTeamRole>() {+ return Ok(None);+ }++ EntityAccessReceipt::try_new_authenticated_user(+ macro_user_id.clone(),+ Entity {+ entity_id: team_info.team_id.to_string(),+ entity_type: EntityType::Team,+ },+ permission,+ )+ .map(Some)+ .map_err(|err| async_graphql::Error::new(err.to_string()))+}diff --git a/rust/cloud-storage/document_storage_service/src/api/mod.rs b/rust/cloud-storage/document_storage_service/src/api/mod.rsindex f8eea09b20..8da10a2f97 100644--- a/rust/cloud-storage/document_storage_service/src/api/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/api/mod.rs@@ -30,6 +30,8 @@ mod middleware;mod activity;mod annotations;mod documents;+#[cfg(feature = "graphql")]+mod graphql_soup;mod health;mod history;mod instructions;@@ -87,6 +89,13 @@ pub async fn setup_and_serve(state: ApiContext) -> anyhow::Result<()> {.context("error starting service")}+fn items_router(state: ApiContext) -> Router<ApiContext> {+ let router = soup::inbound::axum_router::soup_router(state.soup_router_state.clone());+ #[cfg(feature = "graphql")]+ let router = router.merge(graphql_soup::router());+ router+}+fn api_router(state: ApiContext) -> Router {let github_sync_service_router_state = GithubSyncRouterState {service: state.github_sync_service.clone(),@@ -135,10 +144,7 @@ fn api_router(state: ApiContext) -> Router {]),).nest("/instructions", instructions::router())- .nest(- "/items",- soup::inbound::axum_router::soup_router(state.soup_router_state.clone()),- )+ .nest("/items", items_router(state.clone())).nest("/threads",threads::router(state.clone()).layer(axum::middleware::from_fn(diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex fcb4823273..de9f0d01b3 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -70,6 +70,8 @@ use macro_env_var::maybe_env_vars;use macro_service_urls::{ConnectionGatewayUrl, LexicalServiceUrl, SyncServiceUrl};use macro_sha_count_client::Redis;use notification::domain::service::SqsNotificationIngress;+#[cfg(feature = "graphql")]+use notification::domain::service::{NotificationReaderService, PlatformArnConfig};use notification::outbound::queue::SqsQueue;use opensearch_client::OpensearchClient;use properties::{@@ -268,6 +270,21 @@ async fn main() -> anyhow::Result<()> {let notification_ingress_service = Arc::new(SqsNotificationIngress {queue: ingress_queue.clone(),});+ #[cfg(feature = "graphql")]+ let graphql_notification_reader: Arc<dyn graphql_soup::SoupNotificationEdgeReader> =+ Arc::new(NotificationReaderService {+ repository: notification::outbound::repository::DbNotificationRepository::new(+ db.clone(),+ ),+ queue: ai_tools::ToolNotificationQueue::Sqs(ingress_queue.clone()),+ sns_endpoint: ai_tools::NoOpSnsEndpointManager,+ platform_config: PlatformArnConfig {+ apns_platform_arn: String::new(),+ fcm_platform_arn: String::new(),+ apns_voip_platform_arn: String::new(),+ },+ realtime: notification::domain::ports::NoopNotificationRealtimePublisher,+ });tracing::trace!("initialized notification ingress service");let entity_access_service = Arc::new(@@ -537,7 +554,8 @@ async fn main() -> anyhow::Result<()> {let call_webhook_state = WebhookRouterState::new(call_service.clone());let call_internal_state = InternalCallRouterState::new(call_service.clone());- // Create the SQS worker for delete document processing before config is moved+ // Create the SQS worker for delete document processing before config is moved.+ #[cfg(feature = "delete_document_worker")]let delete_document_worker = sqs_worker::SQSWorker::new(aws_sdk_sqs::Client::new(&aws_config),document_delete_queue.to_string(),@@ -617,21 +635,27 @@ async fn main() -> anyhow::Result<()> {(*entity_access_service).clone(),);+ let soup_service = Arc::new(SoupImpl::new(+ PgSoupRepo::new(readonly_pool::ReadOnlyPool(readonly_db.clone())),+ frecency_service,+ readonly_email_service,+ channel_service_for_soup,+ call_record_query_service,+ crm_service.clone(),+ foreign_entity_service_for_soup,+ ));+let api_context = ApiContext {contacts_ingress: contacts_ingress.clone(),- soup_router_state: SoupRouterState::new(- SoupImpl::new(- PgSoupRepo::new(readonly_pool::ReadOnlyPool(readonly_db.clone())),- frecency_service,- readonly_email_service,- channel_service_for_soup,- call_record_query_service,- crm_service.clone(),- foreign_entity_service_for_soup,- ),+ soup_router_state: SoupRouterState::from_arc(+ soup_service.clone(),email_service,entity_access_service.clone(),),+ #[cfg(feature = "graphql")]+ graphql_soup_schema: graphql_soup::build_schema_from_arc(soup_service),+ #[cfg(feature = "graphql")]+ graphql_notification_reader,github_sync_service: Arc::new(github_sync_service_impl),foreign_entity_state,db: db.clone(),@@ -687,18 +711,21 @@ async fn main() -> anyhow::Result<()> {},};- // Spawn the delete document worker- let delete_worker_ctx = service::delete_document_worker::DeleteDocumentWorkerContext {- worker: Arc::new(delete_document_worker),- db: db.clone(),- s3_client: api_context.s3_client.clone(),- redis_client: api_context.redis_client.clone(),- sync_service_client: api_context.sync_service_client.clone(),- };-- tokio::spawn(async move {- service::delete_document_worker::run_worker(delete_worker_ctx).await;- });+ #[cfg(feature = "delete_document_worker")]+ {+ // Spawn the delete document worker.+ let delete_worker_ctx = service::delete_document_worker::DeleteDocumentWorkerContext {+ worker: Arc::new(delete_document_worker),+ db: db.clone(),+ s3_client: api_context.s3_client.clone(),+ redis_client: api_context.redis_client.clone(),+ sync_service_client: api_context.sync_service_client.clone(),+ };++ tokio::spawn(async move {+ service::delete_document_worker::run_worker(delete_worker_ctx).await;+ });+ }api::setup_and_serve(api_context).await?;diff --git a/rust/cloud-storage/document_storage_service/src/service/mod.rs b/rust/cloud-storage/document_storage_service/src/service/mod.rsindex c5d38b58b3..432bf9171e 100644--- a/rust/cloud-storage/document_storage_service/src/service/mod.rs+++ b/rust/cloud-storage/document_storage_service/src/service/mod.rs@@ -1,5 +1,6 @@pub mod call_search_indexer;pub mod conn_gateway;+#[cfg(feature = "delete_document_worker")]pub mod delete_document_worker;pub mod property_search_indexer;pub mod s3;diff --git a/rust/cloud-storage/graphql_soup/Cargo.toml b/rust/cloud-storage/graphql_soup/Cargo.tomlnew file mode 100644index 0000000000..185a9ec810--- /dev/null+++ b/rust/cloud-storage/graphql_soup/Cargo.toml@@ -0,0 +1,27 @@+[package]+name = "graphql_soup"+version = "0.1.0"+edition = "2024"+publish = false++[dependencies]+async-graphql = { workspace = true, features = ["dataloader"] }+async-trait = { workspace = true }+either = { workspace = true }+entity_access = { path = "../entity_access", default-features = false }+filter_ast = { path = "../filter_ast" }+item_filters = { path = "../item_filters" }+macro_user_id = { path = "../macro_user_id" }+model-entity = { path = "../model-entity" }+models_pagination = { path = "../models_pagination" }+models_properties = { path = "../models_properties" }+models_soup = { path = "../models_soup" }+notification = { path = "../notification" }+properties = { path = "../properties" }+rootcause = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+soup = { path = "../soup", default-features = false, features = ["ports"] }+tokio = { workspace = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/rust/cloud-storage/graphql_soup/src/lib.rs b/rust/cloud-storage/graphql_soup/src/lib.rsnew file mode 100644index 0000000000..ea640e5f0d--- /dev/null+++ b/rust/cloud-storage/graphql_soup/src/lib.rs@@ -0,0 +1,1478 @@+//! GraphQL inbound adapter for Soup.+//!+//! This crate is intentionally additive: it maps GraphQL requests onto the+//! existing `soup` domain service without changing the existing REST API.+#![deny(missing_docs)]++use async_graphql::{+ Context, EmptyMutation, EmptySubscription, Enum, ID, Json, Object, Schema, SimpleObject, Union,+ dataloader::{DataLoader, Loader},+};+use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};+use filter_ast::Expr;+use item_filters::ast::{EntityFilterAst, crm_company::CrmCompanyLiteral};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use models_pagination::{+ Base64Str, CursorWithValAndFilter, PaginatedOpaqueCursor, SimpleSortMethod, TypeEraseCursor,+};+use models_properties::{EntityReference, service::property_value::PropertyValue};+use models_soup::{+ SoupProperty,+ call_record::SoupCallRecord,+ chat::SoupChat,+ comms::{ChannelType, SoupChannel, SoupChannelThread},+ crm_company::SoupCrmCompany,+ document::{SoupDocument, SoupDocumentSubType},+ email_thread::SoupEnrichedEmailThreadPreview,+ foreign_entity::SoupForeignEntity,+ item::SoupItem,+ project::SoupProject,+};+use notification::domain::models::{+ UserNotificationRow,+ request::{NotificationEntityRef, NotificationItemType},+};+use serde_json::Value;+use soup::domain::{+ models::{FrecencySoupItem, SoupQuery, SoupRequest, SoupType},+ ports::SoupService,+};+use std::{collections::HashMap, str::FromStr, sync::Arc};+use uuid::Uuid;++/// Request-scoped data required to execute a Soup GraphQL query.+///+/// The embedding Axum/service layer remains responsible for authentication and+/// for resolving inbox link IDs. This keeps `graphql_soup` independent from the+/// existing REST extractors.+#[derive(Clone)]+pub struct GraphqlSoupRequestContext {+ /// Authenticated Macro user executing the request.+ pub macro_user_id: MacroUserIdStr<'static>,+ /// Link IDs available to the request.+ pub link_ids: Vec<Uuid>,+ /// Optional team access receipt used for CRM-scoped queries.+ pub team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,+}++/// Key for loading properties attached to an entity.+#[derive(Debug, Clone, Hash, PartialEq, Eq)]+pub struct EntityPropertiesKey {+ /// Entity type key used by the property service.+ pub entity_type: String,+ /// Entity ID used by the property service.+ pub entity_id: String,+}++/// Object-safe reader used by GraphQL property edges.+#[async_trait::async_trait]+pub trait SoupPropertyEdgeReader: Send + Sync + 'static {+ /// Load properties for the requested entity keys.+ async fn get_properties(+ &self,+ keys: Vec<EntityPropertiesKey>,+ ) -> Result<HashMap<EntityPropertiesKey, Vec<SoupProperty>>, rootcause::Report>;+}++#[async_trait::async_trait]+impl<T> SoupPropertyEdgeReader for T+where+ T: properties::PropertiesService,+{+ async fn get_properties(+ &self,+ keys: Vec<EntityPropertiesKey>,+ ) -> Result<HashMap<EntityPropertiesKey, Vec<SoupProperty>>, rootcause::Report> {+ let mut result = keys+ .iter()+ .cloned()+ .map(|key| (key, Vec::new()))+ .collect::<HashMap<_, _>>();++ let entity_refs = keys+ .iter()+ .filter_map(+ |key| match property_entity_type_from_key(&key.entity_type) {+ Ok(Some(entity_type)) => {+ Some(Ok(EntityReference::new(key.entity_id.clone(), entity_type)))+ }+ Ok(None) => None,+ Err(err) => Some(Err(err)),+ },+ )+ .collect::<Result<Vec<_>, rootcause::Report>>()?;++ let properties_by_entity = self+ .get_entity_properties_batch(entity_refs)+ .await+ .map_err(|err| rootcause::report!(err))?;++ for (key, properties) in properties_by_entity {+ result.insert(+ EntityPropertiesKey {+ entity_id: key.entity_id,+ entity_type: key.entity_type.to_string(),+ },+ properties.into_iter().map(SoupProperty::from).collect(),+ );+ }++ Ok(result)+ }+}++/// DataLoader for entity property edges.+pub struct EntityPropertiesLoader {+ reader: Arc<dyn SoupPropertyEdgeReader>,+}++impl EntityPropertiesLoader {+ /// Create a new entity properties DataLoader.+ pub fn new(reader: Arc<dyn SoupPropertyEdgeReader>) -> Self {+ Self { reader }+ }+}++impl Loader<EntityPropertiesKey> for EntityPropertiesLoader {+ type Value = Vec<SoupProperty>;+ type Error = Arc<rootcause::Report>;++ async fn load(+ &self,+ keys: &[EntityPropertiesKey],+ ) -> Result<HashMap<EntityPropertiesKey, Self::Value>, Self::Error> {+ self.reader+ .get_properties(keys.to_vec())+ .await+ .map_err(Arc::new)+ }+}++/// Build a DataLoader for entity property edges.+pub fn entity_properties_loader(+ reader: Arc<dyn SoupPropertyEdgeReader>,+) -> DataLoader<EntityPropertiesLoader> {+ DataLoader::new(EntityPropertiesLoader::new(reader), tokio::spawn)+}++/// Key for loading notifications attached to an entity.+#[derive(Debug, Clone, Hash, PartialEq, Eq)]+pub struct EntityNotificationsKey {+ /// Entity type key used by the notification service.+ pub entity_type: String,+ /// Entity ID used by the notification service.+ pub entity_id: String,+}++/// Object-safe reader used by GraphQL notification edges.+#[async_trait::async_trait]+pub trait SoupNotificationEdgeReader: Send + Sync + 'static {+ /// Load notifications for the requested entity keys.+ async fn get_notifications(+ &self,+ user_id: MacroUserIdStr<'static>,+ keys: Vec<EntityNotificationsKey>,+ ) -> Result<+ HashMap<EntityNotificationsKey, Vec<UserNotificationRow<serde_json::Value>>>,+ rootcause::Report,+ >;+}++#[async_trait::async_trait]+impl<T> SoupNotificationEdgeReader for T+where+ T: notification::domain::service::NotificationReader,+{+ async fn get_notifications(+ &self,+ user_id: MacroUserIdStr<'static>,+ keys: Vec<EntityNotificationsKey>,+ ) -> Result<+ HashMap<EntityNotificationsKey, Vec<UserNotificationRow<serde_json::Value>>>,+ rootcause::Report,+ > {+ let mut result = keys+ .iter()+ .cloned()+ .map(|key| (key, Vec::new()))+ .collect::<HashMap<_, _>>();++ let entity_refs = keys+ .iter()+ .map(|key| {+ Ok(NotificationEntityRef {+ entity_type: notification_item_type_from_key(&key.entity_type)?,+ id: key.entity_id.clone(),+ })+ })+ .collect::<Result<Vec<_>, rootcause::Report>>()?;++ let notifications_by_entity = self+ .get_entity_notifications_batch(user_id, entity_refs)+ .await+ .map_err(|err| rootcause::report!(err))?;++ for (key, notifications) in notifications_by_entity {+ result.insert(+ EntityNotificationsKey {+ entity_type: notification_item_type_key(key.entity_type).to_owned(),+ entity_id: key.id,+ },+ notifications,+ );+ }++ Ok(result)+ }+}++/// DataLoader for entity notification edges.+pub struct EntityNotificationsLoader {+ user_id: MacroUserIdStr<'static>,+ reader: Arc<dyn SoupNotificationEdgeReader>,+}++impl EntityNotificationsLoader {+ /// Create a new entity notifications DataLoader.+ pub fn new(+ user_id: MacroUserIdStr<'static>,+ reader: Arc<dyn SoupNotificationEdgeReader>,+ ) -> Self {+ Self { user_id, reader }+ }+}++impl Loader<EntityNotificationsKey> for EntityNotificationsLoader {+ type Value = Vec<UserNotificationRow<serde_json::Value>>;+ type Error = Arc<rootcause::Report>;++ async fn load(+ &self,+ keys: &[EntityNotificationsKey],+ ) -> Result<HashMap<EntityNotificationsKey, Self::Value>, Self::Error> {+ self.reader+ .get_notifications(self.user_id.clone(), keys.to_vec())+ .await+ .map_err(Arc::new)+ }+}++/// Build a DataLoader for entity notification edges.+pub fn entity_notifications_loader(+ user_id: MacroUserIdStr<'static>,+ reader: Arc<dyn SoupNotificationEdgeReader>,+) -> DataLoader<EntityNotificationsLoader> {+ DataLoader::new(+ EntityNotificationsLoader::new(user_id, reader),+ tokio::spawn,+ )+}++/// GraphQL Soup schema type.+pub type SoupSchema<S> = Schema<SoupQueryRoot<S>, EmptyMutation, EmptySubscription>;++/// GraphQL Soup schema type backed by a shared soup service.+pub type SharedSoupSchema<S> = SoupSchema<SharedSoupService<S>>;++/// Object-safe-ish wrapper for sharing a concrete Soup service with GraphQL.+#[derive(Clone)]+pub struct SharedSoupService<S>(Arc<S>);++impl<S> SharedSoupService<S> {+ /// Create a shared Soup service wrapper.+ pub fn new(service: Arc<S>) -> Self {+ Self(service)+ }+}++impl<S> SoupService for SharedSoupService<S>+where+ S: SoupService,+{+ async fn get_user_soup<T>(+ &self,+ req: SoupRequest<T>,+ team_receipt: Option<EntityAccessReceipt<MemberTeamRole>>,+ ) -> Result<soup::domain::ports::SoupOutput<T>, soup::domain::models::SoupErr>+ where+ SoupRequest<T>: soup::domain::models::IntoSoupReqAst,+ T: Clone + serde::Serialize + Send,+ {+ self.0.get_user_soup(req, team_receipt).await+ }++ async fn get_user_soup_grouped(+ &self,+ req: soup::domain::models::GroupedSortRequest<'_>,+ ) -> Result<Vec<soup::domain::models::GroupedSoupItem>, soup::domain::models::SoupErr> {+ self.0.get_user_soup_grouped(req).await+ }+}++/// Root GraphQL query object for Soup.+pub struct SoupQueryRoot<S> {+ service: S,+}++impl<S> SoupQueryRoot<S> {+ /// Create a root GraphQL query object.+ pub fn new(service: S) -> Self {+ Self { service }+ }+}++/// Build a GraphQL schema for Soup backed by the provided service.+pub fn build_schema<S>(service: S) -> SoupSchema<S>+where+ S: SoupService,+{+ Schema::build(+ SoupQueryRoot::new(service),+ EmptyMutation,+ EmptySubscription,+ )+ .finish()+}++/// Build a GraphQL schema for Soup backed by an `Arc`-shared service.+pub fn build_schema_from_arc<S>(service: Arc<S>) -> SharedSoupSchema<S>+where+ S: SoupService,+{+ build_schema(SharedSoupService::new(service))+}++#[Object]+impl<S> SoupQueryRoot<S>+where+ S: SoupService,+{+ /// Fetch a page of Soup items using the existing Soup filter AST format.+ async fn soup(&self, ctx: &Context<'_>, input: SoupInput) -> async_graphql::Result<SoupPage> {+ let request_context = ctx.data::<GraphqlSoupRequestContext>()?;+ let request = input.into_request(request_context)?;++ let effective_filter = request.cursor.filter();+ let team_receipt = resolve_crm_team_receipt(+ requests_crm_scope(effective_filter),+ request_context.team_receipt.clone(),+ )?;+ require_crm_admin_role(requests_crm_admin(effective_filter), &team_receipt)?;++ let page = self.service.get_user_soup(request, team_receipt).await?;+ Ok(SoupPage::from(page.type_erase()))+ }+}++/// Input for `Query.soup`.+#[derive(async_graphql::InputObject)]+pub struct SoupInput {+ /// Maximum number of items to return. Defaults to 20, max 500.+ pub limit: Option<u16>,+ /// Whether to return expanded Soup items. Defaults to true.+ pub expand: Option<bool>,+ /// Simple timestamp sort. Defaults to VIEWED_AT. Frecency is intentionally+ /// not supported by this initial GraphQL adapter.+ pub sort_method: Option<GraphqlSimpleSortMethod>,+ /// Opaque cursor returned by a previous GraphQL Soup response.+ pub cursor: Option<String>,+ /// Existing Soup AST filter payload, represented as GraphQL JSON.+ pub filters: Option<Json<EntityFilterAst>>,+}++impl SoupInput {+ fn into_request(+ self,+ request_context: &GraphqlSoupRequestContext,+ ) -> async_graphql::Result<SoupRequest<EntityFilterAst>> {+ let filter = self.filters.map(|Json(filter)| filter).unwrap_or_default();+ let sort = self+ .sort_method+ .map(SimpleSortMethod::from)+ .unwrap_or(SimpleSortMethod::ViewedAt);++ let cursor = match self.cursor {+ Some(cursor) => {+ let cursor = Base64Str::<+ CursorWithValAndFilter<Uuid, SimpleSortMethod, EntityFilterAst>,+ >::new_from_string(cursor)+ .decode_json()+ .map_err(|err| async_graphql::Error::new(format!("invalid cursor: {err}")))?;+ SoupQuery::new_cursor_simple(cursor)+ }+ None => SoupQuery::new_sort_simple(sort, filter),+ };++ Ok(SoupRequest {+ soup_type: match self.expand {+ Some(false) => SoupType::UnExpanded,+ Some(true) | None => SoupType::Expanded,+ },+ limit: self.limit.unwrap_or(20).min(500),+ cursor,+ user: request_context.macro_user_id.clone(),+ email_preview_view: Default::default(),+ link_ids: request_context.link_ids.clone(),+ })+ }+}++/// GraphQL representation of supported simple Soup sorts.+#[derive(Enum, Copy, Clone, Eq, PartialEq)]+pub enum GraphqlSimpleSortMethod {+ /// Sort by most recently viewed.+ ViewedAt,+ /// Sort by creation timestamp.+ CreatedAt,+ /// Sort by update timestamp.+ UpdatedAt,+ /// Sort by viewed timestamp, falling back to updated timestamp.+ ViewedUpdated,+}++impl From<GraphqlSimpleSortMethod> for SimpleSortMethod {+ fn from(value: GraphqlSimpleSortMethod) -> Self {+ match value {+ GraphqlSimpleSortMethod::ViewedAt => SimpleSortMethod::ViewedAt,+ GraphqlSimpleSortMethod::CreatedAt => SimpleSortMethod::CreatedAt,+ GraphqlSimpleSortMethod::UpdatedAt => SimpleSortMethod::UpdatedAt,+ GraphqlSimpleSortMethod::ViewedUpdated => SimpleSortMethod::ViewedUpdated,+ }+ }+}++/// Page returned by `Query.soup`.+#[derive(SimpleObject)]+pub struct SoupPage {+ /// Items in the current page.+ pub items: Vec<GraphqlSoupItem>,+ /// Opaque cursor for the next page, if one exists.+ pub next_cursor: Option<String>,+ /// Whether more items are available after this page.+ pub has_more: bool,+}++impl From<PaginatedOpaqueCursor<FrecencySoupItem>> for SoupPage {+ fn from(page: PaginatedOpaqueCursor<FrecencySoupItem>) -> Self {+ let has_more = page.next_cursor.is_some();+ Self {+ items: page.items.into_iter().map(GraphqlSoupItem::from).collect(),+ next_cursor: page.next_cursor,+ has_more,+ }+ }+}++/// GraphQL Soup item envelope.+pub struct GraphqlSoupItem {+ id: String,+ entity_type: String,+ frecency_score: f64,+ entity: GraphqlSoupEntity,+}++#[Object]+impl GraphqlSoupItem {+ async fn id(&self) -> &str {+ &self.id+ }++ async fn entity_type(&self) -> &str {+ &self.entity_type+ }++ async fn frecency_score(&self) -> f64 {+ self.frecency_score+ }++ async fn entity(&self) -> &GraphqlSoupEntity {+ &self.entity+ }+}++impl From<FrecencySoupItem> for GraphqlSoupItem {+ fn from(item: FrecencySoupItem) -> Self {+ let FrecencySoupItem {+ item,+ frecency_score,+ ..+ } = item;+ let entity_ref = item.entity();++ Self {+ id: entity_ref.entity_id.into_owned(),+ entity_type: entity_type_name(entity_ref.entity_type).to_owned(),+ frecency_score: frecency_score+ .map(|f| f.data.frecency_score)+ .unwrap_or_default(),+ entity: GraphqlSoupEntity::from(item),+ }+ }+}++/// GraphQL union over expanded Soup entity variants.+#[derive(Union)]+pub enum GraphqlSoupEntity {+ /// Document entity.+ Document(GraphqlSoupDocument),+ /// Chat entity.+ Chat(GraphqlSoupChat),+ /// Project entity.+ Project(GraphqlSoupProject),+ /// Email thread entity.+ EmailThread(GraphqlSoupEmailThread),+ /// Channel entity.+ Channel(GraphqlSoupChannel),+ /// Channel thread entity.+ ChannelThread(GraphqlSoupChannelThread),+ /// Call entity.+ Call(GraphqlSoupCall),+ /// CRM company entity.+ CrmCompany(GraphqlSoupCrmCompany),+ /// Foreign entity.+ ForeignEntity(GraphqlSoupForeignEntity),+}++impl From<SoupItem> for GraphqlSoupEntity {+ fn from(item: SoupItem) -> Self {+ match item {+ SoupItem::Document(item) => Self::Document(GraphqlSoupDocument(item)),+ SoupItem::Chat(item) => Self::Chat(GraphqlSoupChat(item)),+ SoupItem::Project(item) => Self::Project(GraphqlSoupProject(item)),+ SoupItem::EmailThread(item) => Self::EmailThread(GraphqlSoupEmailThread(item)),+ SoupItem::Channel(item) => Self::Channel(GraphqlSoupChannel(item)),+ SoupItem::ChannelThread(item) => Self::ChannelThread(GraphqlSoupChannelThread(item)),+ SoupItem::Call(item) => Self::Call(GraphqlSoupCall(item)),+ SoupItem::CrmCompany(item) => Self::CrmCompany(GraphqlSoupCrmCompany(item)),+ SoupItem::ForeignEntity(item) => Self::ForeignEntity(GraphqlSoupForeignEntity(item)),+ }+ }+}++/// GraphQL document entity.+pub struct GraphqlSoupDocument(SoupDocument);++#[Object]+impl GraphqlSoupDocument {+ async fn id(&self) -> ID {+ ID(self.0.id.to_string())+ }++ async fn name(&self) -> &str {+ &self.0.name+ }++ async fn owner_id(&self) -> String {+ self.0.owner_id.as_ref().to_owned()+ }++ async fn file_type(&self) -> Option<&str> {+ self.0.file_type.as_deref()+ }++ async fn project_id(&self) -> Option<ID> {+ self.0.project_id.map(|id| ID(id.to_string()))+ }++ async fn created_at(&self) -> String {+ self.0.created_at.to_rfc3339()+ }++ async fn updated_at(&self) -> String {+ self.0.updated_at.to_rfc3339()+ }++ async fn viewed_at(&self) -> Option<String> {+ self.0.viewed_at.map(|ts| ts.to_rfc3339())+ }++ async fn deleted_at(&self) -> Option<String> {+ self.0.deleted_at.map(|ts| ts.to_rfc3339())+ }++ async fn sub_type(&self) -> Option<GraphqlSoupDocumentSubType> {+ self.0+ .sub_type+ .as_ref()+ .map(GraphqlSoupDocumentSubType::from)+ }++ async fn properties(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlSoupProperty>> {+ let loader = ctx.data::<DataLoader<EntityPropertiesLoader>>()?;+ let key = EntityPropertiesKey {+ entity_id: self.0.id.to_string(),+ entity_type: self.0.entity_type().to_string(),+ };++ let properties = loader+ .load_one(key)+ .await+ .map_err(|err| async_graphql::Error::new(err.to_string()))?+ .unwrap_or_default();+ Ok(properties.into_iter().map(GraphqlSoupProperty).collect())+ }++ async fn notifications(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {+ load_entity_notifications(+ ctx,+ EntityNotificationsKey {+ entity_id: self.0.id.to_string(),+ entity_type: self.0.entity_type().to_string(),+ },+ )+ .await+ }+}++/// GraphQL document subtype details.+pub struct GraphqlSoupDocumentSubType {+ kind: &'static str,+ is_completed: Option<bool>,+}++impl From<&SoupDocumentSubType> for GraphqlSoupDocumentSubType {+ fn from(value: &SoupDocumentSubType) -> Self {+ match value {+ SoupDocumentSubType::Task { is_completed } => Self {+ kind: "task",+ is_completed: Some(*is_completed),+ },+ SoupDocumentSubType::Snippet {} => Self {+ kind: "snippet",+ is_completed: None,+ },+ }+ }+}++#[Object]+impl GraphqlSoupDocumentSubType {+ async fn kind(&self) -> &str {+ self.kind+ }++ async fn is_completed(&self) -> Option<bool> {+ self.is_completed+ }+}++/// GraphQL notification attached to a Soup entity.+pub struct GraphqlSoupNotification(UserNotificationRow<serde_json::Value>);++#[Object]+impl GraphqlSoupNotification {+ async fn id(&self) -> ID {+ ID(self.0.notification_id.to_string())+ }++ async fn event_type(&self) -> &str {+ &self.0.notification_event_type+ }++ async fn entity_type(&self) -> String {+ self.0.entity.entity_type.to_string()+ }++ async fn entity_id(&self) -> &str {+ &self.0.entity.entity_id+ }++ async fn sent(&self) -> bool {+ self.0.sent+ }++ async fn done(&self) -> bool {+ self.0.done+ }++ async fn seen(&self) -> bool {+ self.0.viewed_at.is_some()+ }++ async fn created_at(&self) -> String {+ self.0.created_at.to_rfc3339()+ }++ async fn viewed_at(&self) -> Option<String> {+ self.0.viewed_at.map(|ts| ts.to_rfc3339())+ }++ async fn updated_at(&self) -> String {+ self.0.updated_at.to_rfc3339()+ }++ async fn sender_id(&self) -> Option<String> {+ self.0.sender_id.as_ref().map(|sender| sender.to_string())+ }++ async fn metadata(&self) -> Json<Value> {+ Json(self.0.notification_metadata.clone())+ }+}++async fn load_entity_notifications(+ ctx: &Context<'_>,+ key: EntityNotificationsKey,+) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {+ let loader = ctx.data::<DataLoader<EntityNotificationsLoader>>()?;+ let notifications = loader+ .load_one(key)+ .await+ .map_err(|err| async_graphql::Error::new(err.to_string()))?+ .unwrap_or_default();+ Ok(notifications+ .into_iter()+ .map(GraphqlSoupNotification)+ .collect())+}++/// GraphQL property attached to a Soup entity.+pub struct GraphqlSoupProperty(SoupProperty);++#[Object]+impl GraphqlSoupProperty {+ async fn id(&self) -> ID {+ ID(self.0.definition.id.to_string())+ }++ async fn display_name(&self) -> &str {+ &self.0.definition.display_name+ }++ async fn data_type(&self) -> String {+ format!("{:?}", self.0.definition.data_type)+ }++ async fn is_multi_select(&self) -> bool {+ self.0.definition.is_multi_select+ }++ async fn specific_entity_type(&self) -> Option<String> {+ self.0+ .definition+ .specific_entity_type+ .map(|entity_type| entity_type.to_string())+ }++ async fn is_system(&self) -> bool {+ self.0.definition.is_system+ }++ async fn is_metadata(&self) -> bool {+ self.0.definition.is_metadata+ }++ async fn value(&self) -> Option<GraphqlSoupPropertyValue> {+ self.0.value.as_ref().map(GraphqlSoupPropertyValue::from)+ }+}++/// GraphQL representation of a property value.+#[derive(SimpleObject)]+pub struct GraphqlSoupPropertyValue {+ kind: String,+ bool_value: Option<bool>,+ number_value: Option<f64>,+ string_value: Option<String>,+ date_value: Option<String>,+ select_option_ids: Vec<ID>,+ entity_references: Vec<GraphqlSoupPropertyEntityReference>,+ links: Vec<String>,+}++impl From<&PropertyValue> for GraphqlSoupPropertyValue {+ fn from(value: &PropertyValue) -> Self {+ match value {+ PropertyValue::Bool(value) => Self {+ kind: "Boolean".to_owned(),+ bool_value: Some(*value),+ number_value: None,+ string_value: None,+ date_value: None,+ select_option_ids: Vec::new(),+ entity_references: Vec::new(),+ links: Vec::new(),+ },+ PropertyValue::Num(value) => Self {+ kind: "Number".to_owned(),+ bool_value: None,+ number_value: Some(*value),+ string_value: None,+ date_value: None,+ select_option_ids: Vec::new(),+ entity_references: Vec::new(),+ links: Vec::new(),+ },+ PropertyValue::Str(value) => Self {+ kind: "String".to_owned(),+ bool_value: None,+ number_value: None,+ string_value: Some(value.clone()),+ date_value: None,+ select_option_ids: Vec::new(),+ entity_references: Vec::new(),+ links: Vec::new(),+ },+ PropertyValue::Date(value) => Self {+ kind: "Date".to_owned(),+ bool_value: None,+ number_value: None,+ string_value: None,+ date_value: Some(value.to_rfc3339()),+ select_option_ids: Vec::new(),+ entity_references: Vec::new(),+ links: Vec::new(),+ },+ PropertyValue::SelectOption(values) => Self {+ kind: "SelectOption".to_owned(),+ bool_value: None,+ number_value: None,+ string_value: None,+ date_value: None,+ select_option_ids: values.iter().map(|id| ID(id.to_string())).collect(),+ entity_references: Vec::new(),+ links: Vec::new(),+ },+ PropertyValue::EntityRef(values) => Self {+ kind: "EntityReference".to_owned(),+ bool_value: None,+ number_value: None,+ string_value: None,+ date_value: None,+ select_option_ids: Vec::new(),+ entity_references: values+ .iter()+ .map(GraphqlSoupPropertyEntityReference::from)+ .collect(),+ links: Vec::new(),+ },+ PropertyValue::Link(values) => Self {+ kind: "Link".to_owned(),+ bool_value: None,+ number_value: None,+ string_value: None,+ date_value: None,+ select_option_ids: Vec::new(),+ entity_references: Vec::new(),+ links: values.clone(),+ },+ }+ }+}++/// GraphQL entity reference stored in a property value.+#[derive(SimpleObject)]+pub struct GraphqlSoupPropertyEntityReference {+ entity_id: String,+ entity_type: String,+ specific_message_id: Option<ID>,+}++impl From<&models_properties::EntityReference> for GraphqlSoupPropertyEntityReference {+ fn from(value: &models_properties::EntityReference) -> Self {+ Self {+ entity_id: value.entity_id.clone(),+ entity_type: value.entity_type.to_string(),+ specific_message_id: value+ .specific_message_id+ .map(|message_id| ID(message_id.to_string())),+ }+ }+}++/// GraphQL chat entity.+pub struct GraphqlSoupChat(SoupChat);++#[Object]+impl GraphqlSoupChat {+ async fn id(&self) -> ID {+ ID(self.0.id.to_string())+ }++ async fn name(&self) -> &str {+ &self.0.name+ }++ async fn owner_id(&self) -> String {+ self.0.owner_id.as_ref().to_owned()+ }++ async fn project_id(&self) -> Option<ID> {+ self.0.project_id.map(|id| ID(id.to_string()))+ }++ async fn is_persistent(&self) -> bool {+ self.0.is_persistent+ }++ async fn created_at(&self) -> String {+ self.0.created_at.to_rfc3339()+ }++ async fn updated_at(&self) -> String {+ self.0.updated_at.to_rfc3339()+ }++ async fn viewed_at(&self) -> Option<String> {+ self.0.viewed_at.map(|ts| ts.to_rfc3339())+ }++ async fn notifications(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {+ load_entity_notifications(+ ctx,+ EntityNotificationsKey {+ entity_id: self.0.id.to_string(),+ entity_type: "chat".to_owned(),+ },+ )+ .await+ }+}++/// GraphQL project entity.+pub struct GraphqlSoupProject(SoupProject);++#[Object]+impl GraphqlSoupProject {+ async fn id(&self) -> ID {+ ID(self.0.id.to_string())+ }++ async fn name(&self) -> &str {+ &self.0.name+ }++ async fn owner_id(&self) -> String {+ self.0.owner_id.as_ref().to_owned()+ }++ async fn parent_id(&self) -> Option<ID> {+ self.0.parent_id.map(|id| ID(id.to_string()))+ }++ async fn created_at(&self) -> String {+ self.0.created_at.to_rfc3339()+ }++ async fn updated_at(&self) -> String {+ self.0.updated_at.to_rfc3339()+ }++ async fn viewed_at(&self) -> Option<String> {+ self.0.viewed_at.map(|ts| ts.to_rfc3339())+ }++ async fn notifications(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {+ load_entity_notifications(+ ctx,+ EntityNotificationsKey {+ entity_id: self.0.id.to_string(),+ entity_type: "project".to_owned(),+ },+ )+ .await+ }+}++/// GraphQL email thread entity.+pub struct GraphqlSoupEmailThread(SoupEnrichedEmailThreadPreview);++#[Object]+impl GraphqlSoupEmailThread {+ async fn id(&self) -> ID {+ ID(self.0.thread.id.to_string())+ }++ async fn owner_id(&self) -> String {+ self.0.thread.owner_id.as_ref().to_owned()+ }++ async fn name(&self) -> Option<&str> {+ self.0.thread.name.as_deref()+ }++ async fn snippet(&self) -> Option<&str> {+ self.0.thread.snippet.as_deref()+ }++ async fn sender_email(&self) -> Option<&str> {+ self.0.thread.sender_email.as_deref()+ }++ async fn sender_name(&self) -> Option<&str> {+ self.0.thread.sender_name.as_deref()+ }++ async fn is_read(&self) -> bool {+ self.0.thread.is_read+ }++ async fn is_draft(&self) -> bool {+ self.0.thread.is_draft+ }++ async fn is_important(&self) -> bool {+ self.0.thread.is_important+ }++ async fn project_id(&self) -> Option<ID> {+ self.0.thread.project_id.as_ref().map(|id| ID(id.clone()))+ }++ async fn sort_ts(&self) -> String {+ self.0.thread.sort_ts.to_rfc3339()+ }++ async fn created_at(&self) -> String {+ self.0.thread.created_at.to_rfc3339()+ }++ async fn updated_at(&self) -> String {+ self.0.thread.updated_at.to_rfc3339()+ }++ async fn viewed_at(&self) -> Option<String> {+ self.0.thread.viewed_at.map(|ts| ts.to_rfc3339())+ }++ async fn attachment_count(&self) -> usize {+ self.0.attachments.len()+ }++ async fn participant_count(&self) -> usize {+ self.0.participants.len()+ }++ async fn notifications(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {+ load_entity_notifications(+ ctx,+ EntityNotificationsKey {+ entity_id: self.0.thread.id.to_string(),+ entity_type: "email".to_owned(),+ },+ )+ .await+ }+}++/// GraphQL channel entity.+pub struct GraphqlSoupChannel(SoupChannel);++#[Object]+impl GraphqlSoupChannel {+ async fn id(&self) -> ID {+ ID(self.0.channel.channel.id.0.to_string())+ }++ async fn name(&self) -> Option<&str> {+ self.0.channel.channel.name.as_deref()+ }++ async fn channel_type(&self) -> &'static str {+ channel_type_name(self.0.channel.channel.channel_type)+ }++ async fn owner_id(&self) -> String {+ self.0.channel.channel.owner_id.as_ref().to_owned()+ }++ async fn team_id(&self) -> Option<ID> {+ self.0.channel.channel.team_id.map(|id| ID(id.to_string()))+ }++ async fn created_at(&self) -> String {+ self.0.channel.channel.created_at.to_rfc3339()+ }++ async fn updated_at(&self) -> String {+ self.0.channel.channel.updated_at.to_rfc3339()+ }++ async fn viewed_at(&self) -> Option<String> {+ self.0.viewed_at.map(|ts| ts.to_rfc3339())+ }++ async fn participant_count(&self) -> usize {+ self.0.channel.participants.len()+ }++ async fn notifications(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {+ load_entity_notifications(+ ctx,+ EntityNotificationsKey {+ entity_id: self.0.channel.channel.id.0.to_string(),+ entity_type: "channel".to_owned(),+ },+ )+ .await+ }+}++/// GraphQL channel thread entity.+pub struct GraphqlSoupChannelThread(SoupChannelThread);++#[Object]+impl GraphqlSoupChannelThread {+ async fn id(&self) -> ID {+ ID(self.0.id.to_string())+ }++ async fn channel_id(&self) -> ID {+ ID(self.0.channel_id.to_string())+ }++ async fn sender_id(&self) -> &str {+ &self.0.sender_id+ }++ async fn content(&self) -> &str {+ &self.0.content+ }++ async fn created_at(&self) -> String {+ self.0.created_at.to_rfc3339()+ }++ async fn updated_at(&self) -> String {+ self.0.updated_at.to_rfc3339()+ }++ async fn effective_updated_at(&self) -> String {+ self.0.effective_updated_at().to_rfc3339()+ }++ async fn reply_count(&self) -> i64 {+ self.0.thread.reply_count+ }++ async fn notifications(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {+ load_entity_notifications(+ ctx,+ EntityNotificationsKey {+ entity_id: self.0.id.to_string(),+ entity_type: "message".to_owned(),+ },+ )+ .await+ }+}++/// GraphQL call entity.+pub struct GraphqlSoupCall(SoupCallRecord);++#[Object]+impl GraphqlSoupCall {+ async fn id(&self) -> ID {+ ID(self.0.call_id.to_string())+ }++ async fn channel_id(&self) -> ID {+ ID(self.0.channel_id.to_string())+ }++ async fn created_by(&self) -> &str {+ &self.0.created_by+ }++ async fn name(&self) -> Option<&str> {+ self.0+ .custom_name+ .as_deref()+ .or(self.0.channel_name.as_deref())+ }++ async fn summary(&self) -> Option<&str> {+ self.0.summary.as_deref()+ }++ async fn started_at(&self) -> String {+ self.0.started_at.to_rfc3339()+ }++ async fn ended_at(&self) -> Option<String> {+ self.0.ended_at.map(|ts| ts.to_rfc3339())+ }++ async fn duration_ms(&self) -> Option<i64> {+ self.0.duration_ms+ }++ async fn is_active(&self) -> bool {+ self.0.is_active+ }++ async fn attended(&self) -> bool {+ self.0.attended+ }++ async fn participant_count(&self) -> usize {+ self.0.participants.len()+ }++ async fn notifications(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {+ load_entity_notifications(+ ctx,+ EntityNotificationsKey {+ entity_id: self.0.call_id.to_string(),+ entity_type: "call".to_owned(),+ },+ )+ .await+ }+}++/// GraphQL CRM company entity.+pub struct GraphqlSoupCrmCompany(SoupCrmCompany);++#[Object]+impl GraphqlSoupCrmCompany {+ async fn id(&self) -> ID {+ ID(self.0.id.to_string())+ }++ async fn team_id(&self) -> ID {+ ID(self.0.team_id.to_string())+ }++ async fn name(&self) -> Option<&str> {+ self.0.name.as_deref()+ }++ async fn description(&self) -> Option<&str> {+ self.0.description.as_deref()+ }++ async fn email_sync(&self) -> bool {+ self.0.email_sync+ }++ async fn hidden(&self) -> bool {+ self.0.hidden+ }++ async fn created_at(&self) -> String {+ self.0.created_at.to_rfc3339()+ }++ async fn updated_at(&self) -> String {+ self.0.updated_at.to_rfc3339()+ }++ async fn viewed_at(&self) -> Option<String> {+ self.0.viewed_at.map(|ts| ts.to_rfc3339())+ }++ async fn domains(&self) -> Vec<String> {+ self.0+ .domains+ .iter()+ .map(|domain| domain.domain.clone())+ .collect()+ }++ async fn notifications(&self) -> Vec<GraphqlSoupNotification> {+ Vec::new()+ }+}++/// GraphQL foreign entity.+pub struct GraphqlSoupForeignEntity(SoupForeignEntity);++#[Object]+impl GraphqlSoupForeignEntity {+ async fn id(&self) -> ID {+ ID(self.0.id.to_string())+ }++ async fn foreign_entity_id(&self) -> &str {+ &self.0.foreign_entity_id+ }++ async fn foreign_entity_source(&self) -> &str {+ &self.0.foreign_entity_source+ }++ async fn stored_for_id(&self) -> &str {+ &self.0.stored_for_id+ }++ async fn stored_for_auth_entity(&self) -> &str {+ &self.0.stored_for_auth_entity+ }++ async fn metadata(&self) -> Json<Value> {+ Json(self.0.metadata.clone())+ }++ async fn created_at(&self) -> String {+ self.0.created_at.to_rfc3339()+ }++ async fn updated_at(&self) -> String {+ self.0.updated_at.to_rfc3339()+ }++ async fn notifications(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlSoupNotification>> {+ load_entity_notifications(+ ctx,+ EntityNotificationsKey {+ entity_id: self.0.foreign_entity_id.clone(),+ entity_type: "github".to_owned(),+ },+ )+ .await+ }+}++fn property_entity_type_from_key(+ key: &str,+) -> Result<Option<models_properties::EntityType>, rootcause::Report> {+ match key {+ "email" | "email_thread" => Ok(Some(models_properties::EntityType::Thread)),+ "crm_company" => Ok(Some(models_properties::EntityType::Company)),+ "call" | "channel_message" | "channel_thread" | "foreign_entity" | "github" => Ok(None),+ other => models_properties::EntityType::from_str(other)+ .map(Some)+ .map_err(|err| {+ rootcause::report!("invalid entity type {other} for property edge: {err}")+ }),+ }+}++fn notification_item_type_from_key(key: &str) -> Result<NotificationItemType, rootcause::Report> {+ match key {+ "email" | "email_thread" => Ok(NotificationItemType::Email),+ "message" | "channel_message" => Ok(NotificationItemType::Message),+ "channel" => Ok(NotificationItemType::Channel),+ "document" => Ok(NotificationItemType::Document),+ "project" => Ok(NotificationItemType::Project),+ "chat" => Ok(NotificationItemType::Chat),+ "call" => Ok(NotificationItemType::Call),+ "task" => Ok(NotificationItemType::Task),+ "github" | "foreign_entity" => Ok(NotificationItemType::Github),+ other => Err(rootcause::report!(+ "unsupported notification entity type {other}"+ )),+ }+}++fn notification_item_type_key(item_type: NotificationItemType) -> &'static str {+ match item_type {+ NotificationItemType::Email => "email",+ NotificationItemType::Message => "message",+ NotificationItemType::Channel => "channel",+ NotificationItemType::Document => "document",+ NotificationItemType::Project => "project",+ NotificationItemType::Chat => "chat",+ NotificationItemType::Call => "call",+ NotificationItemType::Task => "task",+ NotificationItemType::Github => "github",+ }+}++fn channel_type_name(channel_type: ChannelType) -> &'static str {+ match channel_type {+ ChannelType::Public => "public",+ ChannelType::Private => "private",+ ChannelType::DirectMessage => "direct_message",+ ChannelType::Team => "team",+ }+}++fn entity_type_name(entity_type: EntityType) -> &'static str {+ match entity_type {+ EntityType::Document => "document",+ EntityType::Chat => "chat",+ EntityType::Project => "project",+ EntityType::EmailThread => "email_thread",+ EntityType::Channel => "channel",+ EntityType::ChannelMessage => "channel_message",+ EntityType::Call => "call",+ EntityType::CrmCompany => "crm_company",+ EntityType::ForeignEntity => "foreign_entity",+ _ => "unknown",+ }+}++fn resolve_crm_team_receipt(+ crm_scope_requested: bool,+ receipt: Option<EntityAccessReceipt<MemberTeamRole>>,+) -> async_graphql::Result<Option<EntityAccessReceipt<MemberTeamRole>>> {+ if crm_scope_requested && receipt.is_none() {+ return Err(async_graphql::Error::new(+ "CRM-scoped queries require team membership",+ ));+ }+ Ok(receipt)+}++fn require_crm_admin_role(+ admin_requested: bool,+ receipt: &Option<EntityAccessReceipt<MemberTeamRole>>,+) -> async_graphql::Result<()> {+ if !admin_requested {+ return Ok(());+ }+ let Some(receipt) = receipt else {+ return Err(async_graphql::Error::new(+ "Querying hidden CRM companies requires admin/owner team role",+ ));+ };+ if !receipt+ .entity_permission()+ .satisfies::<entity_access::domain::models::AdminTeamRole>()+ {+ return Err(async_graphql::Error::new(+ "Querying hidden CRM companies requires admin/owner team role",+ ));+ }+ Ok(())+}++fn requests_crm_scope(filter: &EntityFilterAst) -> bool {+ filter.email_filter.crm_scope.is_some()+}++fn requests_crm_admin(filter: &EntityFilterAst) -> bool {+ filter+ .crm_company_filter+ .as_deref()+ .is_some_and(ast_requests_crm_admin)+}++fn ast_requests_crm_admin(expr: &Expr<CrmCompanyLiteral>) -> bool {+ match expr {+ Expr::Literal(CrmCompanyLiteral::Hidden(_)) => true,+ Expr::And(a, b) | Expr::Or(a, b) => ast_requests_crm_admin(a) || ast_requests_crm_admin(b),+ Expr::Not(a) => ast_requests_crm_admin(a),+ _ => false,+ }+}diff --git a/rust/cloud-storage/notification/src/domain/models/request.rs b/rust/cloud-storage/notification/src/domain/models/request.rsindex a1b398d41c..5fad9f98c5 100644--- a/rust/cloud-storage/notification/src/domain/models/request.rs+++ b/rust/cloud-storage/notification/src/domain/models/request.rs@@ -17,7 +17,7 @@ use uuid::Uuid;/// User-facing notification categories used for list filtering.#[allow(missing_docs)]-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]#[cfg_attr(feature = "ai_tool", derive(schemars::JsonSchema))]#[serde(rename_all = "camelCase")]pub enum NotificationItemType {@@ -49,7 +49,7 @@ impl NotificationItemType {}/// User-facing reference to one specific entity to filter notifications by.-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]#[cfg_attr(feature = "ai_tool", derive(schemars::JsonSchema))]#[serde(rename_all = "camelCase")]pub struct NotificationEntityRef {diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rsindex d1d7bbb2c1..20615e782f 100644--- a/rust/cloud-storage/notification/src/domain/ports.rs+++ b/rust/cloud-storage/notification/src/domain/ports.rs@@ -19,7 +19,7 @@ use crate::domain::models::device::DeviceType;use crate::domain::models::{PatchDelete, TaggedContent, UserNotificationStatusUpdate};use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};-use crate::domain::models::request::NotificationListFilters;+use crate::domain::models::request::{NotificationEntityRef, NotificationListFilters};use crate::domain::models::{DeviceEndpoint, DisabledNotificationType, NotificationExtEmail, NotificationIdAndCollapseKey,NotificationStatusPatch, SendNotificationRequestBuilder, UserNotificationRow, VoipPushTarget,@@ -146,6 +146,18 @@ pub trait NotificationRepository: Send + Sync + 'static {filters: NotificationListFilters,) -> impl Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;+ /// Get a user's active notifications for multiple entities, grouped by requested entity.+ fn get_entity_notifications_batch(+ &self,+ user_id: MacroUserIdStr<'_>,+ entity_refs: Vec<NotificationEntityRef>,+ ) -> impl Future<+ Output = Result<+ HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>,+ Report,+ >,+ > + Send;+/// Get a single user notification by ID.////// Returns `None` if no active (non-deleted) notification exists for the given user and ID.diff --git a/rust/cloud-storage/notification/src/domain/service/device/test.rs b/rust/cloud-storage/notification/src/domain/service/device/test.rsindex 33e8c5a04b..5eeaf78cb6 100644--- a/rust/cloud-storage/notification/src/domain/service/device/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/device/test.rs@@ -191,6 +191,22 @@ impl NotificationRepository for MockNotifRepo {) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {unimplemented!()}+ async fn get_entity_notifications_batch(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ entity_refs: Vec<crate::domain::models::request::NotificationEntityRef>,+ ) -> Result<+ std::collections::HashMap<+ crate::domain::models::request::NotificationEntityRef,+ Vec<crate::domain::models::UserNotificationRow<serde_json::Value>>,+ >,+ Report,+ > {+ Ok(entity_refs+ .into_iter()+ .map(|entity_ref| (entity_ref, Vec::new()))+ .collect())+ }async fn get_user_notification_by_id<T: serde::de::DeserializeOwned + Send>(&self,_: macro_user_id::user_id::MacroUserIdStr<'_>,diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rsindex 22b1bf0535..bd52a2b7cc 100644--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs@@ -13,8 +13,9 @@ use crate::domain::models::queue_message::{QueueMessageNeedsStateMachine, UserApnsEndpoints,};use crate::domain::models::request::{- BuildApnsOutput, GetNotificationsByEventItemIdsRequest, NotificationListFilters,- NotificationStatus, SendNotificationRequest, UpdateNotificationsRequest,+ BuildApnsOutput, GetNotificationsByEventItemIdsRequest, NotificationEntityRef,+ NotificationListFilters, NotificationStatus, SendNotificationRequest,+ UpdateNotificationsRequest,};use crate::domain::models::{DeviceEndpoint, DisabledNotificationType, Notification, NotificationResult,@@ -79,6 +80,18 @@ pub trait NotificationReader: Send + Sync + 'static {req: GetNotificationsByEventItemIdsRequest<'_>,) -> impl Future<Output = Result<Paginated<UserNotificationRow<T>, String>, Report>> + Send;+ /// Get a user's active notifications for multiple entities, grouped by requested entity.+ fn get_entity_notifications_batch(+ &self,+ user_id: MacroUserIdStr<'_>,+ entity_refs: Vec<NotificationEntityRef>,+ ) -> impl Future<+ Output = Result<+ HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>,+ Report,+ >,+ > + Send;+/// Get a single user notification by ID.fn get_user_notification_by_id<T: DeserializeOwned + Send>(&self,@@ -650,6 +663,18 @@ whereOk(paginated)}+ #[tracing::instrument(err, skip(self))]+ async fn get_entity_notifications_batch(+ &self,+ user_id: MacroUserIdStr<'_>,+ entity_refs: Vec<NotificationEntityRef>,+ ) -> Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>, Report>+ {+ self.repository+ .get_entity_notifications_batch(user_id, entity_refs)+ .await+ }+#[tracing::instrument(err, skip(self))]async fn get_user_notification_by_id<T: DeserializeOwned + Send>(&self,diff --git a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rsindex 5e1f003a04..2060e23490 100644--- a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs@@ -158,6 +158,22 @@ impl NotificationRepository for MockNotifRepo {) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {unimplemented!()}+ async fn get_entity_notifications_batch(+ &self,+ _: macro_user_id::user_id::MacroUserIdStr<'_>,+ entity_refs: Vec<crate::domain::models::request::NotificationEntityRef>,+ ) -> Result<+ std::collections::HashMap<+ crate::domain::models::request::NotificationEntityRef,+ Vec<crate::domain::models::UserNotificationRow<serde_json::Value>>,+ >,+ Report,+ > {+ Ok(entity_refs+ .into_iter()+ .map(|entity_ref| (entity_ref, Vec::new()))+ .collect())+ }async fn get_user_notification_by_id<T: serde::de::DeserializeOwned + Send>(&self,_: macro_user_id::user_id::MacroUserIdStr<'_>,diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rsindex 596769bc11..0698e4fe10 100644--- a/rust/cloud-storage/notification/src/domain/service/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/test.rs@@ -315,6 +315,23 @@ impl NotificationRepository for MockRepository {Ok(vec![])}+ async fn get_entity_notifications_batch(+ &self,+ _user_id: MacroUserIdStr<'_>,+ entity_refs: Vec<crate::domain::models::request::NotificationEntityRef>,+ ) -> Result<+ std::collections::HashMap<+ crate::domain::models::request::NotificationEntityRef,+ Vec<UserNotificationRow<serde_json::Value>>,+ >,+ Report,+ > {+ Ok(entity_refs+ .into_iter()+ .map(|entity_ref| (entity_ref, Vec::new()))+ .collect())+ }+async fn get_user_notification_by_id<T: DeserializeOwned + Send>(&self,_user_id: MacroUserIdStr<'_>,@@ -516,6 +533,23 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {.await}+ async fn get_entity_notifications_batch(+ &self,+ _user_id: MacroUserIdStr<'_>,+ entity_refs: Vec<crate::domain::models::request::NotificationEntityRef>,+ ) -> Result<+ std::collections::HashMap<+ crate::domain::models::request::NotificationEntityRef,+ Vec<UserNotificationRow<serde_json::Value>>,+ >,+ Report,+ > {+ Ok(entity_refs+ .into_iter()+ .map(|entity_ref| (entity_ref, Vec::new()))+ .collect())+ }+async fn get_user_notification_by_id<T: DeserializeOwned + Send>(&self,user_id: MacroUserIdStr<'_>,diff --git a/rust/cloud-storage/notification/src/domain/service/voip/test.rs b/rust/cloud-storage/notification/src/domain/service/voip/test.rsindex 9e2af1c621..0a03e47faa 100644--- a/rust/cloud-storage/notification/src/domain/service/voip/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/voip/test.rs@@ -180,6 +180,22 @@ impl NotificationRepository for MockRepo {) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {unimplemented!()}+ async fn get_entity_notifications_batch(+ &self,+ _: MacroUserIdStr<'_>,+ entity_refs: Vec<crate::domain::models::request::NotificationEntityRef>,+ ) -> Result<+ std::collections::HashMap<+ crate::domain::models::request::NotificationEntityRef,+ Vec<crate::domain::models::UserNotificationRow<serde_json::Value>>,+ >,+ Report,+ > {+ Ok(entity_refs+ .into_iter()+ .map(|entity_ref| (entity_ref, Vec::new()))+ .collect())+ }async fn get_user_notification_by_id<T: serde::de::DeserializeOwned + Send>(&self,_: MacroUserIdStr<'_>,diff --git a/rust/cloud-storage/notification/src/inbound/http/test.rs b/rust/cloud-storage/notification/src/inbound/http/test.rsindex b39361b2d8..11064a0dbe 100644--- a/rust/cloud-storage/notification/src/inbound/http/test.rs+++ b/rust/cloud-storage/notification/src/inbound/http/test.rs@@ -1,4 +1,4 @@-use std::collections::HashSet;+use std::collections::{HashMap, HashSet};use axum::{Router, http::Request};use hmac::{Hmac, Mac};@@ -17,7 +17,10 @@ use crate::domain::{models::{DisabledNotificationType, UserNotificationRow,device::DeviceType,- request::{GetNotificationsByEventItemIdsRequest, UpdateNotificationsRequest},+ request::{+ GetNotificationsByEventItemIdsRequest, NotificationEntityRef,+ UpdateNotificationsRequest,+ },signing::SignedUrl,},service::NotificationReader,@@ -56,6 +59,19 @@ impl NotificationReader for UnreachableService {async { unreachable!("should not be called") }}+ fn get_entity_notifications_batch(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _entity_refs: Vec<NotificationEntityRef>,+ ) -> impl Future<+ Output = Result<+ HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>,+ Report,+ >,+ > + Send {+ async { unreachable!("should not be called") }+ }+fn get_user_notification_by_id<T: DeserializeOwned + Send>(&self,_user_id: MacroUserIdStr<'_>,@@ -450,6 +466,19 @@ impl NotificationReader for PresignedTestService {async { unreachable!() }}+ fn get_entity_notifications_batch(+ &self,+ _user_id: MacroUserIdStr<'_>,+ _entity_refs: Vec<NotificationEntityRef>,+ ) -> impl Future<+ Output = Result<+ HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>,+ Report,+ >,+ > + Send {+ async { unreachable!() }+ }+fn get_user_notification_by_id<T: DeserializeOwned + Send>(&self,_user_id: MacroUserIdStr<'_>,diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rsindex 45102ec6ea..e5704225ce 100644--- a/rust/cloud-storage/notification/src/outbound/repository.rs+++ b/rust/cloud-storage/notification/src/outbound/repository.rs@@ -4,7 +4,9 @@mod test;use crate::domain::models::device::DeviceType;-use crate::domain::models::request::NotificationListFilters;+use crate::domain::models::request::{+ NotificationEntityRef, NotificationItemType, NotificationListFilters,+};use crate::domain::models::{DeviceEndpoint, DisabledNotificationType, NotificationIdAndCollapseKey,NotificationStatusPatch, PatchDelete, SendNotificationRequestBuilder, TaggedContent,@@ -247,6 +249,65 @@ fn push_entities_filter<'a>(builder: &mut QueryBuilder<'a, Postgres>, entity_tok}}+fn notification_ref_matches_row(+ entity_ref: &NotificationEntityRef,+ event_item_id: &str,+ event_item_type: &str,+ notification_event_type: &str,+ metadata: &serde_json::Value,+) -> bool {+ if entity_ref.entity_type == NotificationItemType::Message {+ return metadata+ .get("messageId")+ .or_else(|| metadata.get("message_id"))+ .and_then(|value| value.as_str())+ .is_some_and(|message_id| message_id == entity_ref.id);+ }++ if entity_ref.id != event_item_id {+ return false;+ }++ match entity_ref.entity_type {+ NotificationItemType::Email => event_item_type == "email_thread",+ NotificationItemType::Channel => event_item_type == "channel",+ NotificationItemType::Document => {+ event_item_type == "document" && !notification_metadata_is_task(metadata)+ }+ NotificationItemType::Task => {+ event_item_type == "document" && notification_metadata_is_task(metadata)+ }+ NotificationItemType::Project => event_item_type == "project",+ NotificationItemType::Chat => event_item_type == "chat",+ NotificationItemType::Call => event_item_type == "call",+ NotificationItemType::Github => {+ event_item_type == "foreign_entity"+ && notification_event_type_is_github(notification_event_type)+ }+ NotificationItemType::Message => false,+ }+}++fn notification_metadata_is_task(metadata: &serde_json::Value) -> bool {+ metadata+ .get("subType")+ .or_else(|| metadata.get("sub_type"))+ .and_then(|value| value.as_str())+ == Some("task")+}++fn notification_event_type_is_github(notification_event_type: &str) -> bool {+ matches!(+ notification_event_type,+ "github_pr_status_changed"+ | "github_review_requested"+ | "github_pr_comment"+ | "github_pr_mention"+ | "github_pr_review"+ | "github_pr_check_run"+ )+}+fn push_cursor_filter(builder: &mut QueryBuilder<'_, Postgres>,cursor_timestamp: Option<DateTime<Utc>>,@@ -388,6 +449,18 @@ pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {filters: NotificationListFilters,) -> impl std::future::Future<Output = Result<Vec<UserNotificationRow<T>>, Report>> + Send;+ /// Get a user's active notifications for multiple entities, grouped by requested entity.+ fn get_entity_notifications_batch(+ &self,+ user_id: MacroUserIdStr<'_>,+ entity_refs: Vec<NotificationEntityRef>,+ ) -> impl std::future::Future<+ Output = Result<+ HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>,+ Report,+ >,+ > + Send;+/// Get a single user notification by ID.fn get_user_notification_by_id<T: DeserializeOwned + Send>(&self,@@ -1002,6 +1075,143 @@ impl NotificationDbOps for PgPool {Ok(notifications)}+ async fn get_entity_notifications_batch(+ &self,+ user_id: MacroUserIdStr<'_>,+ entity_refs: Vec<NotificationEntityRef>,+ ) -> Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>, Report>+ {+ let mut seen_entity_refs = HashSet::new();+ let entity_refs = entity_refs+ .into_iter()+ .filter(|entity_ref| seen_entity_refs.insert(entity_ref.clone()))+ .collect::<Vec<_>>();++ let mut result = entity_refs+ .iter()+ .cloned()+ .map(|entity_ref| (entity_ref, Vec::new()))+ .collect::<HashMap<_, _>>();++ if entity_refs.is_empty() {+ return Ok(result);+ }++ let filters = NotificationListFilters {+ done: Some(false),+ seen: None,+ include_types: Vec::new(),+ entities: entity_refs.clone(),+ };+ let entity_tokens = filters.entity_tokens();++ let mut builder = QueryBuilder::new(+ r#"+ SELECT+ un.user_id as owner_id,+ un.notification_id,+ n.event_item_id,+ n.event_item_type,+ un.sent,+ un.done,+ un.created_at::timestamptz as created_at,+ un.seen_at::timestamptz as viewed_at,+ un.created_at::timestamptz as updated_at,+ un.deleted_at::timestamptz as deleted_at,+ n.metadata as notification_metadata,+ n.notification_event_type as notification_event_type,+ n.sender_id as sender_id+ FROM user_notification un+ JOIN notification n ON n.id = un.notification_id+ WHERE un.user_id = "#,+ );+ builder.push_bind(user_id.as_ref());+ push_notification_status_filters(&mut builder, &filters);+ push_entities_filter(&mut builder, &entity_tokens);+ builder.push(" ORDER BY un.created_at DESC, un.notification_id DESC");++ let rows = builder+ .build_query_as::<UserNotificationListRow>()+ .fetch_all(self)+ .await?;++ for row in rows {+ let (+ owner_id,+ notification_id,+ event_item_id,+ event_item_type,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata,+ notification_event_type,+ sender_id,+ ) = row;++ let entity = match EntityType::from_str(&event_item_type) {+ Ok(entity_type) => entity_type.with_entity_string(event_item_id.clone()),+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;+ }+ };+ let sender_id = match sender_id+ .map(|s| MacroUserIdStr::parse_from_str(&s).map(CowLike::into_owned))+ .transpose()+ {+ Ok(sender_id) => sender_id,+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;+ }+ };+ let owner_id = match MacroUserIdStr::parse_from_str(&owner_id).map(CowLike::into_owned)+ {+ Ok(owner_id) => owner_id,+ Err(e) => {+ tracing::warn!(?notification_id, error = ?e, "skipping invalid notification");+ continue;+ }+ };++ let notification = UserNotificationRow {+ owner_id,+ notification_id,+ notification_event_type: notification_event_type.clone(),+ entity,+ sent,+ done,+ created_at,+ viewed_at,+ updated_at,+ deleted_at,+ notification_metadata: notification_metadata.clone(),+ sender_id,+ };++ for entity_ref in &entity_refs {+ if notification_ref_matches_row(+ entity_ref,+ &event_item_id,+ &event_item_type,+ ¬ification_event_type,+ ¬ification_metadata,+ ) {+ result+ .entry(entity_ref.clone())+ .or_default()+ .push(notification.clone());+ }+ }+ }++ Ok(result)+ }+async fn get_user_notification_by_id<T: DeserializeOwned + Send>(&self,user_id: MacroUserIdStr<'_>,@@ -1344,6 +1554,17 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati.await}+ async fn get_entity_notifications_batch(+ &self,+ user_id: MacroUserIdStr<'_>,+ entity_refs: Vec<NotificationEntityRef>,+ ) -> Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>, Report>+ {+ self.db+ .get_entity_notifications_batch(user_id, entity_refs)+ .await+ }+async fn get_user_notification_by_id<T: DeserializeOwned + Send>(&self,user_id: MacroUserIdStr<'_>,diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rsindex 7926a9e384..ce9c55f6b3 100644--- a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs+++ b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs@@ -1,7 +1,7 @@use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{CreatedAt, Query};use notification::domain::models::TaggedContent;-use notification::domain::models::request::NotificationListFilters;+use notification::domain::models::request::{NotificationEntityRef, NotificationListFilters};use notification::domain::models::{DeviceEndpoint, NotificationIdAndCollapseKey, NotificationStatusPatch,SendNotificationRequestBuilder, UserNotificationRow, device::DeviceType,@@ -156,6 +156,17 @@ impl NotificationRepository for SandboxNotificationRepository {.await}+ async fn get_entity_notifications_batch(+ &self,+ user_id: MacroUserIdStr<'_>,+ entity_refs: Vec<NotificationEntityRef>,+ ) -> Result<HashMap<NotificationEntityRef, Vec<UserNotificationRow<serde_json::Value>>>, Report>+ {+ self.inner+ .get_entity_notifications_batch(user_id, entity_refs)+ .await+ }+async fn get_user_notification_by_id<T: DeserializeOwned + Send>(&self,user_id: MacroUserIdStr<'_>,diff --git a/rust/cloud-storage/properties/Cargo.toml b/rust/cloud-storage/properties/Cargo.tomlindex d7e09dc390..e47e1e7074 100644--- a/rust/cloud-storage/properties/Cargo.toml+++ b/rust/cloud-storage/properties/Cargo.toml@@ -29,6 +29,7 @@ model_notifications = { path = "../model_notifications" }model-entity = { path = "../model-entity" }models_permissions = { path = "../models_permissions" }models_properties = { path = "../models_properties" }+properties_db_client = { path = "../properties_db_client" }schemars = { workspace = true, optional = true }serde = { workspace = true }serde_json = { workspace = true }diff --git a/rust/cloud-storage/properties/src/domain/model.rs b/rust/cloud-storage/properties/src/domain/model.rsindex 341d05ceb8..5a33817457 100644--- a/rust/cloud-storage/properties/src/domain/model.rs+++ b/rust/cloud-storage/properties/src/domain/model.rs@@ -1,10 +1,26 @@//! Domain models for properties.-use models_properties::DataType;use models_properties::service::property_option::PropertyOptionValue;use models_properties::service::property_value::PropertyValue;+use models_properties::{DataType, EntityReference, EntityType};use uuid::Uuid;+/// Key identifying the properties attached to one entity.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct EntityPropertiesKey {+ pub entity_id: String,+ pub entity_type: EntityType,+}++impl From<&EntityReference> for EntityPropertiesKey {+ fn from(value: &EntityReference) -> Self {+ Self {+ entity_id: value.entity_id.clone(),+ entity_type: value.entity_type,+ }+ }+}+/// Summary of a property attached to an entity, including its definition and current value.#[derive(Debug, Clone)]pub struct EntityPropertyInfo {diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rsindex 10171e2143..d3aa070899 100644--- a/rust/cloud-storage/properties/src/domain/ports.rs+++ b/rust/cloud-storage/properties/src/domain/ports.rs@@ -3,15 +3,18 @@//! These traits define the interfaces that the domain layer uses.//! Implementations live in the outbound module.+use std::collections::HashMap;+use macro_user_id::user_id::MacroUserIdStr;use model_notifications::TaskAssignedMetadata;-use models_properties::EntityType;+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::service::property_definition::PropertyDefinition;use models_properties::service::property_value::PropertyValue;+use models_properties::{EntityReference, EntityType};use notification::domain::models::SendNotificationRequest;use uuid::Uuid;-use super::model::EntityPropertyInfo;+use super::model::{EntityPropertiesKey, EntityPropertyInfo};/// Repository trait for property operations.///@@ -100,6 +103,15 @@ pub trait PropertiesRepo: Send + Sync + 'static {entity_type: EntityType,) -> impl Future<Output = Result<Vec<EntityPropertyInfo>, Self::Err>> + Send;+ /// Get all properties attached to multiple entities, keyed by entity id and type.+ /// Returns properties sorted by display name for each entity.+ fn get_entity_properties_batch(+ &self,+ entity_refs: Vec<EntityReference>,+ ) -> impl Future<+ Output = Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, Self::Err>,+ > + Send;+/// Get the name of a document./// Returns `None` if the document doesn't exist or has no name./// Tasks are stored as documents, so this works for both documents and tasks.diff --git a/rust/cloud-storage/properties/src/domain/service.rs b/rust/cloud-storage/properties/src/domain/service.rsindex 7b98a4e9a8..a639a89a8a 100644--- a/rust/cloud-storage/properties/src/domain/service.rs+++ b/rust/cloud-storage/properties/src/domain/service.rs@@ -1,13 +1,16 @@//! Service trait for properties.-use models_properties::EntityType;+use std::collections::HashMap;+use models_properties::api::requests::SetPropertyValue;+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::service::property_value::PropertyValue;+use models_properties::{EntityReference, EntityType};use system_properties::SystemPropertyKey;use uuid::Uuid;use super::error::PropertiesErr;-use super::model::EntityPropertyInfo;+use super::model::{EntityPropertiesKey, EntityPropertyInfo};/// Service trait for property operations.pub trait PropertiesService: Send + Sync + 'static {@@ -53,6 +56,17 @@ pub trait PropertiesService: Send + Sync + 'static {entity_type: EntityType,) -> impl Future<Output = Result<Vec<EntityPropertyInfo>, PropertiesErr>> + Send;+ /// Get all properties attached to multiple entities, keyed by entity id and type.+ fn get_entity_properties_batch(+ &self,+ entity_refs: Vec<EntityReference>,+ ) -> impl Future<+ Output = Result<+ HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>,+ PropertiesErr,+ >,+ > + Send;+/// Get a property value for an entity by property definition ID./// Returns `None` if the property is not attached to the entity.fn get_property_value(diff --git a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs b/rust/cloud-storage/properties/src/domain/service_impl/mod.rsindex cdd0d8c4dd..36715df336 100644--- a/rust/cloud-storage/properties/src/domain/service_impl/mod.rs+++ b/rust/cloud-storage/properties/src/domain/service_impl/mod.rs@@ -3,17 +3,20 @@mod helpers;mod task_properties;-use models_properties::EntityType;+use std::collections::HashMap;+use models_properties::api::requests::SetPropertyValue;use models_properties::convert_set_property_value_to_property_value;+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::service::property_value::PropertyValue;+use models_properties::{EntityReference, EntityType};use system_properties::{StatusOption, SystemPropertyKey};use uuid::Uuid;-use super::error::PropertiesErr;-use super::model::EntityPropertyInfo;use std::sync::Arc;+use super::error::PropertiesErr;+use super::model::{EntityPropertiesKey, EntityPropertyInfo};use super::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer};use super::service::PropertiesService;@@ -188,6 +191,19 @@ where.map_err(anyhow::Error::from)?)}+ #[tracing::instrument(skip(self), err)]+ async fn get_entity_properties_batch(+ &self,+ entity_refs: Vec<EntityReference>,+ ) -> Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, PropertiesErr>+ {+ Ok(self+ .repository+ .get_entity_properties_batch(entity_refs)+ .await+ .map_err(anyhow::Error::from)?)+ }+#[tracing::instrument(skip(self), fields(entity_id = %entity_id, entity_type = ?entity_type, property_definition_id = %property_definition_id))]async fn get_property_value(&self,diff --git a/rust/cloud-storage/properties/src/lib.rs b/rust/cloud-storage/properties/src/lib.rsindex b18d7c5800..f98a5da99b 100644--- a/rust/cloud-storage/properties/src/lib.rs+++ b/rust/cloud-storage/properties/src/lib.rs@@ -15,7 +15,7 @@ pub mod inbound;pub mod outbound;pub use domain::error::PropertiesErr;-pub use domain::model::{EntityPropertyInfo, PropertyOptionInfo};+pub use domain::model::{EntityPropertiesKey, EntityPropertyInfo, PropertyOptionInfo};pub use domain::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer,};diff --git a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rsindex 57f36d4c8d..e5070b875b 100644--- a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs+++ b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs@@ -1,15 +1,17 @@//! PostgreSQL implementation for properties repository.-use models_properties::EntityType;+use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;use models_properties::service::property_value::PropertyValue;+use models_properties::{EntityReference, EntityType};use sqlx::{Pool, Postgres};+use std::collections::HashMap;use uuid::Uuid;use super::{entity_properties_get_query, entity_property_queries, property_definition_queries,task_property_queries,};-use crate::domain::model::EntityPropertyInfo;+use crate::domain::model::{EntityPropertiesKey, EntityPropertyInfo};use crate::domain::ports::PropertiesRepo;use models_properties::service::property_definition::PropertyDefinition;@@ -111,6 +113,34 @@ impl PropertiesRepo for PropertiesPgRepo {entity_properties_get_query::get_entity_properties(&self.pool, entity_id, entity_type).await}+ #[tracing::instrument(skip(self), err)]+ async fn get_entity_properties_batch(+ &self,+ entity_refs: Vec<EntityReference>,+ ) -> Result<HashMap<EntityPropertiesKey, Vec<EntityPropertyWithDefinition>>, Self::Err> {+ let mut result = entity_refs+ .iter()+ .map(|entity_ref| (EntityPropertiesKey::from(entity_ref), Vec::new()))+ .collect::<HashMap<_, _>>();++ let properties_by_entity_id =+ properties_db_client::entity_properties::get::get_bulk_entity_properties_values(+ &self.pool,+ &entity_refs,+ )+ .await?;++ for property in properties_by_entity_id.into_values().flatten() {+ let key = EntityPropertiesKey {+ entity_id: property.property.entity_id.clone(),+ entity_type: property.property.entity_type,+ };+ result.entry(key).or_default().push(property);+ }++ Ok(result)+ }+#[tracing::instrument(skip(self))]async fn get_entity_property_value(&self,diff --git a/rust/cloud-storage/soup/src/inbound/axum_router.rs b/rust/cloud-storage/soup/src/inbound/axum_router.rsindex 20e24b77fc..2c606c3f88 100644--- a/rust/cloud-storage/soup/src/inbound/axum_router.rs+++ b/rust/cloud-storage/soup/src/inbound/axum_router.rs@@ -390,13 +390,28 @@ where{/// Creates router state from the soup service, email service, and entity access service.pub fn new(service: T, email: U, entity_access_service: Arc<EAS>) -> Self {+ Self::from_arc(Arc::new(service), email, entity_access_service)+ }++ /// Creates router state from a shared soup service, email service, and entity access service.+ pub fn from_arc(service: Arc<T>, email: U, entity_access_service: Arc<EAS>) -> Self {SoupRouterState {- service: Arc::new(service),+ service,email: EmailRouterState::new(email),entity_access_service,}}+ /// Returns an `Arc` to the inner soup service.+ pub fn service(&self) -> Arc<T> {+ Arc::clone(&self.service)+ }++ /// Returns an `Arc` to the inner email service.+ pub fn email_service(&self) -> Arc<U> {+ self.email.service()+ }+async fn handle<R>(&self,macro_user_id: MacroUserIdStr<'static>,diff --git a/rust/cloud-storage/workspace-hack/Cargo.toml b/rust/cloud-storage/workspace-hack/Cargo.tomlindex 604aa597b7..44a6578a69 100644--- a/rust/cloud-storage/workspace-hack/Cargo.toml+++ b/rust/cloud-storage/workspace-hack/Cargo.toml@@ -117,7 +117,7 @@ time = { version = "0.3", features = ["formatting", "macros", "parsing"] }tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "parking_lot", "process", "rt-multi-thread", "signal", "test-util"] }tokio-rustls = { version = "0.26", default-features = false, features = ["tls12"] }tokio-stream = { version = "0.1", features = ["fs"] }-tokio-util = { version = "0.7", features = ["codec", "io"] }+tokio-util = { version = "0.7", features = ["codec", "compat", "io"] }tower = { version = "0.5", default-features = false, features = ["balance", "buffer", "limit", "load-shed", "log"] }tower-http = { version = "0.6", features = ["compression-gzip", "cors", "fs", "limit", "request-id", "timeout", "trace", "util"] }tracing = { version = "0.1", features = ["log"] }@@ -238,7 +238,7 @@ time = { version = "0.3", features = ["formatting", "macros", "parsing"] }tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "parking_lot", "process", "rt-multi-thread", "signal", "test-util"] }tokio-rustls = { version = "0.26", default-features = false, features = ["tls12"] }tokio-stream = { version = "0.1", features = ["fs"] }-tokio-util = { version = "0.7", features = ["codec", "io"] }+tokio-util = { version = "0.7", features = ["codec", "compat", "io"] }tower = { version = "0.5", default-features = false, features = ["balance", "buffer", "limit", "load-shed", "log"] }tower-http = { version = "0.6", features = ["compression-gzip", "cors", "fs", "limit", "request-id", "timeout", "trace", "util"] }tracing = { version = "0.1", features = ["log"] }@@ -258,10 +258,10 @@ getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-fhyper-rustls-754bda37e0fb3874 = { package = "hyper-rustls", version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "native-tokio", "ring", "tls12", "webpki-tokio"] }hyper-util = { version = "0.1", default-features = false, features = ["client-proxy-system"] }ipnet = { version = "2", features = ["serde"] }-linux-raw-sys = { version = "0.12", default-features = false, features = ["auxvec", "elf", "errno", "general", "ioctl", "no_std", "system"] }+linux-raw-sys = { version = "0.12", default-features = false, features = ["auxvec", "elf", "errno", "general", "if_ether", "ioctl", "net", "netlink", "no_std", "prctl", "system", "xdp"] }once_cell = { version = "1", default-features = false, features = ["critical-section"] }rand-93f6ce9d446188ac = { package = "rand", version = "0.10" }-rustix = { version = "1", features = ["fs", "system"] }+rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }thiserror = { version = "2" }tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "ring"] }tokio-util = { version = "0.7", default-features = false, features = ["io-util"] }@@ -276,10 +276,10 @@ getrandom-9fbad63c4bcf4a8f = { package = "getrandom", version = "0.4", default-fhyper-rustls-754bda37e0fb3874 = { package = "hyper-rustls", version = "0.27", default-features = false, features = ["aws-lc-rs", "http1", "http2", "native-tokio", "ring", "tls12", "webpki-tokio"] }hyper-util = { version = "0.1", default-features = false, features = ["client-proxy-system"] }ipnet = { version = "2", features = ["serde"] }-linux-raw-sys = { version = "0.12", default-features = false, features = ["auxvec", "elf", "errno", "general", "ioctl", "no_std", "system"] }+linux-raw-sys = { version = "0.12", default-features = false, features = ["auxvec", "elf", "errno", "general", "if_ether", "ioctl", "net", "netlink", "no_std", "prctl", "system", "xdp"] }once_cell = { version = "1", default-features = false, features = ["critical-section"] }rand-93f6ce9d446188ac = { package = "rand", version = "0.10" }-rustix = { version = "1", features = ["fs", "system"] }+rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }thiserror = { version = "2" }tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "ring"] }tokio-util = { version = "0.7", default-features = false, features = ["io-util"] }@@ -297,7 +297,7 @@ hyper-util = { version = "0.1", default-features = false, features = ["client-pripnet = { version = "2", features = ["serde"] }once_cell = { version = "1", default-features = false, features = ["critical-section"] }rand-93f6ce9d446188ac = { package = "rand", version = "0.10" }-rustix = { version = "1", features = ["fs", "system"] }+rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }security-framework-sys = { version = "2" }thiserror = { version = "2" }tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "ring"] }@@ -316,7 +316,7 @@ hyper-util = { version = "0.1", default-features = false, features = ["client-pripnet = { version = "2", features = ["serde"] }once_cell = { version = "1", default-features = false, features = ["critical-section"] }rand-93f6ce9d446188ac = { package = "rand", version = "0.10" }-rustix = { version = "1", features = ["fs", "system"] }+rustix = { version = "1", features = ["event", "fs", "net", "pipe", "process", "system", "time"] }security-framework-sys = { version = "2" }thiserror = { version = "2" }tokio-rustls = { version = "0.26", default-features = false, features = ["aws-lc-rs", "ring"] }