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/filter query variables (#5444)

Sean Ayec4a3f9172ffe
diff --git a/apps/web/src/lib/graphql-cache/exchange/inspection.test.ts b/apps/web/src/lib/graphql-cache/exchange/inspection.test.ts
index b310d39a38..aa5ef1dd35 100644
--- a/apps/web/src/lib/graphql-cache/exchange/inspection.test.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/inspection.test.ts
@@ -19,11 +19,20 @@ const input = {
};
describe('typed generated query inspection', () => {
- it('serializes only the document, operation name, and field path', async () => {
+ it('serializes the document, field path, and typed variable filters', async () => {
const inspectQuery = async (request: unknown) => {
expect(request).toMatchObject({
operationName: 'GroupSoupMembership',
path: [{ field: 'user' }, { field: 'groupSoup' }],
+ variableFilters: [
+ {
+ input: {
+ initial: {
+ groupBy: { propertyDefinitionId: 'status-def' },
+ },
+ },
+ },
+ ],
});
expect(request).not.toHaveProperty('variables');
expect(request).not.toHaveProperty('entityKey');
@@ -43,7 +52,18 @@ describe('typed generated query inspection', () => {
const result = await inspect(
host,
- selectAll(GroupSoupMembershipDocument).field('user').field('groupSoup')
+ selectAll(GroupSoupMembershipDocument).field('user').field('groupSoup'),
+ {
+ variableFilters: [
+ {
+ input: {
+ initial: {
+ groupBy: { propertyDefinitionId: 'status-def' },
+ },
+ },
+ },
+ ],
+ }
);
expect(result).toHaveLength(2);
@@ -61,7 +81,11 @@ describe('typed generated query inspection', () => {
// @ts-expect-error Lists cannot be traversed by v1 inspection paths.
selected.field('bins').field('length');
- const results = await inspect(host, selected);
+ const results = await inspect(host, selected, {
+ variableFilters: [{ input: { initial: { limit: 20 } } }],
+ });
+ // @ts-expect-error Filters are typed from the generated operation variables.
+ inspect(host, selected, { variableFilters: [{ missing: true }] });
expectTypeOf(
results[0]!.variables
).toEqualTypeOf<GroupSoupMembershipQueryVariables>();
diff --git a/apps/web/src/lib/graphql-cache/exchange/inspection.ts b/apps/web/src/lib/graphql-cache/exchange/inspection.ts
index 66321671c0..891292010b 100644
--- a/apps/web/src/lib/graphql-cache/exchange/inspection.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/inspection.ts
@@ -1,15 +1,16 @@
/**
* Generated-operation cache inspection.
*
- * Callers select one response field without supplying variables. Cache-core
- * discovers every cached argument variant and returns generated variables
- * plus the selected effective value when the complete query is available.
+ * Callers select one response field without supplying concrete variables.
+ * Cache-core discovers cached argument variants, filters them before
+ * materialization when requested, and returns generated variables plus the
+ * selected effective value when the complete query is available.
*/
import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
import { type AnyVariables, stringifyDocument } from '@urql/core';
import type { CacheHost } from '../host/types';
-import type { CachedQueryInstanceWire } from '../protocol';
+import type { CachedQueryInstanceWire, QueryVariableFilter } from '../protocol';
import {
documentOperationName,
type ObjectFieldKey,
@@ -47,6 +48,19 @@ export type CachedSelection<TValue, TVariables> = {
value?: TValue;
};
+/** Recursive partial match over generated operation variables. */
+export type InspectionVariableFilter<T> = T extends readonly unknown[]
+ ? T
+ : T extends object
+ ? { [K in keyof T]?: InspectionVariableFilter<T[K]> }
+ : T;
+
+/** Limits which cached variants an inspection materializes. */
+export type InspectionOptions<TVariables> = {
+ /** OR-ed recursive partial matches; omitted or empty means every variant. */
+ variableFilters?: readonly InspectionVariableFilter<TVariables>[];
+};
+
function createInspectionSelection<TValue, TVariables>(
state: InspectionSelectionState
): InspectionSelection<TValue, TVariables> {
@@ -91,13 +105,14 @@ function validateInstances(value: unknown): CachedQueryInstanceWire[] {
}
/**
- * Enumerates every cached argument variant of one generated selected field.
- * Only the serialized document, operation name, and response-key path cross
- * the host boundary.
+ * Enumerates matching cached argument variants of one generated selected
+ * field. Only the serialized document, operation name, response-key path, and
+ * optional partial-variable filters cross the host boundary.
*/
export async function inspect<TValue, TVariables extends AnyVariables>(
host: CacheHost,
- selection: InspectionSelection<TValue, TVariables>
+ selection: InspectionSelection<TValue, TVariables>,
+ options: InspectionOptions<TVariables> = {}
): Promise<CachedSelection<TValue, TVariables>[]> {
if (selection.path.length === 0) {
throw new Error('cache query inspection requires a selected field');
@@ -106,6 +121,13 @@ export async function inspect<TValue, TVariables extends AnyVariables>(
query: stringifyDocument(selection.document),
operationName: documentOperationName(selection.document),
path: [...selection.path],
+ ...(options.variableFilters
+ ? {
+ variableFilters: options.variableFilters.map(
+ (filter) => filter as QueryVariableFilter
+ ),
+ }
+ : {}),
});
return validateInstances(result) as CachedSelection<TValue, TVariables>[];
}
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
index 197e66ad4e..24d58ce63e 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.test.ts
@@ -205,6 +205,9 @@ describe('createTauriCacheHost', () => {
'query Views($input: GroupedSoupInput!) { user { groupSoup(input: $input) { bins { key } } } }',
operationName: 'Views',
path: [{ field: 'user' }, { field: 'groupSoup' }],
+ variableFilters: [
+ { input: { initial: { groupBy: { field: 'PROPERTY' } } } },
+ ],
};
await expect(host.inspectQuery(request)).resolves.toEqual(instances);
diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
index 3e8b2e7162..dc568fd1c3 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -207,6 +207,7 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
query: args.query,
operationName: args.operationName,
path: args.path,
+ variableFilters: args.variableFilters,
}
);
},
diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.ts
index a6da384cee..52cd3729f7 100644
--- a/apps/web/src/lib/graphql-cache/host/types.ts
+++ b/apps/web/src/lib/graphql-cache/host/types.ts
@@ -14,6 +14,7 @@ import type {
OptimisticLinkPatchWire,
OptimisticWriteResult,
QueryRevalidationWire,
+ QueryVariableFilter,
ReadRecordsArgs,
ReadResult,
SelectedRecordPageWire,
@@ -35,6 +36,8 @@ export interface InspectQueryArgs {
operationName?: string;
/** Response-key field path from the query root. */
path: Array<{ field: string }>;
+ /** OR-ed recursive partial matches applied before result materialization. */
+ variableFilters?: QueryVariableFilter[];
}
export interface CacheWriteArgs extends Omit<CacheReadArgs, 'priority'> {
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
index 0b5d85d13c..f323102eb2 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.test.ts
@@ -68,6 +68,9 @@ describe('createWorkerCacheHost', () => {
'query Views($input: GroupedSoupInput!) { user { groupSoup(input: $input) { bins { key } } } }',
operationName: 'Views',
path: [{ field: 'user' }, { field: 'groupSoup' }],
+ variableFilters: [
+ { input: { initial: { groupBy: { field: 'PROPERTY' } } } },
+ ],
};
await expect(host.inspectQuery(request)).resolves.toEqual(instances);
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.ts b/apps/web/src/lib/graphql-cache/host/worker-host.ts
index 6d9d761ec9..9be4a564d5 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts
@@ -236,6 +236,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
query: args.query,
operationName: args.operationName,
path: args.path,
+ variableFilters: args.variableFilters,
})) as CachedQueryInstanceWire[];
},
diff --git a/apps/web/src/lib/graphql-cache/index.ts b/apps/web/src/lib/graphql-cache/index.ts
index 41826e73dc..cbbf9607cb 100644
--- a/apps/web/src/lib/graphql-cache/index.ts
+++ b/apps/web/src/lib/graphql-cache/index.ts
@@ -46,6 +46,7 @@ export type {
CacheResponse,
MutationSettlement,
OptimisticWriteResult,
+ QueryVariableFilter,
ReadRecordsArgs,
ReadResult,
RecordCursor,
diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.ts
index aa614654c5..1f0f05b9a1 100644
--- a/apps/web/src/lib/graphql-cache/protocol.ts
+++ b/apps/web/src/lib/graphql-cache/protocol.ts
@@ -14,6 +14,9 @@ export type ReadResult = { kind: 'hit'; data: unknown } | { kind: 'miss' };
/** Scheduling hint for latency-sensitive cache reads. */
export type CacheReadPriority = 'user-visible';
+/** Recursive partial-variable object used to limit query inspection work. */
+export type QueryVariableFilter = Record<string, unknown>;
+
/** Opaque exclusive cursor for deterministic normalized-record scans. */
export type RecordCursor = string;
@@ -218,6 +221,8 @@ export type CacheRequest = { id: number } & (
operationName?: string;
/** Response-key field path from the query root. */
path: Array<{ field: string }>;
+ /** OR-ed recursive partial matches applied before result materialization. */
+ variableFilters?: QueryVariableFilter[];
}
| { kind: 'teardown'; opId: string }
/** External invalidation (e.g. websocket push): evict + report ops. */
diff --git a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
index 1ef8ed2d3c..d1056bc1fc 100644
--- a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
+++ b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
@@ -55,7 +55,8 @@ export interface CacheEngine {
inspectQuery(
query: string,
operationName: string | undefined,
- path: Array<{ field: string }>
+ path: Array<{ field: string }>,
+ variableFilters: Array<Record<string, unknown>>
): Promise<CachedQueryInstanceWire[]>;
claimNextMutation(
owner: string,
diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
index 305ee9cd79..237977bc9d 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
@@ -242,7 +242,8 @@ export class CacheWorkerCore {
return await this.requireEngine().inspectQuery(
request.query,
request.operationName,
- request.path
+ request.path,
+ request.variableFilters ?? []
);
})
.with({ kind: 'claim-next-mutation' }, async (request) => {
diff --git a/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.test.ts b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.test.ts
index 93aa1fda94..5a8e13556a 100644
--- a/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.test.ts
+++ b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.test.ts
@@ -1,4 +1,4 @@
-import type { CacheHost } from '@graphql-cache/host/types';
+import type { CacheHost, InspectQueryArgs } from '@graphql-cache/host/types';
import { describe, expect, it, vi } from 'vitest';
import { registerGroupedSoupContinuation } from './graphql-operation-registry';
import { buildOptimisticGroupedPropertyUpdates } from './graphql-optimistic';
@@ -30,7 +30,7 @@ function host(args?: {
continuation?: boolean;
initialContainsItem?: boolean;
miss?: boolean;
- onInspect?: () => void;
+ onInspect?: (request: InspectQueryArgs) => void;
sourceKey?: string;
typename?: 'GraphqlSoupCall' | 'GraphqlSoupDocument';
}): CacheHost {
@@ -97,8 +97,8 @@ function host(args?: {
return {
clientId: 'test',
- async inspectQuery() {
- args?.onInspect?.();
+ async inspectQuery(request: InspectQueryArgs) {
+ args?.onInspect?.(request);
return instances;
},
} as unknown as CacheHost;
@@ -106,8 +106,9 @@ function host(args?: {
describe('buildOptimisticGroupedPropertyUpdates', () => {
it('builds source removal then destination prepend for a status move', async () => {
+ const onInspect = vi.fn();
const result = await buildOptimisticGroupedPropertyUpdates({
- host: host({ includeUnrelated: true }),
+ host: host({ includeUnrelated: true, onInspect }),
entityId: 'task-1',
propertyDefinitionId: 'status-def',
oldGroupKeys: ['in-progress'],
@@ -136,6 +137,32 @@ describe('buildOptimisticGroupedPropertyUpdates', () => {
],
]);
expect(result.revalidations).toHaveLength(1);
+ expect(onInspect).toHaveBeenCalledWith(
+ expect.objectContaining({
+ variableFilters: [
+ {
+ input: {
+ initial: {
+ groupBy: {
+ field: 'PROPERTY',
+ propertyDefinitionId: 'status-def',
+ },
+ },
+ },
+ },
+ {
+ input: {
+ continuation: {
+ groupBy: {
+ field: 'PROPERTY',
+ propertyDefinitionId: 'status-def',
+ },
+ },
+ },
+ },
+ ],
+ })
+ );
});
it('derives the normalized key from the inspected typename and id', async () => {
diff --git a/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.ts b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.ts
index 852338ae44..fe55732e75 100644
--- a/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.ts
+++ b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.ts
@@ -101,9 +101,22 @@ export async function buildOptimisticGroupedPropertyUpdates(
return { updates: [], revalidations: [] };
}
+ const relevantGroupBy = {
+ field: 'PROPERTY' as const,
+ propertyDefinitionId: args.propertyDefinitionId,
+ };
const cachedViews = await inspect(
args.host,
- selectAll(GroupSoupMembershipDocument).field('user').field('groupSoup')
+ selectAll(GroupSoupMembershipDocument).field('user').field('groupSoup'),
+ {
+ // Filter inside cache-core before each variant is denormalized. Without
+ // this, editing one property reads every cached grouped view first and
+ // discards unrelated groupings only after crossing the worker boundary.
+ variableFilters: [
+ { input: { initial: { groupBy: relevantGroupBy } } },
+ { input: { continuation: { groupBy: relevantGroupBy } } },
+ ],
+ }
);
const relevantViews = cachedViews.filter(({ variables }) =>
isRelevantPropertyGrouping(variables.input, args.propertyDefinitionId)
diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
index 6e79fb2f62..3921ba4846 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
@@ -182,12 +182,14 @@ pub async fn graphql_cache_inspect_query(
query: String,
operation_name: Option<String>,
path: Vec<InspectionPathSegment>,
+ variable_filters: Option<Vec<serde_json::Map<String, serde_json::Value>>>,
) -> Result<Vec<CachedQueryInstance>, String> {
engine_handle(&state)?
.inspect_query(
query,
operation_name,
path.into_iter().map(|segment| segment.field).collect(),
+ variable_filters.unwrap_or_default(),
)
.await
}
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
index 1e3edf7dde..b5a41bfbbd 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
@@ -232,6 +232,7 @@ impl EngineHandle {
query: String,
operation_name: Option<String>,
path: Vec<String>,
+ variable_filters: Vec<serde_json::Map<String, serde_json::Value>>,
) -> Result<Vec<CachedQueryInstance>, String> {
self.inner
.lock()
@@ -241,6 +242,7 @@ impl EngineHandle {
query,
operation_name,
path,
+ variable_filters,
})
.await
.map_err(|error| error.to_string())
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
index c61feebceb..2622167b0e 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
@@ -148,6 +148,7 @@ fn query_inspection_serializes_generated_variables_and_value() {
QUERY.to_string(),
Some("Soup".to_string()),
vec!["user".to_string(), "soup".to_string()],
+ Vec::new(),
))
.unwrap();
assert_eq!(instances.len(), 1);
diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rs
index 5fea5ce35f..6e52851e79 100644
--- a/crates/client/cache-core/src/engine.rs
+++ b/crates/client/cache-core/src/engine.rs
@@ -13,8 +13,8 @@ use crate::link_patch::{
};
use crate::normalize::{NormalizeError, RecordUpdates, normalize};
use crate::query_inspection::{
- CachedQueryInstance, OwnerResolution, QueryInspection, QueryInspectionError, prepare,
- recover_variants, resolve_owner, selected_result_value,
+ CachedQueryInstance, OwnerResolution, QueryInspection, QueryInspectionError,
+ matches_variable_filters, prepare, recover_variants, resolve_owner, selected_result_value,
};
use crate::queue::{
ClaimedMutation, MutationClaimRequest, MutationClaimToken, MutationId, MutationRequest,
@@ -1123,6 +1123,9 @@ impl<S: Storage> Engine<S> {
let variables = recover_variants(&owner, &prepared)?;
let mut instances = Vec::with_capacity(variables.len());
for variables in variables {
+ if !matches_variable_filters(&variables, &inspection.variable_filters) {
+ continue;
+ }
let value = match self
.read_query(
None,
diff --git a/crates/client/cache-core/src/query_inspection.rs b/crates/client/cache-core/src/query_inspection.rs
index 23483cab41..d43c16c322 100644
--- a/crates/client/cache-core/src/query_inspection.rs
+++ b/crates/client/cache-core/src/query_inspection.rs
@@ -31,6 +31,9 @@ pub struct QueryInspection {
pub operation_name: Option<String>,
/// Field-only response-key path beginning at the query root.
pub path: Vec<String>,
+ /// Recursive partial-variable filters. A variant is materialized when it
+ /// matches any filter; an empty list materializes every cached variant.
+ pub variable_filters: Vec<serde_json::Map<String, Json>>,
}
/// One cached argument variant reconstructed as generated query variables.
@@ -280,6 +283,38 @@ pub(crate) fn recover_variants(
Ok(unique.into_values().collect())
}
+/// Returns whether one recovered variable set should be materialized.
+///
+/// Filter objects use recursive partial-object matching and OR semantics. A
+/// scalar or array leaf must equal the cached value exactly.
+pub(crate) fn matches_variable_filters(
+ variables: &serde_json::Map<String, Json>,
+ filters: &[serde_json::Map<String, Json>],
+) -> bool {
+ filters.is_empty()
+ || filters
+ .iter()
+ .any(|filter| partial_object_match(variables, filter))
+}
+
+fn partial_object_match(
+ value: &serde_json::Map<String, Json>,
+ filter: &serde_json::Map<String, Json>,
+) -> bool {
+ filter.iter().all(|(key, expected)| {
+ value
+ .get(key)
+ .is_some_and(|actual| partial_json_match(actual, expected))
+ })
+}
+
+fn partial_json_match(actual: &Json, expected: &Json) -> bool {
+ match (actual, expected) {
+ (Json::Object(actual), Json::Object(expected)) => partial_object_match(actual, expected),
+ _ => actual == expected,
+ }
+}
+
fn parse_stored_arguments(
storage_key: &str,
field_name: &str,
diff --git a/crates/client/cache-core/src/query_inspection/test.rs b/crates/client/cache-core/src/query_inspection/test.rs
index ba15abe83b..9b096e026a 100644
--- a/crates/client/cache-core/src/query_inspection/test.rs
+++ b/crates/client/cache-core/src/query_inspection/test.rs
@@ -29,3 +29,61 @@ fn concrete_union_member_outside_selected_fragment_is_absent() {
assert!(matches!(result, OwnerResolution::Absent));
}
+
+#[test]
+fn variable_filters_match_recursive_partial_objects_with_or_semantics() {
+ let Json::Object(variables) = serde_json::json!({
+ "input": {
+ "continuation": {
+ "groupBy": {
+ "field": "PROPERTY",
+ "propertyDefinitionId": "status-def"
+ },
+ "groupKey": "in-progress",
+ "cursor": "cursor-1"
+ }
+ }
+ }) else {
+ unreachable!()
+ };
+ let Json::Object(unrelated) = serde_json::json!({
+ "input": {"initial": {"groupBy": {"field": "PROPERTY"}}}
+ }) else {
+ unreachable!()
+ };
+ let Json::Object(relevant) = serde_json::json!({
+ "input": {"continuation": {"groupBy": {
+ "field": "PROPERTY",
+ "propertyDefinitionId": "status-def"
+ }}}
+ }) else {
+ unreachable!()
+ };
+
+ assert!(matches_variable_filters(&variables, &[]));
+ assert!(matches_variable_filters(&variables, &[unrelated, relevant]));
+}
+
+#[test]
+fn variable_filters_reject_different_or_missing_nested_values() {
+ let Json::Object(variables) = serde_json::json!({
+ "input": {"initial": {"groupBy": {
+ "field": "PROPERTY",
+ "propertyDefinitionId": "status-def"
+ }}}
+ }) else {
+ unreachable!()
+ };
+ let Json::Object(different) = serde_json::json!({
+ "input": {"initial": {"groupBy": {"propertyDefinitionId": "priority-def"}}}
+ }) else {
+ unreachable!()
+ };
+ let Json::Object(missing) = serde_json::json!({
+ "input": {"continuation": {"groupBy": {"propertyDefinitionId": "status-def"}}}
+ }) else {
+ unreachable!()
+ };
+
+ assert!(!matches_variable_filters(&variables, &[different, missing]));
+}
diff --git a/crates/client/cache-core/tests/query_inspection.rs b/crates/client/cache-core/tests/query_inspection.rs
index c3d4e57520..c74b09a04d 100644
--- a/crates/client/cache-core/tests/query_inspection.rs
+++ b/crates/client/cache-core/tests/query_inspection.rs
@@ -62,6 +62,7 @@ fn inspection(query: &str, path: &[&str]) -> QueryInspection {
query: query.to_string(),
operation_name: Some("GroupViews".to_string()),
path: path.iter().map(|part| (*part).to_string()).collect(),
+ variable_filters: Vec::new(),
}
}
@@ -149,6 +150,70 @@ fn enumerates_variants_aliases_and_misses_in_canonical_order() {
});
}
+#[test]
+fn materializes_only_variants_matching_recursive_variable_filters() {
+ block_on(async {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ let status_initial = initial(20);
+ let status_continuation = continuation("cursor-1");
+ let priority_initial = object(json!({"input": {"initial": {
+ "groupBy": {"field": "PROPERTY", "propertyDefinitionId": "priority-def"},
+ "limit": 20
+ }}}));
+ write_group(
+ &mut engine,
+ GROUP_QUERY,
+ &status_initial,
+ &page("task-1", None),
+ )
+ .await;
+ write_group(
+ &mut engine,
+ GROUP_QUERY,
+ &status_continuation,
+ &page("task-2", None),
+ )
+ .await;
+ write_group(
+ &mut engine,
+ GROUP_QUERY,
+ &priority_initial,
+ &page("task-3", None),
+ )
+ .await;
+
+ let mut filtered = inspection(GROUP_QUERY, &["user", "groupSoup"]);
+ filtered.variable_filters = vec![
+ object(json!({"input": {"initial": {"groupBy": {
+ "field": "PROPERTY",
+ "propertyDefinitionId": "status-def"
+ }}}})),
+ object(json!({"input": {"continuation": {"groupBy": {
+ "field": "PROPERTY",
+ "propertyDefinitionId": "status-def"
+ }}}})),
+ ];
+ let results = engine.inspect_query(&filtered).await.unwrap();
+
+ assert_eq!(results.len(), 2);
+ assert!(
+ results
+ .iter()
+ .any(|result| result.variables == status_initial)
+ );
+ assert!(
+ results
+ .iter()
+ .any(|result| result.variables == status_continuation)
+ );
+ assert!(
+ results
+ .iter()
+ .all(|result| result.variables != priority_initial)
+ );
+ });
+}
+
#[test]
fn recovers_nested_constants_lists_and_repeated_variables() {
block_on(async {
@@ -322,6 +387,7 @@ fn rejects_invalid_entrypoints_paths_variables_and_limits() {
query: "mutation GroupViews { renameFile(input: {}) { id } }".into(),
operation_name: Some("GroupViews".into()),
path: vec!["renameFile".into()],
+ variable_filters: Vec::new(),
};
assert!(matches!(
engine.inspect_query(&mutation).await.unwrap_err(),
diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rs
index c75e3b20c9..333f3de8fe 100644
--- a/crates/client/cache-wasm/src/shell.rs
+++ b/crates/client/cache-wasm/src/shell.rs
@@ -376,15 +376,19 @@ impl CacheEngine {
query: String,
operation_name: Option<String>,
path: JsValue,
+ variable_filters: JsValue,
) -> js_sys::Promise {
let engine = self.engine.clone();
future_to_promise(async move {
let path: Vec<JsInspectionPathSegment> =
serde_wasm_bindgen::from_value(path).map_err(err_js)?;
+ let variable_filters: Vec<serde_json::Map<String, serde_json::Value>> =
+ serde_wasm_bindgen::from_value(variable_filters).map_err(err_js)?;
let inspection = QueryInspection {
query,
operation_name,
path: path.into_iter().map(|segment| segment.field).collect(),
+ variable_filters,
};
let instances = engine
.lock()
diff --git a/crates/client/cache-wasm/tests/web.rs b/crates/client/cache-wasm/tests/web.rs
index 38b7495529..e909e82410 100644
--- a/crates/client/cache-wasm/tests/web.rs
+++ b/crates/client/cache-wasm/tests/web.rs
@@ -97,6 +97,7 @@ async fn write_then_read_through_js_boundary() {
QUERY.into(),
Some("Soup".into()),
js(serde_json::json!([{"field": "user"}, {"field": "soup"}])),
+ js(serde_json::json!([])),
))
.await
.unwrap();