Skip to content

armgit / macro

Public Imported from GitHub
0

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

Seanaye/feat/split module (#4680)

Sean Ayefa65d2a5049c
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 8221395c69..1575f721b0 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -904,6 +904,89 @@
"user_quota",
"workspace-hack"
],
+ "complete_graph": [
+ "agent",
+ "ai_toolset",
+ "ai_usage",
+ "attachment",
+ "authentication_service_client",
+ "bot_id",
+ "call",
+ "channel_sender",
+ "channels",
+ "complete_graph",
+ "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",
+ "entity_access_management",
+ "filter_ast",
+ "foreign_entity",
+ "frecency",
+ "graphql_common",
+ "graphql_notification",
+ "graphql_properties",
+ "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_event_broker",
+ "macro_event_topics",
+ "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",
+ "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"
+ ],
"connection": [
"agent",
"ai_toolset",
@@ -1435,6 +1518,7 @@
"channels",
"chat",
"comms_db_client",
+ "complete_graph",
"connection",
"connection_gateway_client",
"connection_gateway_models",
@@ -1460,6 +1544,9 @@
"frecency",
"fusionauth",
"github",
+ "graphql_common",
+ "graphql_notification",
+ "graphql_properties",
"graphql_soup",
"invite_email",
"ip_extractor",
@@ -2511,6 +2598,113 @@
"models_pagination",
"workspace-hack"
],
+ "graphql_common": [
+ "cowlike",
+ "filter_ast",
+ "graphql_common",
+ "macro_user_id",
+ "model-entity",
+ "workspace-hack"
+ ],
+ "graphql_notification": [
+ "ai_toolset",
+ "cowlike",
+ "decode_jwt",
+ "filter_ast",
+ "graphql_common",
+ "graphql_notification",
+ "last_online_tracker",
+ "macro_auth",
+ "macro_env",
+ "macro_env_var",
+ "macro_service_urls",
+ "macro_user_id",
+ "macro_uuid",
+ "model-entity",
+ "model-error-response",
+ "model_user",
+ "models_pagination",
+ "notification",
+ "rate_limit",
+ "remote_env_var",
+ "workspace-hack"
+ ],
+ "graphql_properties": [
+ "agent",
+ "ai_toolset",
+ "ai_usage",
+ "attachment",
+ "authentication_service_client",
+ "bot_id",
+ "call",
+ "channel_sender",
+ "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",
+ "entity_access_management",
+ "filter_ast",
+ "frecency",
+ "graphql_common",
+ "graphql_properties",
+ "invite_email",
+ "ip_extractor",
+ "item_filters",
+ "last_online_tracker",
+ "macro_auth",
+ "macro_aws_config",
+ "macro_db_client",
+ "macro_env",
+ "macro_env_var",
+ "macro_event_broker",
+ "macro_event_topics",
+ "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_opensearch",
+ "models_pagination",
+ "models_permissions",
+ "models_properties",
+ "models_soup",
+ "models_team",
+ "non_empty",
+ "notification",
+ "prompt",
+ "properties",
+ "rate_limit",
+ "remote_env_var",
+ "s3_key",
+ "share_permission_db_utils",
+ "sqs_client",
+ "sqs_worker",
+ "system_properties",
+ "unfurl",
+ "user_quota",
+ "workspace-hack"
+ ],
"graphql_soup": [
"agent",
"ai_toolset",
@@ -2538,6 +2732,9 @@
"filter_ast",
"foreign_entity",
"frecency",
+ "graphql_common",
+ "graphql_notification",
+ "graphql_properties",
"graphql_soup",
"invite_email",
"ip_extractor",
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 85edbd113c..160afff90c 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2811,6 +2811,29 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "complete_graph"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "async-graphql",
+ "axum",
+ "axum-extra",
+ "email",
+ "entity_access",
+ "graphql_common",
+ "graphql_notification",
+ "graphql_properties",
+ "graphql_soup",
+ "macro_user_id",
+ "model_user",
+ "models_pagination",
+ "soup",
+ "tokio",
+ "uuid",
+ "workspace-hack",
+]
+
[[package]]
name = "compression-codecs"
version = "0.4.38"
@@ -4137,6 +4160,7 @@ dependencies = [
"clap",
"cloudfront_sign",
"comms_db_client",
+ "complete_graph",
"connection",
"connection_gateway_client",
"contacts",
@@ -4156,7 +4180,6 @@ dependencies = [
"frecency",
"futures",
"github",
- "graphql_soup",
"hex",
"http-body-util",
"jsonwebtoken 10.3.0",
@@ -5801,20 +5824,68 @@ dependencies = [
]
[[package]]
-name = "graphql_soup"
+name = "graphql_common"
+version = "0.1.0"
+dependencies = [
+ "async-graphql",
+ "axum",
+ "filter_ast",
+ "macro_user_id",
+ "model-entity",
+ "tokio",
+ "uuid",
+ "workspace-hack",
+]
+
+[[package]]
+name = "graphql_notification"
+version = "0.1.0"
+dependencies = [
+ "async-graphql",
+ "async-trait",
+ "graphql_common",
+ "macro_user_id",
+ "notification",
+ "rootcause",
+ "serde_json",
+ "tokio",
+ "workspace-hack",
+]
+
+[[package]]
+name = "graphql_properties"
version = "0.1.0"
dependencies = [
- "anyhow",
"async-graphql",
"async-trait",
+ "filter_ast",
+ "graphql_common",
+ "item_filters",
+ "macro_user_id",
+ "models_properties",
+ "models_soup",
+ "properties",
+ "rootcause",
+ "tokio",
+ "tracing",
+ "workspace-hack",
+]
+
+[[package]]
+name = "graphql_soup"
+version = "0.1.0"
+dependencies = [
+ "async-graphql",
"axum",
"axum-extra",
"chrono",
"document_sub_type",
- "either",
"email",
"entity_access",
"filter_ast",
+ "graphql_common",
+ "graphql_notification",
+ "graphql_properties",
"item_filters",
"macro_user_id",
"model-entity",
@@ -5823,14 +5894,9 @@ dependencies = [
"models_pagination",
"models_properties",
"models_soup",
- "notification",
- "properties",
- "rootcause",
"serde",
"serde_json",
"soup",
- "tokio",
- "tracing",
"uuid",
"workspace-hack",
]
@@ -15367,6 +15433,7 @@ version = "0.1.0"
dependencies = [
"ahash",
"aho-corasick",
+ "async-graphql",
"aws-config",
"aws-credential-types",
"aws-runtime",
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index ad8e8d7a8b..beb7e81f0f 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -15,6 +15,7 @@ members = [
"client/cache-idb",
"client/cache-sqlite",
"client/cache-wasm",
+ "complete_graph",
"connection_gateway",
"contacts_service",
"convert_service",
@@ -37,6 +38,9 @@ members = [
"embedding",
"favorites",
"foreign_entity",
+ "graphql_common",
+ "graphql_notification",
+ "graphql_properties",
"graphql_soup",
"image_optimizer",
"image_proxy_service",
diff --git a/rust/cloud-storage/complete_graph/AGENTS.md b/rust/cloud-storage/complete_graph/AGENTS.md
new file mode 100644
index 0000000000..d77beb918f
--- /dev/null
+++ b/rust/cloud-storage/complete_graph/AGENTS.md
@@ -0,0 +1,69 @@
+# complete_graph — schema conventions
+
+This crate composes the domain GraphQL adapter crates (`graphql_soup`,
+`graphql_properties`, `graphql_notification`, with shared plumbing in
+`graphql_common`) into the complete GraphQL schema consumed by the client's
+**normalized cache** (`rust/cloud-storage/client`, design doc:
+`js/app/docs/graphql-normalized-cache-plan.md`). Two field-naming
+conventions in this schema are load-bearing for cache correctness. The
+cache's build validates *shapes* but cannot validate *semantics* — that's
+what schema review is for.
+
+## 1. `id` is a reserved, semantic field name (presence-of-id convention)
+
+Clients key cache records by `__typename:id`. Consequences:
+
+- **An output object type with an `id: ID!` field is a normalized entity.**
+ Two responses containing the same `__typename:id` pair are *merged into
+ one record* — so `id` must identify the same logical value everywhere it
+ can appear, across all queries, arguments, and parent objects.
+- **Only name a field `id` when it is the object's global identity.** If a
+ type carries a reference to something else's id, name it accordingly:
+ - `GraphqlSoupProperty` exposes `propertyDefinitionId`, **not** `id` — a
+ property instance's `value` is per-entity, while the definition id is
+ shared. Naming it `id` would merge property values across entities.
+ - `GraphqlSoupChannelMessage.id` (renamed from `messageId`) — it *is* the
+ message's identity, so it uses the reserved name.
+- **Types without an `id` field are embedded** inline in their parent
+ record (`SoupPage`, participants, property values, `DocumentSubType`).
+ This is correct for value objects and query-scoped wrappers. Do **not**
+ add constant or synthetic ids to such types — a constant id (e.g.
+ `"soup_page"`) would merge every instance into a single record globally.
+- `id` fields must be exactly `ID!` (non-null, non-list); the cache build
+ (`rust/cloud-storage/client/cache-core/build.rs`) fails otherwise, and fails if
+ the query root exposes an `id`.
+
+Review checklist when adding/changing a type:
+1. Does it have a stable global identity? → expose it as `id: ID!`.
+2. Is its content dependent on where it appears (parent entity, arguments)?
+ → no `id` field; expose reference ids under descriptive names.
+3. Renaming/removing an `id` field changes client caching semantics — it
+ rotates cache keys and turns entities into embedded values (or vice
+ versa). Deliberate, but call it out in review.
+
+## 2. `QueryRoot → user` (viewer pattern) is the identity witness
+
+All user-scoped data hangs off `user: GraphqlUser!`, and `GraphqlUser.id`
+must be the **authenticated** user's id from the request context. The
+client extracts it from every response and passes it to the cache as a
+session tag: a response for a different user than the one bound to the
+cache triggers a full wipe-and-rebind (cross-user leak protection on
+account switches).
+
+- Never resolve `GraphqlUser.id` from anything other than the
+ authenticated request context.
+- New user-scoped root data should be added under `GraphqlUser`, not as
+ new root fields.
+
+## Regenerating the SDL
+
+After schema changes:
+
+```sh
+cargo run -p complete_graph --bin graphql_schema -- schema.graphql # from rust/cloud-storage
+```
+
+The exported `schema.graphql` feeds both the client codegen
+(`js/app && bun gen-graphql`) and the cache metadata codegen (hashing it —
+any change rotates all persisted client caches, which rebuild from the
+network automatically).
diff --git a/rust/cloud-storage/complete_graph/Cargo.toml b/rust/cloud-storage/complete_graph/Cargo.toml
new file mode 100644
index 0000000000..862f039976
--- /dev/null
+++ b/rust/cloud-storage/complete_graph/Cargo.toml
@@ -0,0 +1,32 @@
+[package]
+name = "complete_graph"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+anyhow = { workspace = true }
+async-graphql = { workspace = true, features = ["dataloader"] }
+axum = { workspace = true }
+axum-extra = { workspace = true }
+email = { path = "../email", default-features = false, features = [
+ "axum",
+ "inbound",
+ "ports",
+] }
+entity_access = { path = "../entity_access", default-features = false, features = [
+ "inbound",
+] }
+graphql_common = { path = "../graphql_common" }
+graphql_notification = { path = "../graphql_notification" }
+graphql_properties = { path = "../graphql_properties" }
+graphql_soup = { path = "../graphql_soup" }
+model_user = { path = "../model_user", features = ["axum"] }
+soup = { path = "../soup", default-features = false, features = ["ports"] }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+macro_user_id = { path = "../macro_user_id" }
+models_pagination = { path = "../models_pagination" }
+tokio = { workspace = true }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/graphql_soup/src/bin/graphql_soup_schema.rs b/rust/cloud-storage/complete_graph/src/bin/graphql_schema.rs
similarity index 85%
rename from rust/cloud-storage/graphql_soup/src/bin/graphql_soup_schema.rs
rename to rust/cloud-storage/complete_graph/src/bin/graphql_schema.rs
index 3b507535b2..7496110b29 100644
--- a/rust/cloud-storage/graphql_soup/src/bin/graphql_soup_schema.rs
+++ b/rust/cloud-storage/complete_graph/src/bin/graphql_schema.rs
@@ -6,9 +6,9 @@ fn main() -> Result<()> {
let output_path = std::env::args_os()
.nth(1)
.map(PathBuf::from)
- .context("usage: graphql_soup_schema <output-path>")?;
+ .context("usage: graphql_schema <output-path>")?;
- let schema = graphql_soup::build_schema().sdl();
+ let schema = complete_graph::build_schema().sdl();
if let Some(parent) = output_path
.parent()
diff --git a/rust/cloud-storage/complete_graph/src/lib.rs b/rust/cloud-storage/complete_graph/src/lib.rs
new file mode 100644
index 0000000000..13957b39b7
--- /dev/null
+++ b/rust/cloud-storage/complete_graph/src/lib.rs
@@ -0,0 +1,22 @@
+//! Composition of the domain GraphQL adapter crates (`graphql_soup`,
+//! `graphql_properties`, `graphql_notification`) into the complete schema
+//! served by `document_storage_service` and exported as SDL.
+#![deny(missing_docs)]
+
+mod schema;
+#[cfg(test)]
+mod sdl_test;
+
+pub use graphql_common::GraphqlSoupRequestParts;
+pub use graphql_notification::{
+ EntityNotificationsKey, EntityNotificationsLoader, SoupNotificationEdgeReader,
+ entity_notifications_loader,
+};
+pub use graphql_properties::{
+ EntityPropertiesKey, EntityPropertiesLoader, SoupPropertyEdgeReader, entity_properties_loader,
+};
+pub use graphql_soup::SharedSoupService;
+pub use schema::{
+ SchemaOnlySoupSchema, SchemaOnlyState, SharedSoupSchema, SoupQueryRoot, SoupSchema,
+ build_schema, build_schema_from_arc, build_schema_with_service,
+};
diff --git a/rust/cloud-storage/graphql_soup/src/schema.rs b/rust/cloud-storage/complete_graph/src/schema.rs
similarity index 54%
rename from rust/cloud-storage/graphql_soup/src/schema.rs
rename to rust/cloud-storage/complete_graph/src/schema.rs
index 3cdbb0318c..cc34610c70 100644
--- a/rust/cloud-storage/graphql_soup/src/schema.rs
+++ b/rust/cloud-storage/complete_graph/src/schema.rs
@@ -4,27 +4,17 @@ mod test;
use std::{marker::PhantomData, sync::Arc};
use async_graphql::{Context, EmptyMutation, EmptySubscription, Object, Schema};
-use axum::extract::{FromRef, FromRequestParts};
+use axum::extract::FromRef;
use axum_extra::extract::Cached;
use email::{
domain::ports::{EmailService, NoOpEmailService},
- inbound::axum::{axum_impls::MultiEmailLinkExtractor, previews_router::EmailRouterState},
-};
-use entity_access::{
- domain::{
- models::{EntityAccessReceipt, MemberTeamRole},
- ports::{EntityAccessService, NoOpEntityAccessService},
- },
- inbound::axum_extractors::OptionalMacroUserTeamExtractor,
+ inbound::axum::previews_router::EmailRouterState,
};
+use entity_access::domain::ports::{EntityAccessService, NoOpEntityAccessService};
+use graphql_common::extract_part;
+use graphql_soup::{SharedSoupService, SoupInput, SoupPage, resolve_soup};
use model_user::axum_extractor::MacroUserExtractor;
-use models_pagination::TypeEraseCursor;
-use soup::domain::{
- models::SoupRequest,
- ports::{NoOpSoupService, SoupService},
-};
-
-use crate::{inputs::SoupInput, objects::SoupPage, request_context::GraphqlSoupRequestParts};
+use soup::domain::ports::{NoOpSoupService, SoupService};
/// GraphQL Soup schema type.
///
@@ -58,56 +48,6 @@ impl FromRef<SchemaOnlyState> for Arc<NoOpEntityAccessService> {
}
}
-/// Object-safe-ish wrapper for sharing a concrete Soup service with GraphQL.
-pub struct SharedSoupService<S>(Arc<S>);
-
-impl<S> Clone for SharedSoupService<S> {
- fn clone(&self) -> Self {
- Self(Arc::clone(&self.0))
- }
-}
-
-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
- }
-
- async fn caller_tag_sets<'a>(
- &self,
- user_id: macro_user_id::user_id::MacroUserIdStr<'a>,
- ) -> Result<
- Vec<models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions>,
- soup::domain::models::SoupErr,
- >{
- self.0.caller_tag_sets(user_id).await
- }
-}
-
/// Zero-sized marker tying the query objects to the email/entity-access/state
/// generics without requiring values of those types.
type ServicesMarker<E, EAS, St> = PhantomData<fn() -> (E, EAS, St)>;
@@ -172,22 +112,6 @@ where
build_schema_with_service(SharedSoupService::new(service))
}
-/// Run an axum extractor against the request parts stored in the GraphQL
-/// context, using the embedding router state `St` also stored there.
-async fn extract_part<T, St>(ctx: &Context<'_>) -> async_graphql::Result<T>
-where
- T: FromRequestParts<St>,
- T::Rejection: std::fmt::Display,
- St: Clone + Send + Sync + 'static,
-{
- let parts = ctx.data::<GraphqlSoupRequestParts>()?;
- let state = ctx.data::<St>()?;
- parts
- .extract_with_state::<T, St>(state)
- .await
- .map_err(|err| async_graphql::Error::new(err.to_string()))
-}
-
#[Object]
impl<S, E, EAS, St> SoupQueryRoot<S, E, EAS, St>
where
@@ -226,32 +150,6 @@ where
/// 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 Cached(MacroUserExtractor { macro_user_id, .. }) =
- extract_part::<Cached<MacroUserExtractor>, St>(ctx).await?;
- let Cached(MultiEmailLinkExtractor(links, _)) =
- extract_part::<Cached<MultiEmailLinkExtractor<E>>, St>(ctx).await?;
- let link_ids = links.into_iter().map(|link| link.id).collect();
- let request = input.into_request(macro_user_id, link_ids)?;
-
- // Team membership is only resolved when the query actually asks for
- // CRM-scoped data; everything else skips the lookup entirely. The
- // authorization itself (membership + admin role for hidden
- // companies) is enforced by the soup domain and CRM service from
- // the receipt.
- let effective_filter = request.cursor.filter();
- let team_receipt =
- if effective_filter.requests_crm_scope() || effective_filter.requests_crm_admin() {
- let Cached(team) = extract_part::<
- Cached<OptionalMacroUserTeamExtractor<MemberTeamRole, EAS>>,
- St,
- >(ctx)
- .await?;
- team.entity_access_receipt
- } else {
- None
- };
-
- let page = self.service.get_user_soup(request, team_receipt).await?;
- Ok(SoupPage::from(page.type_erase()))
+ resolve_soup::<S, E, EAS, St>(&self.service, ctx, input).await
}
}
diff --git a/rust/cloud-storage/graphql_soup/src/schema/test.rs b/rust/cloud-storage/complete_graph/src/schema/test.rs
similarity index 98%
rename from rust/cloud-storage/graphql_soup/src/schema/test.rs
rename to rust/cloud-storage/complete_graph/src/schema/test.rs
index ebe256df2f..7a78ca4eb4 100644
--- a/rust/cloud-storage/graphql_soup/src/schema/test.rs
+++ b/rust/cloud-storage/complete_graph/src/schema/test.rs
@@ -6,9 +6,10 @@ use email::domain::models::{
UpsertEmailFilterInput,
};
use entity_access::domain::models::{
- AccessError, AccessLevel, CallChannelInfo, EditAccessLevel, EntityPermission, EntityType,
- RequiredPermission, UserTeamInfo, ViewAccessLevel,
+ AccessError, AccessLevel, CallChannelInfo, EditAccessLevel, EntityAccessReceipt,
+ EntityPermission, EntityType, RequiredPermission, UserTeamInfo, ViewAccessLevel,
};
+use graphql_common::GraphqlSoupRequestParts;
use macro_user_id::{
lowercased::Lowercase,
user_id::{MacroUserId, MacroUserIdStr},
diff --git a/rust/cloud-storage/graphql_soup/src/objects/tests.rs b/rust/cloud-storage/complete_graph/src/sdl_test.rs
similarity index 71%
rename from rust/cloud-storage/graphql_soup/src/objects/tests.rs
rename to rust/cloud-storage/complete_graph/src/sdl_test.rs
index 31891f4746..bd242cbc9e 100644
--- a/rust/cloud-storage/graphql_soup/src/objects/tests.rs
+++ b/rust/cloud-storage/complete_graph/src/sdl_test.rs
@@ -33,6 +33,20 @@ fn soup_response_schema_exposes_frontend_fields() {
}
}
+/// The exported SDL is a frontend contract: `schema.graphql` feeds the client
+/// codegen and the normalized-cache metadata. Splitting the schema across
+/// crates must never change it silently — regenerate with
+/// `cargo run -p complete_graph --bin graphql_schema -- schema.graphql`.
+#[test]
+fn sdl_matches_committed_schema_graphql() {
+ let sdl = crate::build_schema().sdl();
+ assert_eq!(
+ format!("{sdl}\n"),
+ include_str!("../../schema.graphql"),
+ "generated SDL diverges from the committed schema.graphql"
+ );
+}
+
fn assert_sdl_line(sdl: &str, expected: &str) {
assert!(
sdl.lines().any(|line| line.trim() == expected),
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index 91a9272f96..3afb1df745 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -22,7 +22,7 @@ path = "src/doppler_config.rs"
connection_gateway = []
default = ["connection_gateway", "delete_document_worker", "graphql", "location_check"]
delete_document_worker = []
-graphql = ["dep:async-graphql", "dep:async-graphql-axum", "dep:graphql_soup"]
+graphql = ["dep:async-graphql", "dep:async-graphql-axum", "dep:complete_graph"]
local = ["local_auth"]
local_auth = ["macro_middleware/local_auth"]
location_check = []
@@ -74,7 +74,7 @@ favorites = { path = "../favorites", features = ["inbound", "postgres"] }
foreign_entity = { path = "../foreign_entity", features = ["inbound"] }
frecency = { path = "../frecency", features = ["postgres"] }
futures = { workspace = true }
-graphql_soup = { path = "../graphql_soup", optional = true }
+complete_graph = { path = "../complete_graph", 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.rs
index f12df2c624..35aa53965a 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -134,7 +134,7 @@ type DssSoupState = SoupRouterState<DssSoupService, DssEmailService, EntityAcces
/// parameter lets GraphQL resolvers run the same axum extractors as the REST
/// routes, lazily, against the stored request parts.
#[cfg(feature = "graphql")]
-pub(crate) type DssGraphqlSoupSchema = graphql_soup::SharedSoupSchema<
+pub(crate) type DssGraphqlSoupSchema = complete_graph::SharedSoupSchema<
DssSoupService,
DssEmailService,
EntityAccessService,
@@ -353,7 +353,7 @@ pub(crate) struct ApiContext {
#[cfg(feature = "graphql")]
pub graphql_soup_schema: DssGraphqlSoupSchema,
#[cfg(feature = "graphql")]
- pub graphql_notification_reader: Arc<dyn graphql_soup::SoupNotificationEdgeReader>,
+ pub graphql_notification_reader: Arc<dyn complete_graph::SoupNotificationEdgeReader>,
pub favorites_state: DssFavoritesState,
pub favorites_service: Arc<FavoritesServiceType>,
pub foreign_entity_state: DssForeignEntityState,
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.rs
index 845be79ada..cde91db6cb 100644
--- a/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/graphql_soup.rs
@@ -8,7 +8,7 @@ use axum::{
routing::get,
};
use axum_extra::extract::Cached;
-use graphql_soup::GraphqlSoupRequestParts;
+use complete_graph::GraphqlSoupRequestParts;
use model_user::axum_extractor::OptionalMacroUserExtractor;
pub(crate) fn router() -> Router<ApiContext> {
@@ -54,16 +54,16 @@ async fn handler(State(state): State<ApiContext>, req: Request) -> Response {
.into_response();
};
- let property_reader: std::sync::Arc<dyn graphql_soup::SoupPropertyEdgeReader> =
+ let property_reader: std::sync::Arc<dyn complete_graph::SoupPropertyEdgeReader> =
state.properties_service.clone();
let request = request
.data(GraphqlSoupRequestParts::new(parts))
.data(state.clone())
- .data(graphql_soup::entity_properties_loader(
+ .data(complete_graph::entity_properties_loader(
macro_user_id.clone(),
property_reader,
))
- .data(graphql_soup::entity_notifications_loader(
+ .data(complete_graph::entity_notifications_loader(
macro_user_id,
state.graphql_notification_reader.clone(),
));
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 9f8b324771..4fd027c02e 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -285,7 +285,7 @@ async fn main() -> anyhow::Result<()> {
queue: ingress_queue.clone(),
});
#[cfg(feature = "graphql")]
- let graphql_notification_reader: Arc<dyn graphql_soup::SoupNotificationEdgeReader> =
+ let graphql_notification_reader: Arc<dyn complete_graph::SoupNotificationEdgeReader> =
Arc::new(NotificationReaderService {
repository: notification::outbound::repository::DbNotificationRepository::new(
db.clone(),
@@ -735,7 +735,7 @@ async fn main() -> anyhow::Result<()> {
),
favorites_service,
#[cfg(feature = "graphql")]
- graphql_soup_schema: graphql_soup::build_schema_from_arc(soup_service),
+ graphql_soup_schema: complete_graph::build_schema_from_arc(soup_service),
#[cfg(feature = "graphql")]
graphql_notification_reader,
github_sync_service: Arc::new(github_sync_service_impl),
diff --git a/rust/cloud-storage/graphql_common/Cargo.toml b/rust/cloud-storage/graphql_common/Cargo.toml
new file mode 100644
index 0000000000..dfc58f3692
--- /dev/null
+++ b/rust/cloud-storage/graphql_common/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "graphql_common"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+async-graphql = { workspace = true }
+axum = { workspace = true }
+filter_ast = { path = "../filter_ast" }
+macro_user_id = { path = "../macro_user_id" }
+model-entity = { path = "../model-entity" }
+tokio = { workspace = true }
+uuid = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/rust/cloud-storage/graphql_common/src/entity_type.rs b/rust/cloud-storage/graphql_common/src/entity_type.rs
new file mode 100644
index 0000000000..f3226a2be6
--- /dev/null
+++ b/rust/cloud-storage/graphql_common/src/entity_type.rs
@@ -0,0 +1,53 @@
+use async_graphql::Enum;
+use model_entity::EntityType;
+
+/// GraphQL representation of Soup entity types.
+#[derive(Enum, Copy, Clone, Eq, PartialEq)]
+pub enum GraphqlSoupEntityType {
+ /// Document entity.
+ Document,
+ /// Chat entity.
+ Chat,
+ /// Project entity.
+ Project,
+ /// Email thread entity.
+ EmailThread,
+ /// Channel entity.
+ Channel,
+ /// Channel thread entity.
+ ChannelThread,
+ /// Call entity.
+ Call,
+ /// CRM company entity.
+ CrmCompany,
+ /// Foreign entity.
+ ForeignEntity,
+ /// User entity.
+ User,
+ /// Team entity.
+ Team,
+ /// Static file entity.
+ StaticFile,
+ /// CRM contact entity.
+ CrmContact,
+}
+
+impl From<EntityType> for GraphqlSoupEntityType {
+ fn from(entity_type: EntityType) -> Self {
+ match entity_type {
+ EntityType::Document => Self::Document,
+ EntityType::Chat => Self::Chat,
+ EntityType::Project => Self::Project,
+ EntityType::EmailThread => Self::EmailThread,
+ EntityType::Channel => Self::Channel,
+ EntityType::ChannelMessage => Self::ChannelThread,
+ EntityType::Call => Self::Call,
+ EntityType::CrmCompany => Self::CrmCompany,
+ EntityType::ForeignEntity => Self::ForeignEntity,
+ EntityType::User => Self::User,
+ EntityType::Team => Self::Team,
+ EntityType::StaticFile => Self::StaticFile,
+ EntityType::CrmContact => Self::CrmContact,
+ }
+ }
+}
diff --git a/rust/cloud-storage/graphql_common/src/extract.rs b/rust/cloud-storage/graphql_common/src/extract.rs
new file mode 100644
index 0000000000..8de307a1aa
--- /dev/null
+++ b/rust/cloud-storage/graphql_common/src/extract.rs
@@ -0,0 +1,20 @@
+use async_graphql::Context;
+use axum::extract::FromRequestParts;
+
+use crate::request_context::GraphqlSoupRequestParts;
+
+/// Run an axum extractor against the request parts stored in the GraphQL
+/// context, using the embedding router state `St` also stored there.
+pub async fn extract_part<T, St>(ctx: &Context<'_>) -> async_graphql::Result<T>
+where
+ T: FromRequestParts<St>,
+ T::Rejection: std::fmt::Display,
+ St: Clone + Send + Sync + 'static,
+{
+ let parts = ctx.data::<GraphqlSoupRequestParts>()?;
+ let state = ctx.data::<St>()?;
+ parts
+ .extract_with_state::<T, St>(state)
+ .await
+ .map_err(|err| async_graphql::Error::new(err.to_string()))
+}
diff --git a/rust/cloud-storage/graphql_common/src/filter_input.rs b/rust/cloud-storage/graphql_common/src/filter_input.rs
new file mode 100644
index 0000000000..a9372ff06b
--- /dev/null
+++ b/rust/cloud-storage/graphql_common/src/filter_input.rs
@@ -0,0 +1,90 @@
+use std::sync::Arc;
+
+use async_graphql::ID;
+use filter_ast::Expr;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
+use uuid::Uuid;
+
+/// Conversion from a GraphQL filter input tree into a domain filter
+/// expression over literal type `T`.
+pub trait IntoFilterExpr<T>: Sized {
+ /// Convert this input into a `filter_ast` expression tree.
+ fn into_expr(self) -> async_graphql::Result<Expr<T>>;
+}
+
+/// Convert an optional GraphQL filter input into an optional shared
+/// expression tree.
+pub fn optional_tree<I, T>(input: Option<I>) -> async_graphql::Result<Option<Arc<Expr<T>>>>
+where
+ I: IntoFilterExpr<T>,
+{
+ input.map(|expr| expr.into_expr().map(Arc::new)).transpose()
+}
+
+/// Parse a string field into a [`Uuid`], reporting the field name on error.
+pub fn parse_uuid(value: String, field: &str) -> async_graphql::Result<Uuid> {
+ Uuid::parse_str(&value)
+ .map_err(|err| async_graphql::Error::new(format!("invalid {field} UUID `{value}`: {err}")))
+}
+
+/// Parse a GraphQL [`ID`] field into a [`Uuid`], reporting the field name on
+/// error.
+pub fn parse_id(id: ID, field: &str) -> async_graphql::Result<Uuid> {
+ parse_uuid(id.to_string(), field)
+}
+
+/// Parse a string field into an owned [`MacroUserIdStr`], reporting the field
+/// name on error.
+pub fn parse_macro_user_id(
+ value: String,
+ field: &str,
+) -> async_graphql::Result<MacroUserIdStr<'static>> {
+ MacroUserIdStr::parse_from_str(&value)
+ .map(CowLike::into_owned)
+ .map_err(|err| async_graphql::Error::new(format!("invalid {field} `{value}`: {err}")))
+}
+
+/// Generate a recursive GraphQL filter-expression input (`And`/`Or`/`Not`/
+/// `Literal`) plus its binary node struct, and an [`IntoFilterExpr`] impl
+/// converting it into a `filter_ast` expression over the target literal.
+///
+/// The generated types deliberately carry no doc comments: doc comments on
+/// GraphQL input types are emitted as SDL descriptions, and the exported
+/// `schema.graphql` must not change.
+#[macro_export]
+macro_rules! filter_expr_input {
+ ($name:ident, $binary_name:ident, $literal:ty, $target:ty, $type_name:literal) => {
+ #[allow(missing_docs)]
+ #[derive(async_graphql::InputObject)]
+ pub struct $binary_name {
+ pub left: Box<$name>,
+ pub right: Box<$name>,
+ }
+
+ #[allow(missing_docs)]
+ #[derive(async_graphql::OneofObject)]
+ pub enum $name {
+ And($binary_name),
+ Or($binary_name),
+ Not(Box<$name>),
+ Literal($literal),
+ }
+
+ impl $crate::IntoFilterExpr<$target> for $name {
+ fn into_expr(self) -> async_graphql::Result<$crate::filter_ast::Expr<$target>> {
+ match self {
+ Self::And(exprs) => Ok($crate::filter_ast::Expr::and(
+ exprs.left.into_expr()?,
+ exprs.right.into_expr()?,
+ )),
+ Self::Or(exprs) => Ok($crate::filter_ast::Expr::or(
+ exprs.left.into_expr()?,
+ exprs.right.into_expr()?,
+ )),
+ Self::Not(expr) => expr.into_expr().map($crate::filter_ast::Expr::is_not),
+ Self::Literal(literal) => literal.into_expr(),
+ }
+ }
+ }
+ };
+}
diff --git a/rust/cloud-storage/graphql_common/src/lib.rs b/rust/cloud-storage/graphql_common/src/lib.rs
new file mode 100644
index 0000000000..8ae5ace2a9
--- /dev/null
+++ b/rust/cloud-storage/graphql_common/src/lib.rs
@@ -0,0 +1,17 @@
+//! Shared plumbing for the domain GraphQL adapter crates: request-scoped
+//! extractor context, filter-input conversion helpers, and cross-domain
+//! schema types.
+#![deny(missing_docs)]
+
+// Re-exported for use by the `filter_expr_input!` macro expansion.
+pub use filter_ast;
+
+mod entity_type;
+mod extract;
+mod filter_input;
+mod request_context;
+
+pub use entity_type::GraphqlSoupEntityType;
+pub use extract::extract_part;
+pub use filter_input::{IntoFilterExpr, optional_tree, parse_id, parse_macro_user_id, parse_uuid};
+pub use request_context::GraphqlSoupRequestParts;
diff --git a/rust/cloud-storage/graphql_soup/src/request_context.rs b/rust/cloud-storage/graphql_common/src/request_context.rs
similarity index 100%
rename from rust/cloud-storage/graphql_soup/src/request_context.rs
rename to rust/cloud-storage/graphql_common/src/request_context.rs
diff --git a/rust/cloud-storage/graphql_notification/Cargo.toml b/rust/cloud-storage/graphql_notification/Cargo.toml
new file mode 100644
index 0000000000..de0efb967e
--- /dev/null
+++ b/rust/cloud-storage/graphql_notification/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "graphql_notification"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+async-graphql = { workspace = true, features = ["dataloader"] }
+async-trait = { workspace = true }
+graphql_common = { path = "../graphql_common" }
+macro_user_id = { path = "../macro_user_id" }
+notification = { path = "../notification" }
+rootcause = { workspace = true }
+serde_json = { workspace = true }
+tokio = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/rust/cloud-storage/graphql_notification/src/lib.rs b/rust/cloud-storage/graphql_notification/src/lib.rs
new file mode 100644
index 0000000000..8de5cf1693
--- /dev/null
+++ b/rust/cloud-storage/graphql_notification/src/lib.rs
@@ -0,0 +1,12 @@
+//! GraphQL inbound adapter for the notification domain: the notification
+//! object type and the DataLoader-backed entity notification edge.
+#![deny(missing_docs)]
+
+mod loaders;
+mod objects;
+
+pub use loaders::{
+ EntityNotificationsKey, EntityNotificationsLoader, SoupNotificationEdgeReader,
+ entity_notifications_loader,
+};
+pub use objects::{GraphqlSoupNotification, load_entity_notifications};
diff --git a/rust/cloud-storage/graphql_notification/src/loaders.rs b/rust/cloud-storage/graphql_notification/src/loaders.rs
new file mode 100644
index 0000000000..245ad49e34
--- /dev/null
+++ b/rust/cloud-storage/graphql_notification/src/loaders.rs
@@ -0,0 +1,144 @@
+use std::{collections::HashMap, sync::Arc};
+
+use async_graphql::dataloader::{DataLoader, Loader};
+use macro_user_id::user_id::MacroUserIdStr;
+use notification::domain::models::{
+ UserNotificationRow,
+ request::{NotificationEntityRef, NotificationItemType},
+};
+
+/// 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,
+}
+
+impl EntityNotificationsKey {
+ fn notification_item_type(&self) -> Result<NotificationItemType, rootcause::Report> {
+ match self.entity_type.as_str() {
+ "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}"
+ )),
+ }
+ }
+}
+
+/// 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 requested_refs = keys
+ .iter()
+ .map(|key| {
+ Ok((
+ key.clone(),
+ NotificationEntityRef {
+ entity_type: key.notification_item_type()?,
+ id: key.entity_id.clone(),
+ },
+ ))
+ })
+ .collect::<Result<Vec<_>, rootcause::Report>>()?;
+
+ let entity_refs = requested_refs
+ .iter()
+ .map(|(_, entity_ref)| entity_ref.clone())
+ .collect();
+
+ let notifications_by_entity = self
+ .get_entity_notifications_batch(user_id, entity_refs)
+ .await
+ .map_err(|err| rootcause::report!(err))?;
+
+ for (original_key, entity_ref) in requested_refs {
+ if let Some(notifications) = notifications_by_entity.get(&entity_ref) {
+ result.insert(original_key, notifications.clone());
+ }
+ }
+
+ 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,
+ )
+}
diff --git a/rust/cloud-storage/graphql_notification/src/objects.rs b/rust/cloud-storage/graphql_notification/src/objects.rs
new file mode 100644
index 0000000000..2f2d44d61e
--- /dev/null
+++ b/rust/cloud-storage/graphql_notification/src/objects.rs
@@ -0,0 +1,78 @@
+use async_graphql::{Context, ID, Json, Object, dataloader::DataLoader};
+use graphql_common::GraphqlSoupEntityType;
+use notification::domain::models::UserNotificationRow;
+use serde_json::Value;
+
+use crate::loaders::{EntityNotificationsKey, EntityNotificationsLoader};
+
+/// 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) -> GraphqlSoupEntityType {
+ GraphqlSoupEntityType::from(self.0.entity.entity_type)
+ }
+
+ 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())
+ }
+}
+
+/// Load the notifications attached to the given entity via the
+/// [`EntityNotificationsLoader`] stored in the GraphQL context.
+pub 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())
+}
diff --git a/rust/cloud-storage/graphql_properties/Cargo.toml b/rust/cloud-storage/graphql_properties/Cargo.toml
new file mode 100644
index 0000000000..f20d3ffbc1
--- /dev/null
+++ b/rust/cloud-storage/graphql_properties/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "graphql_properties"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+async-graphql = { workspace = true, features = ["dataloader"] }
+async-trait = { workspace = true }
+filter_ast = { path = "../filter_ast" }
+graphql_common = { path = "../graphql_common" }
+item_filters = { path = "../item_filters" }
+macro_user_id = { path = "../macro_user_id" }
+models_properties = { path = "../models_properties" }
+models_soup = { path = "../models_soup" }
+properties = { path = "../properties", default-features = false, features = [
+ "ports",
+] }
+rootcause = { workspace = true }
+tokio = { workspace = true }
+tracing = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/rust/cloud-storage/graphql_properties/src/inputs.rs b/rust/cloud-storage/graphql_properties/src/inputs.rs
new file mode 100644
index 0000000000..cc55e6777a
--- /dev/null
+++ b/rust/cloud-storage/graphql_properties/src/inputs.rs
@@ -0,0 +1,95 @@
+use async_graphql::{Enum, ID};
+use filter_ast::Expr;
+use graphql_common::{IntoFilterExpr, filter_expr_input, parse_id};
+use item_filters::ast::properties::{
+ EntityRefId, PropertiesLiteral, PropertyEntityType, PropertyMatchValue,
+};
+
+filter_expr_input!(
+ GraphqlPropertiesExpr,
+ GraphqlPropertiesBinaryExpr,
+ GraphqlPropertiesLiteral,
+ PropertiesLiteral,
+ "PropertiesFilterExpr"
+);
+
+/// GraphQL input for matching a property value on an entity.
+#[derive(async_graphql::InputObject)]
+pub struct GraphqlPropertiesLiteral {
+ /// Property definition id to match.
+ property_definition_id: ID,
+ /// Optional entity type scope for the property match.
+ entity_type: Option<GraphqlPropertyEntityType>,
+ /// Value to compare against the property.
+ value: GraphqlPropertyMatchValue,
+}
+
+impl IntoFilterExpr<PropertiesLiteral> for GraphqlPropertiesLiteral {
+ fn into_expr(self) -> async_graphql::Result<Expr<PropertiesLiteral>> {
+ Ok(Expr::val(PropertiesLiteral {
+ property_definition_id: parse_id(self.property_definition_id, "propertyDefinitionId")?,
+ entity_type: self.entity_type.map(Into::into),
+ value: self.value.into_ast()?,
+ }))
+ }
+}
+
+/// GraphQL input value used when matching a property.
+#[derive(async_graphql::OneofObject)]
+pub enum GraphqlPropertyMatchValue {
+ /// Select option id to match.
+ SelectOption(ID),
+ /// Entity reference id to match.
+ EntityRef(String),
+}
+
+impl GraphqlPropertyMatchValue {
+ fn into_ast(self) -> async_graphql::Result<PropertyMatchValue> {
+ Ok(match self {
+ Self::SelectOption(id) => {
+ PropertyMatchValue::SelectOption(parse_id(id, "selectOption")?)
+ }
+ Self::EntityRef(value) => {
+ PropertyMatchValue::EntityRef(EntityRefId::new(value).map_err(|err| {
+ async_graphql::Error::new(format!("invalid entityRef: {err}"))
+ })?)
+ }
+ })
+ }
+}
+
+/// GraphQL entity type supported by property filters.
+#[derive(Enum, Copy, Clone, Eq, PartialEq)]
+pub enum GraphqlPropertyEntityType {
+ /// Channel entity.
+ Channel,
+ /// Chat entity.
+ Chat,
+ /// Company entity.
+ Company,
+ /// Document entity.
+ Document,
+ /// Project entity.
+ Project,
+ /// Task entity.
+ Task,
+ /// Thread entity.
+ Thread,
+ /// User entity.
+ User,
+}
+
+impl From<GraphqlPropertyEntityType> for PropertyEntityType {
+ fn from(value: GraphqlPropertyEntityType) -> Self {
+ match value {
+ GraphqlPropertyEntityType::Channel => Self::Channel,
+ GraphqlPropertyEntityType::Chat => Self::Chat,
+ GraphqlPropertyEntityType::Company => Self::Company,
+ GraphqlPropertyEntityType::Document => Self::Document,
+ GraphqlPropertyEntityType::Project => Self::Project,
+ GraphqlPropertyEntityType::Task => Self::Task,
+ GraphqlPropertyEntityType::Thread => Self::Thread,
+ GraphqlPropertyEntityType::User => Self::User,
+ }
+ }
+}
diff --git a/rust/cloud-storage/graphql_properties/src/lib.rs b/rust/cloud-storage/graphql_properties/src/lib.rs
new file mode 100644
index 0000000000..53f7c7fa0d
--- /dev/null
+++ b/rust/cloud-storage/graphql_properties/src/lib.rs
@@ -0,0 +1,15 @@
+//! GraphQL inbound adapter for the properties domain: property object types,
+//! property filter inputs, and the DataLoader-backed entity property edge.
+#![deny(missing_docs)]
+
+mod inputs;
+mod loaders;
+mod objects;
+
+pub use inputs::{GraphqlPropertiesBinaryExpr, GraphqlPropertiesExpr};
+pub use loaders::{
+ EntityPropertiesKey, EntityPropertiesLoader, SoupPropertyEdgeReader, entity_properties_loader,
+};
+pub use objects::{
+ GraphqlSoupProperty, GraphqlSoupPropertyEntityReference, GraphqlSoupPropertyValue,
+};
diff --git a/rust/cloud-storage/graphql_soup/src/loaders.rs b/rust/cloud-storage/graphql_properties/src/loaders.rs
similarity index 51%
rename from rust/cloud-storage/graphql_soup/src/loaders.rs
rename to rust/cloud-storage/graphql_properties/src/loaders.rs
index 6f36a7a51b..1e82cb1cfd 100644
--- a/rust/cloud-storage/graphql_soup/src/loaders.rs
+++ b/rust/cloud-storage/graphql_properties/src/loaders.rs
@@ -3,10 +3,6 @@ use std::{collections::HashMap, str::FromStr, sync::Arc};
use async_graphql::dataloader::{DataLoader, Loader};
use macro_user_id::user_id::MacroUserIdStr;
use models_soup::SoupProperty;
-use notification::domain::models::{
- UserNotificationRow,
- request::{NotificationEntityRef, NotificationItemType},
-};
/// Key for loading properties attached to an entity.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
@@ -152,150 +148,3 @@ pub fn entity_properties_loader(
) -> DataLoader<EntityPropertiesLoader> {
DataLoader::new(EntityPropertiesLoader::new(user_id, 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,
-}
-
-impl EntityNotificationsKey {
- fn notification_item_type(&self) -> Result<NotificationItemType, rootcause::Report> {
- match self.entity_type.as_str() {
- "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 entity_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",
- }
- }
-}
-
-/// 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: key.notification_item_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: EntityNotificationsKey::entity_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,
- )
-}
diff --git a/rust/cloud-storage/graphql_properties/src/objects.rs b/rust/cloud-storage/graphql_properties/src/objects.rs
new file mode 100644
index 0000000000..a829fe4a35
--- /dev/null
+++ b/rust/cloud-storage/graphql_properties/src/objects.rs
@@ -0,0 +1,242 @@
+use async_graphql::{Enum, ID, Object, SimpleObject};
+use models_properties::service::property_value::PropertyValue;
+use models_soup::SoupProperty;
+
+/// GraphQL representation of supported Soup property data types.
+#[derive(Enum, Clone, Copy, PartialEq, Eq)]
+pub enum GraphqlSoupDataType {
+ /// Boolean true/false values.
+ Boolean,
+ /// Date and time values.
+ Date,
+ /// Numeric values.
+ Number,
+ /// String/text values.
+ String,
+ /// Select property with numeric options.
+ SelectNumber,
+ /// Select property with string options.
+ SelectString,
+ /// Tag property - user- or team-scoped colored labels (always multi-select).
+ Tag,
+ /// Entity reference property.
+ Entity,
+ /// Link value Property.
+ Link,
+}
+
+impl From<models_properties::DataType> for GraphqlSoupDataType {
+ fn from(dt: models_properties::DataType) -> Self {
+ match dt {
+ models_properties::DataType::Boolean => Self::Boolean,
+ models_properties::DataType::Date => Self::Date,
+ models_properties::DataType::Number => Self::Number,
+ models_properties::DataType::String => Self::String,
+ models_properties::DataType::SelectNumber => Self::SelectNumber,
+ models_properties::DataType::SelectString => Self::SelectString,
+ models_properties::DataType::Tag => Self::Tag,
+ models_properties::DataType::Entity => Self::Entity,
+ models_properties::DataType::Link => Self::Link,
+ }
+ }
+}
+
+/// GraphQL property attached to a Soup entity.
+pub struct GraphqlSoupProperty(SoupProperty);
+
+impl From<SoupProperty> for GraphqlSoupProperty {
+ fn from(value: SoupProperty) -> Self {
+ Self(value)
+ }
+}
+
+#[Object]
+impl GraphqlSoupProperty {
+ /// Id of the shared property *definition* — deliberately not named `id`:
+ /// a property instance has no global identity (its `value` is
+ /// per-entity), so it must never be treated as a cacheable entity.
+ /// Normalized caches key objects by the presence of an `id` field.
+ async fn property_definition_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) -> GraphqlSoupDataType {
+ self.0.definition.data_type.into()
+ }
+
+ async fn is_multi_select(&self) -> bool {
+ self.0.definition.is_multi_select
+ }
+
+ async fn specific_entity_type(&self) -> Option<GraphqlSoupPropertyEntityType> {
+ self.0
+ .definition
+ .specific_entity_type
+ .map(GraphqlSoupPropertyEntityType::from)
+ }
+
+ 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: GraphqlSoupPropertyEntityType,
+ specific_message_id: Option<ID>,
+}
+
+/// GraphQL entity type supported by Soup properties.
+#[derive(Enum, Clone, Copy, PartialEq, Eq)]
+pub enum GraphqlSoupPropertyEntityType {
+ /// Channel entity.
+ Channel,
+ /// Chat entity.
+ Chat,
+ /// Company entity.
+ Company,
+ /// Document entity.
+ Document,
+ /// Project entity.
+ Project,
+ /// Task entity.
+ Task,
+ /// Thread entity.
+ Thread,
+ /// User entity.
+ User,
+}
+
+impl From<models_properties::EntityType> for GraphqlSoupPropertyEntityType {
+ fn from(entity: models_properties::EntityType) -> Self {
+ match entity {
+ models_properties::EntityType::Channel => Self::Channel,
+ models_properties::EntityType::Chat => Self::Chat,
+ models_properties::EntityType::Company => Self::Company,
+ models_properties::EntityType::Document => Self::Document,
+ models_properties::EntityType::Project => Self::Project,
+ models_properties::EntityType::Task => Self::Task,
+ models_properties::EntityType::Thread => Self::Thread,
+ models_properties::EntityType::User => Self::User,
+ }
+ }
+}
+
+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.into(),
+ specific_message_id: value
+ .specific_message_id
+ .map(|message_id| ID(message_id.to_string())),
+ }
+ }
+}
diff --git a/rust/cloud-storage/graphql_soup/AGENTS.md b/rust/cloud-storage/graphql_soup/AGENTS.md
index c54a2b31a1..61eb7aff05 100644
--- a/rust/cloud-storage/graphql_soup/AGENTS.md
+++ b/rust/cloud-storage/graphql_soup/AGENTS.md
@@ -1,67 +1,7 @@
-# graphql_soup — schema conventions
+# graphql_soup
-This crate defines the GraphQL schema consumed by the client's **normalized
-cache** (`rust/cloud-storage/client`, design doc:
-`js/app/docs/graphql-normalized-cache-plan.md`). Two field-naming
-conventions in this schema are load-bearing for cache correctness. The
-cache's build validates *shapes* but cannot validate *semantics* — that's
-what schema review is for.
-
-## 1. `id` is a reserved, semantic field name (presence-of-id convention)
-
-Clients key cache records by `__typename:id`. Consequences:
-
-- **An output object type with an `id: ID!` field is a normalized entity.**
- Two responses containing the same `__typename:id` pair are *merged into
- one record* — so `id` must identify the same logical value everywhere it
- can appear, across all queries, arguments, and parent objects.
-- **Only name a field `id` when it is the object's global identity.** If a
- type carries a reference to something else's id, name it accordingly:
- - `GraphqlSoupProperty` exposes `propertyDefinitionId`, **not** `id` — a
- property instance's `value` is per-entity, while the definition id is
- shared. Naming it `id` would merge property values across entities.
- - `GraphqlSoupChannelMessage.id` (renamed from `messageId`) — it *is* the
- message's identity, so it uses the reserved name.
-- **Types without an `id` field are embedded** inline in their parent
- record (`SoupPage`, participants, property values, `DocumentSubType`).
- This is correct for value objects and query-scoped wrappers. Do **not**
- add constant or synthetic ids to such types — a constant id (e.g.
- `"soup_page"`) would merge every instance into a single record globally.
-- `id` fields must be exactly `ID!` (non-null, non-list); the cache build
- (`rust/cloud-storage/client/cache-core/build.rs`) fails otherwise, and fails if
- the query root exposes an `id`.
-
-Review checklist when adding/changing a type:
-1. Does it have a stable global identity? → expose it as `id: ID!`.
-2. Is its content dependent on where it appears (parent entity, arguments)?
- → no `id` field; expose reference ids under descriptive names.
-3. Renaming/removing an `id` field changes client caching semantics — it
- rotates cache keys and turns entities into embedded values (or vice
- versa). Deliberate, but call it out in review.
-
-## 2. `QueryRoot → user` (viewer pattern) is the identity witness
-
-All user-scoped data hangs off `user: GraphqlUser!`, and `GraphqlUser.id`
-must be the **authenticated** user's id from the request context. The
-client extracts it from every response and passes it to the cache as a
-session tag: a response for a different user than the one bound to the
-cache triggers a full wipe-and-rebind (cross-user leak protection on
-account switches).
-
-- Never resolve `GraphqlUser.id` from anything other than the
- authenticated request context.
-- New user-scoped root data should be added under `GraphqlUser`, not as
- new root fields.
-
-## Regenerating the SDL
-
-After schema changes:
-
-```sh
-cargo run -p graphql_soup --bin graphql_soup_schema -- schema.graphql # from rust/cloud-storage
-```
-
-The exported `schema.graphql` feeds both the client codegen
-(`js/app && bun gen-graphql`) and the cache metadata codegen (hashing it —
-any change rotates all persisted client caches, which rebuild from the
-network automatically).
+This crate provides the soup-domain GraphQL wrapper types. The composed
+schema (root query, viewer, SDL export) lives in `complete_graph` — see
+`../complete_graph/AGENTS.md` for the schema conventions (presence-of-`id`
+normalized-cache rules and the viewer pattern), which apply to every type
+defined here.
diff --git a/rust/cloud-storage/graphql_soup/Cargo.toml b/rust/cloud-storage/graphql_soup/Cargo.toml
index f4e66dd03f..929111a236 100644
--- a/rust/cloud-storage/graphql_soup/Cargo.toml
+++ b/rust/cloud-storage/graphql_soup/Cargo.toml
@@ -5,14 +5,11 @@ edition = "2024"
publish = false
[dependencies]
-anyhow = { workspace = true }
async-graphql = { workspace = true, features = ["dataloader"] }
-async-trait = { workspace = true }
axum = { workspace = true }
axum-extra = { workspace = true }
chrono = { workspace = true }
document_sub_type = { path = "../document_sub_type" }
-either = { workspace = true }
email = { path = "../email", default-features = false, features = [
"axum",
"inbound",
@@ -22,6 +19,9 @@ entity_access = { path = "../entity_access", default-features = false, features
"inbound",
] }
filter_ast = { path = "../filter_ast" }
+graphql_common = { path = "../graphql_common" }
+graphql_notification = { path = "../graphql_notification" }
+graphql_properties = { path = "../graphql_properties" }
item_filters = { path = "../item_filters" }
macro_user_id = { path = "../macro_user_id" }
model_file_type = { path = "../model_file_type" }
@@ -30,15 +30,8 @@ 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", default-features = false, features = [
- "ports",
-] }
-rootcause = { workspace = true }
-tracing = { 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/inputs.rs b/rust/cloud-storage/graphql_soup/src/inputs.rs
index d475e4cbc8..0725536847 100644
--- a/rust/cloud-storage/graphql_soup/src/inputs.rs
+++ b/rust/cloud-storage/graphql_soup/src/inputs.rs
@@ -1,9 +1,13 @@
-use std::{str::FromStr, sync::Arc};
+use std::str::FromStr;
use async_graphql::{Enum, ID};
use chrono::{DateTime, Utc};
use document_sub_type::DocumentSubType;
use filter_ast::Expr;
+use graphql_common::{
+ IntoFilterExpr, filter_expr_input, optional_tree, parse_id, parse_macro_user_id,
+};
+use graphql_properties::GraphqlPropertiesExpr;
use item_filters::{
CallStatus, SharedEmailFilter,
ast::{
@@ -17,7 +21,6 @@ use item_filters::{
email::{Email, EmailLiteral},
foreign_entity::ForeignEntityLiteral,
project::ProjectLiteral,
- properties::{EntityRefId, PropertiesLiteral, PropertyEntityType, PropertyMatchValue},
},
};
use macro_user_id::{cowlike::CowLike, email::EmailStr, user_id::MacroUserIdStr};
@@ -152,68 +155,6 @@ impl GraphqlEntityFilterAst {
}
}
-trait IntoFilterExpr<T>: Sized {
- fn into_expr(self) -> async_graphql::Result<Expr<T>>;
-}
-
-fn optional_tree<I, T>(input: Option<I>) -> async_graphql::Result<Option<Arc<Expr<T>>>>
-where
- I: IntoFilterExpr<T>,
-{
- input.map(|expr| expr.into_expr().map(Arc::new)).transpose()
-}
-
-fn parse_uuid(value: String, field: &str) -> async_graphql::Result<Uuid> {
- Uuid::parse_str(&value)
- .map_err(|err| async_graphql::Error::new(format!("invalid {field} UUID `{value}`: {err}")))
-}
-
-fn parse_id(id: ID, field: &str) -> async_graphql::Result<Uuid> {
- parse_uuid(id.to_string(), field)
-}
-
-fn parse_macro_user_id(
- value: String,
- field: &str,
-) -> async_graphql::Result<MacroUserIdStr<'static>> {
- MacroUserIdStr::parse_from_str(&value)
- .map(CowLike::into_owned)
- .map_err(|err| async_graphql::Error::new(format!("invalid {field} `{value}`: {err}")))
-}
-
-macro_rules! filter_expr_input {
- ($name:ident, $binary_name:ident, $literal:ty, $target:ty, $type_name:literal) => {
- #[derive(async_graphql::InputObject)]
- struct $binary_name {
- left: Box<$name>,
- right: Box<$name>,
- }
-
- #[derive(async_graphql::OneofObject)]
- enum $name {
- And($binary_name),
- Or($binary_name),
- Not(Box<$name>),
- Literal($literal),
- }
-
- impl IntoFilterExpr<$target> for $name {
- fn into_expr(self) -> async_graphql::Result<Expr<$target>> {
- match self {
- Self::And(exprs) => {
- Ok(Expr::and(exprs.left.into_expr()?, exprs.right.into_expr()?))
- }
- Self::Or(exprs) => {
- Ok(Expr::or(exprs.left.into_expr()?, exprs.right.into_expr()?))
- }
- Self::Not(expr) => expr.into_expr().map(Expr::is_not),
- Self::Literal(literal) => literal.into_expr(),
- }
- }
- }
- };
-}
-
filter_expr_input!(
GraphqlDocumentExpr,
GraphqlDocumentBinaryExpr,
@@ -277,14 +218,6 @@ filter_expr_input!(
ForeignEntityLiteral,
"ForeignEntityFilterExpr"
);
-filter_expr_input!(
- GraphqlPropertiesExpr,
- GraphqlPropertiesBinaryExpr,
- GraphqlPropertiesLiteral,
- PropertiesLiteral,
- "PropertiesFilterExpr"
-);
-
#[derive(async_graphql::InputObject)]
struct GraphqlEmailFilterAst {
tree: Option<GraphqlEmailExpr>,
@@ -740,71 +673,6 @@ impl IntoFilterExpr<ForeignEntityLiteral> for GraphqlForeignEntityLiteral {
}
}
-#[derive(async_graphql::InputObject)]
-struct GraphqlPropertiesLiteral {
- property_definition_id: ID,
- entity_type: Option<GraphqlPropertyEntityType>,
- value: GraphqlPropertyMatchValue,
-}
-
-impl IntoFilterExpr<PropertiesLiteral> for GraphqlPropertiesLiteral {
- fn into_expr(self) -> async_graphql::Result<Expr<PropertiesLiteral>> {
- Ok(Expr::val(PropertiesLiteral {
- property_definition_id: parse_id(self.property_definition_id, "propertyDefinitionId")?,
- entity_type: self.entity_type.map(Into::into),
- value: self.value.into_ast()?,
- }))
- }
-}
-
-#[derive(async_graphql::OneofObject)]
-enum GraphqlPropertyMatchValue {
- SelectOption(ID),
- EntityRef(String),
-}
-
-impl GraphqlPropertyMatchValue {
- fn into_ast(self) -> async_graphql::Result<PropertyMatchValue> {
- Ok(match self {
- Self::SelectOption(id) => {
- PropertyMatchValue::SelectOption(parse_id(id, "selectOption")?)
- }
- Self::EntityRef(value) => {
- PropertyMatchValue::EntityRef(EntityRefId::new(value).map_err(|err| {
- async_graphql::Error::new(format!("invalid entityRef: {err}"))
- })?)
- }
- })
- }
-}
-
-#[derive(Enum, Copy, Clone, Eq, PartialEq)]
-enum GraphqlPropertyEntityType {
- Channel,
- Chat,
- Company,
- Document,
- Project,
- Task,
- Thread,
- User,
-}
-
-impl From<GraphqlPropertyEntityType> for PropertyEntityType {
- fn from(value: GraphqlPropertyEntityType) -> Self {
- match value {
- GraphqlPropertyEntityType::Channel => Self::Channel,
- GraphqlPropertyEntityType::Chat => Self::Chat,
- GraphqlPropertyEntityType::Company => Self::Company,
- GraphqlPropertyEntityType::Document => Self::Document,
- GraphqlPropertyEntityType::Project => Self::Project,
- GraphqlPropertyEntityType::Task => Self::Task,
- GraphqlPropertyEntityType::Thread => Self::Thread,
- GraphqlPropertyEntityType::User => Self::User,
- }
- }
-}
-
/// GraphQL representation of supported simple Soup sorts.
#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub enum GraphqlSimpleSortMethod {
diff --git a/rust/cloud-storage/graphql_soup/src/lib.rs b/rust/cloud-storage/graphql_soup/src/lib.rs
index 5ed245d12d..0e136780cd 100644
--- a/rust/cloud-storage/graphql_soup/src/lib.rs
+++ b/rust/cloud-storage/graphql_soup/src/lib.rs
@@ -2,29 +2,27 @@
//!
//! This crate is intentionally additive: it maps GraphQL requests onto the
//! existing `soup` domain service without changing the existing REST API.
+//! The schema itself is composed and served by the `complete_graph` crate.
#![deny(missing_docs)]
mod inputs;
-mod loaders;
mod objects;
-mod request_context;
-mod schema;
+mod resolvers;
-pub use inputs::{GraphqlSimpleSortMethod, SoupInput};
-pub use loaders::{
- EntityNotificationsKey, EntityNotificationsLoader, EntityPropertiesKey, EntityPropertiesLoader,
- SoupNotificationEdgeReader, SoupPropertyEdgeReader, entity_notifications_loader,
+pub use graphql_common::{GraphqlSoupEntityType, GraphqlSoupRequestParts};
+pub use graphql_notification::{
+ EntityNotificationsKey, EntityNotificationsLoader, GraphqlSoupNotification,
+ SoupNotificationEdgeReader, entity_notifications_loader,
+};
+pub use graphql_properties::{
+ EntityPropertiesKey, EntityPropertiesLoader, GraphqlSoupProperty,
+ GraphqlSoupPropertyEntityReference, GraphqlSoupPropertyValue, SoupPropertyEdgeReader,
entity_properties_loader,
};
+pub use inputs::{GraphqlSimpleSortMethod, SoupInput};
pub use objects::{
GraphqlSoupCall, GraphqlSoupChannel, GraphqlSoupChannelThread, GraphqlSoupChat,
GraphqlSoupCrmCompany, GraphqlSoupDocument, GraphqlSoupDocumentSubType, GraphqlSoupEmailThread,
- GraphqlSoupEntity, GraphqlSoupEntityType, GraphqlSoupForeignEntity, GraphqlSoupItem,
- GraphqlSoupNotification, GraphqlSoupProject, GraphqlSoupProperty,
- GraphqlSoupPropertyEntityReference, GraphqlSoupPropertyValue, SoupPage,
-};
-pub use request_context::GraphqlSoupRequestParts;
-pub use schema::{
- SchemaOnlySoupSchema, SchemaOnlyState, SharedSoupSchema, SharedSoupService, SoupQueryRoot,
- SoupSchema, build_schema, build_schema_from_arc, build_schema_with_service,
+ GraphqlSoupEntity, GraphqlSoupForeignEntity, GraphqlSoupItem, GraphqlSoupProject, SoupPage,
};
+pub use resolvers::{SharedSoupService, resolve_soup};
diff --git a/rust/cloud-storage/graphql_soup/src/objects.rs b/rust/cloud-storage/graphql_soup/src/objects.rs
index 07c6eca7e1..84134f4a7b 100644
--- a/rust/cloud-storage/graphql_soup/src/objects.rs
+++ b/rust/cloud-storage/graphql_soup/src/objects.rs
@@ -1,9 +1,11 @@
-use async_graphql::{Context, Enum, ID, Json, Object, SimpleObject, Union, dataloader::DataLoader};
-use model_entity::EntityType;
+use async_graphql::{Context, ID, Json, Object, SimpleObject, Union};
+use graphql_common::GraphqlSoupEntityType;
+use graphql_notification::{
+ EntityNotificationsKey, GraphqlSoupNotification, load_entity_notifications,
+};
+use graphql_properties::GraphqlSoupProperty;
use models_pagination::PaginatedOpaqueCursor;
-use models_properties::service::property_value::PropertyValue;
use models_soup::{
- SoupProperty,
call_record::{SoupCallRecord, SoupCallRecordParticipant},
chat::SoupChat,
comms::{ChannelMessage, ChannelParticipant, ChannelType, SoupChannel, SoupChannelThread},
@@ -17,12 +19,9 @@ use models_soup::{
item::SoupItem,
project::SoupProject,
};
-use notification::domain::models::UserNotificationRow;
use serde_json::Value;
use soup::domain::models::FrecencySoupItem;
-use crate::loaders::{EntityNotificationsKey, EntityNotificationsLoader};
-
/// Page returned by `Query.soup`.
#[derive(SimpleObject)]
pub struct SoupPage {
@@ -53,57 +52,6 @@ pub struct GraphqlSoupItem {
entity: GraphqlSoupEntity,
}
-/// GraphQL representation of Soup entity types.
-#[derive(Enum, Copy, Clone, Eq, PartialEq)]
-pub enum GraphqlSoupEntityType {
- /// Document entity.
- Document,
- /// Chat entity.
- Chat,
- /// Project entity.
- Project,
- /// Email thread entity.
- EmailThread,
- /// Channel entity.
- Channel,
- /// Channel thread entity.
- ChannelThread,
- /// Call entity.
- Call,
- /// CRM company entity.
- CrmCompany,
- /// Foreign entity.
- ForeignEntity,
- /// User entity
- User,
- /// Team entity
- Team,
- /// Static File
- StaticFile,
- /// crm contact
- CrmContact,
-}
-
-impl From<EntityType> for GraphqlSoupEntityType {
- fn from(entity_type: EntityType) -> Self {
- match entity_type {
- EntityType::Document => Self::Document,
- EntityType::Chat => Self::Chat,
- EntityType::Project => Self::Project,
- EntityType::EmailThread => Self::EmailThread,
- EntityType::Channel => Self::Channel,
- EntityType::ChannelMessage => Self::ChannelThread,
- EntityType::Call => Self::Call,
- EntityType::CrmCompany => Self::CrmCompany,
- EntityType::ForeignEntity => Self::ForeignEntity,
- EntityType::User => Self::User,
- EntityType::Team => Self::Team,
- EntityType::StaticFile => Self::StaticFile,
- EntityType::CrmContact => Self::CrmContact,
- }
- }
-}
-
#[Object]
impl GraphqlSoupItem {
async fn id(&self) -> ID {
@@ -235,7 +183,7 @@ impl GraphqlSoupDocument {
.properties
.iter()
.cloned()
- .map(GraphqlSoupProperty)
+ .map(GraphqlSoupProperty::from)
.collect()
}
@@ -286,299 +234,6 @@ impl GraphqlSoupDocumentSubType {
}
}
-/// 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) -> GraphqlSoupEntityType {
- GraphqlSoupEntityType::from(self.0.entity.entity_type)
- }
-
- 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())
-}
-
-#[derive(Enum, Clone, Copy, PartialEq, Eq)]
-pub enum GraphqlSoupDataType {
- /// Boolean true/false values.
- Boolean,
- /// Date and time values.
- Date,
- /// Numeric values.
- Number,
- /// String/text values.
- String,
- /// Select property with numeric options.
- SelectNumber,
- /// Select property with string options.
- SelectString,
- /// Tag property - user- or team-scoped colored labels (always multi-select).
- Tag,
- /// Entity reference property.
- Entity,
- /// Link value Property.
- Link,
-}
-
-impl GraphqlSoupDataType {
- fn from_properties_data_type(dt: models_properties::DataType) -> Self {
- match dt {
- models_properties::DataType::Boolean => Self::Boolean,
- models_properties::DataType::Date => Self::Date,
- models_properties::DataType::Number => Self::Number,
- models_properties::DataType::String => Self::String,
- models_properties::DataType::SelectNumber => Self::SelectNumber,
- models_properties::DataType::SelectString => Self::SelectString,
- models_properties::DataType::Tag => Self::Tag,
- models_properties::DataType::Entity => Self::Entity,
- models_properties::DataType::Link => Self::Link,
- }
- }
-}
-
-/// GraphQL property attached to a Soup entity.
-pub struct GraphqlSoupProperty(SoupProperty);
-
-#[Object]
-impl GraphqlSoupProperty {
- /// Id of the shared property *definition* — deliberately not named `id`:
- /// a property instance has no global identity (its `value` is
- /// per-entity), so it must never be treated as a cacheable entity.
- /// Normalized caches key objects by the presence of an `id` field.
- async fn property_definition_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) -> GraphqlSoupDataType {
- GraphqlSoupDataType::from_properties_data_type(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<GraphqlSoupPropertyEntityType> {
- self.0
- .definition
- .specific_entity_type
- .map(GraphqlSoupPropertyEntityType::from_property_entity)
- }
-
- 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: GraphqlSoupPropertyEntityType,
- specific_message_id: Option<ID>,
-}
-
-#[derive(Enum, Clone, Copy, PartialEq, Eq)]
-pub enum GraphqlSoupPropertyEntityType {
- Channel,
- Chat,
- Company,
- Document,
- Project,
- Task,
- Thread,
- User,
-}
-
-impl GraphqlSoupPropertyEntityType {
- fn from_property_entity(entity: models_properties::EntityType) -> Self {
- match entity {
- models_properties::EntityType::Channel => Self::Channel,
- models_properties::EntityType::Chat => Self::Chat,
- models_properties::EntityType::Company => Self::Company,
- models_properties::EntityType::Document => Self::Document,
- models_properties::EntityType::Project => Self::Project,
- models_properties::EntityType::Task => Self::Task,
- models_properties::EntityType::Thread => Self::Thread,
- models_properties::EntityType::User => Self::User,
- }
- }
-}
-
-impl From<&models_properties::EntityReference> for GraphqlSoupPropertyEntityReference {
- fn from(value: &models_properties::EntityReference) -> Self {
- Self {
- entity_id: value.entity_id.clone(),
- entity_type: GraphqlSoupPropertyEntityType::from_property_entity(value.entity_type),
- specific_message_id: value
- .specific_message_id
- .map(|message_id| ID(message_id.to_string())),
- }
- }
-}
-
/// GraphQL chat entity.
pub struct GraphqlSoupChat(SoupChat);
@@ -625,7 +280,7 @@ impl GraphqlSoupChat {
.properties
.iter()
.cloned()
- .map(GraphqlSoupProperty)
+ .map(GraphqlSoupProperty::from)
.collect()
}
@@ -686,7 +341,7 @@ impl GraphqlSoupProject {
.properties
.iter()
.cloned()
- .map(GraphqlSoupProperty)
+ .map(GraphqlSoupProperty::from)
.collect()
}
@@ -1002,7 +657,7 @@ impl GraphqlSoupEmailThread {
.properties
.iter()
.cloned()
- .map(GraphqlSoupProperty)
+ .map(GraphqlSoupProperty::from)
.collect()
}
@@ -1444,7 +1099,7 @@ impl GraphqlSoupCrmCompany {
.properties
.iter()
.cloned()
- .map(GraphqlSoupProperty)
+ .map(GraphqlSoupProperty::from)
.collect()
}
@@ -1504,6 +1159,3 @@ impl GraphqlSoupForeignEntity {
.await
}
}
-
-#[cfg(test)]
-mod tests;
diff --git a/rust/cloud-storage/graphql_soup/src/resolvers.rs b/rust/cloud-storage/graphql_soup/src/resolvers.rs
new file mode 100644
index 0000000000..a2c155d564
--- /dev/null
+++ b/rust/cloud-storage/graphql_soup/src/resolvers.rs
@@ -0,0 +1,116 @@
+use std::sync::Arc;
+
+use async_graphql::Context;
+use axum::extract::FromRef;
+use axum_extra::extract::Cached;
+use email::{
+ domain::ports::EmailService,
+ inbound::axum::{axum_impls::MultiEmailLinkExtractor, previews_router::EmailRouterState},
+};
+use entity_access::{
+ domain::{
+ models::{EntityAccessReceipt, MemberTeamRole},
+ ports::EntityAccessService,
+ },
+ inbound::axum_extractors::OptionalMacroUserTeamExtractor,
+};
+use graphql_common::extract_part;
+use model_user::axum_extractor::MacroUserExtractor;
+use models_pagination::TypeEraseCursor;
+use soup::domain::{models::SoupRequest, ports::SoupService};
+
+use crate::{inputs::SoupInput, objects::SoupPage};
+
+/// Object-safe-ish wrapper for sharing a concrete Soup service with GraphQL.
+pub struct SharedSoupService<S>(Arc<S>);
+
+impl<S> Clone for SharedSoupService<S> {
+ fn clone(&self) -> Self {
+ Self(Arc::clone(&self.0))
+ }
+}
+
+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
+ }
+
+ async fn caller_tag_sets<'a>(
+ &self,
+ user_id: macro_user_id::user_id::MacroUserIdStr<'a>,
+ ) -> Result<
+ Vec<models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions>,
+ soup::domain::models::SoupErr,
+ >{
+ self.0.caller_tag_sets(user_id).await
+ }
+}
+
+/// Resolve a page of Soup items for the authenticated user: runs the lazy
+/// axum extractors against the request context, converts the GraphQL input
+/// into a Soup request, and executes it against the Soup service.
+pub async fn resolve_soup<S, E, EAS, St>(
+ service: &S,
+ ctx: &Context<'_>,
+ input: SoupInput,
+) -> async_graphql::Result<SoupPage>
+where
+ S: SoupService,
+ E: EmailService,
+ EAS: EntityAccessService,
+ St: Clone + Send + Sync + 'static,
+ EmailRouterState<E>: FromRef<St>,
+ Arc<EAS>: FromRef<St>,
+{
+ let Cached(MacroUserExtractor { macro_user_id, .. }) =
+ extract_part::<Cached<MacroUserExtractor>, St>(ctx).await?;
+ let Cached(MultiEmailLinkExtractor(links, _)) =
+ extract_part::<Cached<MultiEmailLinkExtractor<E>>, St>(ctx).await?;
+ let link_ids = links.into_iter().map(|link| link.id).collect();
+ let request = input.into_request(macro_user_id, link_ids)?;
+
+ // Team membership is only resolved when the query actually asks for
+ // CRM-scoped data; everything else skips the lookup entirely. The
+ // authorization itself (membership + admin role for hidden
+ // companies) is enforced by the soup domain and CRM service from
+ // the receipt.
+ let effective_filter = request.cursor.filter();
+ let team_receipt = if effective_filter.requests_crm_scope()
+ || effective_filter.requests_crm_admin()
+ {
+ let Cached(team) =
+ extract_part::<Cached<OptionalMacroUserTeamExtractor<MemberTeamRole, EAS>>, St>(ctx)
+ .await?;
+ team.entity_access_receipt
+ } else {
+ None
+ };
+
+ let page = service.get_user_soup(request, team_receipt).await?;
+ Ok(SoupPage::from(page.type_erase()))
+}
diff --git a/rust/cloud-storage/schema.graphql b/rust/cloud-storage/schema.graphql
index 02ffac5e96..4d71377e87 100644
--- a/rust/cloud-storage/schema.graphql
+++ b/rust/cloud-storage/schema.graphql
@@ -291,25 +291,73 @@ input GraphqlPropertiesExpr @oneOf {
literal: GraphqlPropertiesLiteral
}
+"""
+GraphQL input for matching a property value on an entity.
+"""
input GraphqlPropertiesLiteral {
+ """
+ Property definition id to match.
+ """
propertyDefinitionId: ID!
+ """
+ Optional entity type scope for the property match.
+ """
entityType: GraphqlPropertyEntityType
+ """
+ Value to compare against the property.
+ """
value: GraphqlPropertyMatchValue!
}
+"""
+GraphQL entity type supported by property filters.
+"""
enum GraphqlPropertyEntityType {
+ """
+ Channel entity.
+ """
CHANNEL
+ """
+ Chat entity.
+ """
CHAT
+ """
+ Company entity.
+ """
COMPANY
+ """
+ Document entity.
+ """
DOCUMENT
+ """
+ Project entity.
+ """
PROJECT
+ """
+ Task entity.
+ """
TASK
+ """
+ Thread entity.
+ """
THREAD
+ """
+ User entity.
+ """
USER
}
+"""
+GraphQL input value used when matching a property.
+"""
input GraphqlPropertyMatchValue @oneOf {
+ """
+ Select option id to match.
+ """
selectOption: ID
+ """
+ Entity reference id to match.
+ """
entityRef: String
}
@@ -446,6 +494,9 @@ type GraphqlSoupCrmCompany {
notifications: [GraphqlSoupNotification!]!
}
+"""
+GraphQL representation of supported Soup property data types.
+"""
enum GraphqlSoupDataType {
"""
Boolean true/false values.
@@ -609,19 +660,19 @@ enum GraphqlSoupEntityType {
"""
FOREIGN_ENTITY
"""
- User entity
+ User entity.
"""
USER
"""
- Team entity
+ Team entity.
"""
TEAM
"""
- Static File
+ Static file entity.
"""
STATIC_FILE
"""
- crm contact
+ CRM contact entity.
"""
CRM_CONTACT
}
@@ -699,14 +750,41 @@ type GraphqlSoupPropertyEntityReference {
specificMessageId: ID
}
+"""
+GraphQL entity type supported by Soup properties.
+"""
enum GraphqlSoupPropertyEntityType {
+ """
+ Channel entity.
+ """
CHANNEL
+ """
+ Chat entity.
+ """
CHAT
+ """
+ Company entity.
+ """
COMPANY
+ """
+ Document entity.
+ """
DOCUMENT
+ """
+ Project entity.
+ """
PROJECT
+ """
+ Task entity.
+ """
TASK
+ """
+ Thread entity.
+ """
THREAD
+ """
+ User entity.
+ """
USER
}
diff --git a/rust/cloud-storage/tools/xtask/crates/xtask_graphql_soup_schema/src/main.rs b/rust/cloud-storage/tools/xtask/crates/xtask_graphql_soup_schema/src/main.rs
index c5da6ee939..4782926e3d 100644
--- a/rust/cloud-storage/tools/xtask/crates/xtask_graphql_soup_schema/src/main.rs
+++ b/rust/cloud-storage/tools/xtask/crates/xtask_graphql_soup_schema/src/main.rs
@@ -1,6 +1,6 @@
//! `cargo x graphql-soup-schema <output-path>`
//!
-//! Exports the GraphQL Soup SDL to a file by running the `graphql_soup`
+//! Exports the GraphQL Soup SDL to a file by running the `complete_graph`
//! crate's schema-export bin with `SQLX_OFFLINE` so it needs no database.
use std::{path::Path, process::Command};
@@ -25,9 +25,9 @@ fn run(output_path: &Path) -> Result<()> {
.arg("env.SQLX_OFFLINE=\"true\"")
.arg("--quiet")
.arg("-p")
- .arg("graphql_soup")
+ .arg("complete_graph")
.arg("--bin")
- .arg("graphql_soup_schema")
+ .arg("graphql_schema")
.arg("--")
.arg(output_path)
.status()
diff --git a/rust/cloud-storage/workspace-hack/Cargo.toml b/rust/cloud-storage/workspace-hack/Cargo.toml
index 5a9d032030..280277d763 100644
--- a/rust/cloud-storage/workspace-hack/Cargo.toml
+++ b/rust/cloud-storage/workspace-hack/Cargo.toml
@@ -17,6 +17,7 @@ publish = false
[dependencies]
ahash = { version = "0.8" }
aho-corasick = { version = "1" }
+async-graphql = { version = "7", features = ["dataloader"] }
aws-config = { version = "1", features = ["behavior-version-latest"] }
aws-credential-types = { version = "1", default-features = false, features = ["hardcoded-credentials", "test-util"] }
aws-runtime = { version = "1", default-features = false, features = ["event-stream", "http-02x", "http-1x", "sigv4a"] }
@@ -136,6 +137,7 @@ zeroize = { version = "1", features = ["derive"] }
[build-dependencies]
ahash = { version = "0.8" }
aho-corasick = { version = "1" }
+async-graphql = { version = "7", features = ["dataloader"] }
aws-config = { version = "1", features = ["behavior-version-latest"] }
aws-credential-types = { version = "1", default-features = false, features = ["hardcoded-credentials", "test-util"] }
aws-runtime = { version = "1", default-features = false, features = ["event-stream", "http-02x", "http-1x", "sigv4a"] }