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.

fix(soup): handle null GraphQL notification responses (#4923)

Sean Aye139310c5fc78
diff --git a/apps/web/src/lib/graphql-cache/solid/create-query-signal.test.ts b/apps/web/src/lib/graphql-cache/solid/create-query-signal.test.ts
index 9078465289..80c8024e6f 100644
--- a/apps/web/src/lib/graphql-cache/solid/create-query-signal.test.ts
+++ b/apps/web/src/lib/graphql-cache/solid/create-query-signal.test.ts
@@ -1,10 +1,14 @@
-import type { Client, OperationResult } from '@urql/core';
+import { type Client, CombinedError, type OperationResult } from '@urql/core';
import { createRoot, createSignal } from 'solid-js';
import { afterEach, describe, expect, it } from 'vitest';
import { makeSubject } from 'wonka';
import { createQuerySignal, type QuerySignal } from './create-query-signal';
-type FakeResult = Partial<OperationResult>;
+type FakeResult = Omit<Partial<OperationResult>, 'data'> & {
+ // GraphQL permits a root-level null response even though urql's operation
+ // result type models missing data as undefined.
+ data?: OperationResult['data'] | null;
+};
/**
* Fake urql client: each `query()` call returns a fresh subject the test
@@ -80,6 +84,24 @@ describe('createQuerySignal', () => {
expect(query.data()).toEqual({ from: 'optimistic' });
});
+ it('retains valid data and reports errors when GraphQL data is null', () => {
+ const harness = setup();
+ dispose = harness.dispose;
+ const { query, executions } = harness;
+ const error = new CombinedError({
+ graphQLErrors: ['root non-null field failed'],
+ });
+
+ executions[0]?.next({ data: null, error });
+ expect(query.data()).toBeUndefined();
+ expect(query.error()).toBe(error);
+
+ executions[0]?.next({ data: { page: 1 } });
+ executions[0]?.next({ data: null, error });
+ expect(query.data()).toEqual({ page: 1 });
+ expect(query.error()).toBe(error);
+ });
+
it('resubscribes when variables change and ignores the old source', () => {
const harness = setup();
dispose = harness.dispose;
diff --git a/apps/web/src/lib/graphql-cache/solid/create-query-signal.ts b/apps/web/src/lib/graphql-cache/solid/create-query-signal.ts
index 4a4f815490..aec335d428 100644
--- a/apps/web/src/lib/graphql-cache/solid/create-query-signal.ts
+++ b/apps/web/src/lib/graphql-cache/solid/create-query-signal.ts
@@ -75,7 +75,11 @@ export function createQuerySignal<TData, TVariables extends AnyVariables>(
}),
subscribe((result) => {
batch(() => {
- setData(() => result.data);
+ // GraphQL responses may contain `data: null` at runtime when a
+ // non-null field error propagates to the operation root, even
+ // though urql's static type only includes `undefined`. Keep the
+ // last valid result and expose the CombinedError to the caller.
+ if (result.data != null) setData(() => result.data);
setError(result.error);
setStale(result.stale);
setFetching(false);
diff --git a/apps/web/src/lib/queries/soup/reactive-items.ts b/apps/web/src/lib/queries/soup/reactive-items.ts
index 12f486e67f..3826b835c1 100644
--- a/apps/web/src/lib/queries/soup/reactive-items.ts
+++ b/apps/web/src/lib/queries/soup/reactive-items.ts
@@ -11,6 +11,7 @@
*/
import { createQuerySignal } from '@graphql-cache/solid/create-query-signal';
+import { logger } from '@observability/logger';
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
import {
SoupDocument,
@@ -22,6 +23,7 @@ import {
getGraphqlSoupClient,
mapGraphqlSoupPage,
} from '@service-storage/graphql-soup';
+import type { CombinedError } from '@urql/core';
import {
type Accessor,
createComputed,
@@ -46,6 +48,8 @@ export type ReactiveSoupAstItemsQueryOptions = {
export type ReactiveSoupAstItemsQuery = {
data: Accessor<SoupAstItemsData | undefined>;
+ /** Latest GraphQL transport or application error. */
+ error: Accessor<CombinedError | undefined>;
/** False when the filter AST has no GraphQL translation. */
isSupported: Accessor<boolean>;
isLoading: Accessor<boolean>;
@@ -105,11 +109,26 @@ export function useReactiveSoupAstItemsQuery(
});
const page = createMemo(() => {
const data = query.data();
- return data === undefined ? undefined : mapGraphqlSoupPage(data);
+ return data == null ? undefined : mapGraphqlSoupPage(data);
});
return { query, page };
});
+ const error = (): CombinedError | undefined => {
+ for (const entry of pages()) {
+ const queryError = entry.query.error();
+ if (queryError) return queryError;
+ }
+ return undefined;
+ };
+ createComputed(
+ on(error, (queryError) => {
+ if (queryError) {
+ logger.error(queryError, { graphqlOperation: 'Soup' });
+ }
+ })
+ );
+
const lastPage = () => pages().at(-1);
const data = createMemo<SoupAstItemsData | undefined>(() => {
@@ -131,6 +150,7 @@ export function useReactiveSoupAstItemsQuery(
return {
data,
+ error,
isSupported,
isLoading: () => data() === undefined && isFetching(),
isFetching,
diff --git a/crates/graphql_notification/src/loaders.rs b/crates/graphql_notification/src/loaders.rs
index f931f773b5..6b4f4bd0a8 100644
--- a/crates/graphql_notification/src/loaders.rs
+++ b/crates/graphql_notification/src/loaders.rs
@@ -8,26 +8,53 @@ use notification::domain::models::{
};
use rootcause::markers::{Cloneable, Dynamic};
+/// Tests for notification entity mapping and batching.
+#[cfg(test)]
+mod test;
+
/// Map a shared entity type to the notification domain's item type.
-fn notification_item_type(
- entity_type: model_entity::EntityType,
-) -> Result<NotificationItemType, rootcause::Report> {
+///
+/// Some Soup entities, such as CRM companies, do not have a corresponding
+/// notification type. Those entities have an empty notification edge rather
+/// than failing the whole DataLoader batch.
+fn notification_item_type(entity_type: model_entity::EntityType) -> Option<NotificationItemType> {
use model_entity::EntityType;
match entity_type {
- EntityType::EmailThread => Ok(NotificationItemType::Email),
- EntityType::ChannelMessage => Ok(NotificationItemType::Message),
- EntityType::Channel => Ok(NotificationItemType::Channel),
- EntityType::Document => Ok(NotificationItemType::Document),
- EntityType::Project => Ok(NotificationItemType::Project),
- EntityType::Chat => Ok(NotificationItemType::Chat),
- EntityType::Call => Ok(NotificationItemType::Call),
- EntityType::ForeignEntity => Ok(NotificationItemType::Github),
- other => Err(rootcause::report!(
- "unsupported notification entity type {other}"
- )),
+ EntityType::EmailThread => Some(NotificationItemType::Email),
+ EntityType::ChannelMessage => Some(NotificationItemType::Message),
+ EntityType::Channel => Some(NotificationItemType::Channel),
+ EntityType::Document => Some(NotificationItemType::Document),
+ EntityType::Project => Some(NotificationItemType::Project),
+ EntityType::Chat => Some(NotificationItemType::Chat),
+ EntityType::Call => Some(NotificationItemType::Call),
+ EntityType::ForeignEntity => Some(NotificationItemType::Github),
+ EntityType::User
+ | EntityType::Team
+ | EntityType::StaticFile
+ | EntityType::CrmCompany
+ | EntityType::CrmContact => None,
}
}
+/// Build notification-service references for the subset of entities that can
+/// own notifications.
+fn notification_refs(
+ keys: &[model_entity::Entity<'static>],
+) -> Vec<(model_entity::Entity<'static>, NotificationEntityRef)> {
+ keys.iter()
+ .filter_map(|key| {
+ let entity_type = notification_item_type(key.entity_type)?;
+ Some((
+ key.clone(),
+ NotificationEntityRef {
+ entity_type,
+ id: key.entity_id.to_string(),
+ },
+ ))
+ })
+ .collect()
+}
+
/// Reader used by GraphQL notification edges.
pub trait SoupNotificationEdgeReader: Send + Sync + 'static {
/// Load notifications for the requested entity keys.
@@ -62,18 +89,10 @@ where
.map(|key| (key, Vec::new()))
.collect::<HashMap<_, _>>();
- let requested_refs = keys
- .iter()
- .map(|key| {
- Ok((
- key.clone(),
- NotificationEntityRef {
- entity_type: notification_item_type(key.entity_type)?,
- id: key.entity_id.to_string(),
- },
- ))
- })
- .collect::<Result<Vec<_>, rootcause::Report>>()?;
+ let requested_refs = notification_refs(&keys);
+ if requested_refs.is_empty() {
+ return Ok(result);
+ }
let entity_refs = requested_refs
.iter()
diff --git a/crates/graphql_notification/src/loaders/test.rs b/crates/graphql_notification/src/loaders/test.rs
new file mode 100644
index 0000000000..ea35c4162f
--- /dev/null
+++ b/crates/graphql_notification/src/loaders/test.rs
@@ -0,0 +1,28 @@
+use super::*;
+
+/// CRM companies are omitted because the notification domain has no CRM
+/// notification item type.
+#[test]
+fn crm_companies_have_an_empty_notification_edge() {
+ let keys =
+ vec![model_entity::EntityType::CrmCompany.with_entity_string("company-1".to_owned())];
+
+ assert!(notification_refs(&keys).is_empty());
+}
+
+/// Unsupported entities do not prevent supported entities in the same Soup
+/// page from being requested.
+#[test]
+fn mixed_batches_keep_supported_notification_entities() {
+ let keys = vec![
+ model_entity::EntityType::CrmCompany.with_entity_string("company-1".to_owned()),
+ model_entity::EntityType::Document.with_entity_string("document-1".to_owned()),
+ ];
+
+ let refs = notification_refs(&keys);
+
+ assert_eq!(refs.len(), 1);
+ assert_eq!(refs[0].0, keys[1]);
+ assert_eq!(refs[0].1.entity_type, NotificationItemType::Document);
+ assert_eq!(refs[0].1.id, "document-1");
+}