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/select and update gql cache (#4917)

Sean Aye591efaa1aa8c
diff --git a/Cargo.lock b/Cargo.lock
index 1529d966ce..d5e9416990 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2284,7 +2284,7 @@ dependencies = [
[[package]]
name = "cache-wasm"
-version = "0.1.0"
+version = "0.2.0"
dependencies = [
"async-lock",
"cache-core",
diff --git a/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts b/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
index 0f0ece3b98..f14bdb4bad 100644
--- a/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
+++ b/apps/web/src/features/next-soup/soup-view/create-grouped-soup-queries.ts
@@ -3,11 +3,15 @@ import { throwOnErr } from '@core/util/result';
import type { EntityData } from '@entity';
import { useQueryClient } from '@queries/client';
import { groupedCacheVersion } from '@queries/soup/cache';
-import { makeGraphqlGroupedSoupContinuationInput } from '@queries/soup/graphql-ast';
+import {
+ makeGraphqlGroupedSoupContinuationInput,
+ makeGraphqlGroupedSoupInput,
+} from '@queries/soup/graphql-ast';
import {
parseGroupMeta,
serializeGroupByField,
} from '@queries/soup/grouped/api';
+import { registerGroupedSoupContinuation } from '@queries/soup/grouped/graphql-operation-registry';
import type { GroupByField, GroupMeta } from '@queries/soup/grouped/types';
import type {
SoupApiItemFilter,
@@ -149,13 +153,20 @@ export function createGroupedSoupQueries(args: CreateGroupedSoupQueriesArgs) {
}
if (args.transport() === 'graphql') {
- const response = await fetchGraphqlGroupedSoup(
- makeGraphqlGroupedSoupContinuationInput({
+ const continuationInput = makeGraphqlGroupedSoupContinuationInput({
+ groupBy: field,
+ groupKey: group.key,
+ cursor: ctx.pageParam,
+ });
+ registerGroupedSoupContinuation(
+ makeGraphqlGroupedSoupInput({
+ params: args.soupParams(),
+ body: args.soupBody(),
groupBy: field,
- groupKey: group.key,
- cursor: ctx.pageParam,
- })
+ }),
+ continuationInput
);
+ const response = await fetchGraphqlGroupedSoup(continuationInput);
const nextGroup = response.groups.find(
(candidate) => candidate.key === group.key
);
diff --git a/apps/web/src/lib/graphql-cache/exchange/generated-selection.ts b/apps/web/src/lib/graphql-cache/exchange/generated-selection.ts
new file mode 100644
index 0000000000..e170b1f92e
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/exchange/generated-selection.ts
@@ -0,0 +1,27 @@
+import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
+import type { AnyVariables } from '@urql/core';
+import { Kind, type OperationDefinitionNode } from 'graphql';
+
+/** Removes nullable wrappers while traversing generated operation results. */
+export type Present<T> = Exclude<T, null | undefined>;
+/** String response keys generated for an operation result object. */
+export type StringKey<T> = Extract<keyof T, string>;
+/** Fields available to a field-only generated result selection. */
+export type ObjectFieldKey<T> =
+ Present<T> extends readonly unknown[]
+ ? never
+ : Present<T> extends object
+ ? StringKey<Present<T>>
+ : never;
+
+/** Extracts the selected operation name transported with generated queries. */
+export function documentOperationName(
+ document: TypedDocumentNode<unknown, AnyVariables>
+): string | undefined {
+ for (const definition of document.definitions) {
+ if (definition.kind === Kind.OPERATION_DEFINITION) {
+ return (definition as OperationDefinitionNode).name?.value;
+ }
+ }
+ return undefined;
+}
diff --git a/apps/web/src/lib/graphql-cache/exchange/inspection.test.ts b/apps/web/src/lib/graphql-cache/exchange/inspection.test.ts
new file mode 100644
index 0000000000..b310d39a38
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/exchange/inspection.test.ts
@@ -0,0 +1,104 @@
+import {
+ GroupSoupMembershipDocument,
+ type GroupSoupMembershipQuery,
+ type GroupSoupMembershipQueryVariables,
+} from '@service-storage/graphql/generated/graphql';
+import { describe, expect, expectTypeOf, it, vi } from 'vitest';
+import { createNoopCacheHost } from '../host/noop-host';
+import type { CacheHost } from '../host/types';
+import { inspect, selectAll } from './inspection';
+
+const input = {
+ initial: {
+ groupBy: {
+ field: 'PROPERTY' as const,
+ propertyDefinitionId: 'status-def',
+ },
+ limit: 20,
+ },
+};
+
+describe('typed generated query inspection', () => {
+ it('serializes only the document, operation name, and field path', async () => {
+ const inspectQuery = async (request: unknown) => {
+ expect(request).toMatchObject({
+ operationName: 'GroupSoupMembership',
+ path: [{ field: 'user' }, { field: 'groupSoup' }],
+ });
+ expect(request).not.toHaveProperty('variables');
+ expect(request).not.toHaveProperty('entityKey');
+ return [
+ {
+ variables: { input },
+ value: { bins: [{ key: 'status', items: [] }] },
+ },
+ {
+ variables: {
+ input: { ...input, initial: { ...input.initial, limit: 50 } },
+ },
+ },
+ ];
+ };
+ const host = { inspectQuery } as unknown as CacheHost;
+
+ const result = await inspect(
+ host,
+ selectAll(GroupSoupMembershipDocument).field('user').field('groupSoup')
+ );
+
+ expect(result).toHaveLength(2);
+ expect(result[0]?.variables).toEqual({ input });
+ expect(result[1]).not.toHaveProperty('value');
+ });
+
+ it('infers generated response and variable types', () => {
+ const typeAssertions = async (host: CacheHost) => {
+ const root = selectAll(GroupSoupMembershipDocument);
+ // @ts-expect-error `missing` is not selected by the generated query.
+ root.field('missing');
+
+ const selected = root.field('user').field('groupSoup');
+ // @ts-expect-error Lists cannot be traversed by v1 inspection paths.
+ selected.field('bins').field('length');
+
+ const results = await inspect(host, selected);
+ expectTypeOf(
+ results[0]!.variables
+ ).toEqualTypeOf<GroupSoupMembershipQueryVariables>();
+ expectTypeOf(results[0]!.value).toEqualTypeOf<
+ GroupSoupMembershipQuery['user']['groupSoup'] | undefined
+ >();
+ // @ts-expect-error Variables are inferred, not an arbitrary record.
+ results[0]!.variables.missing;
+ // @ts-expect-error The selected value is groupSoup, not the query root.
+ results[0]!.value?.user;
+ };
+
+ expect(typeAssertions).toBeTypeOf('function');
+ });
+
+ it('returns no selections through the no-op host', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const result = await inspect(
+ createNoopCacheHost('test'),
+ selectAll(GroupSoupMembershipDocument).field('user').field('groupSoup')
+ );
+ expect(result).toEqual([]);
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
+ it('rejects malformed host results', async () => {
+ const host = {
+ inspectQuery: async () => [{ variables: null }],
+ } as unknown as CacheHost;
+ await expect(
+ inspect(
+ host,
+ selectAll(GroupSoupMembershipDocument).field('user').field('groupSoup')
+ )
+ ).rejects.toThrow('invalid cache query inspection instance');
+ });
+});
diff --git a/apps/web/src/lib/graphql-cache/exchange/inspection.ts b/apps/web/src/lib/graphql-cache/exchange/inspection.ts
new file mode 100644
index 0000000000..66321671c0
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/exchange/inspection.ts
@@ -0,0 +1,111 @@
+/**
+ * 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.
+ */
+
+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 {
+ documentOperationName,
+ type ObjectFieldKey,
+ type Present,
+} from './generated-selection';
+
+declare const inspectionValueType: unique symbol;
+declare const inspectionVariablesType: unique symbol;
+
+type InspectionSelectionState = {
+ readonly document: TypedDocumentNode<unknown, AnyVariables>;
+ readonly path: readonly { field: string }[];
+};
+
+/** A field-only path generated from an operation result and variables type. */
+export type InspectionSelection<TValue, TVariables> =
+ InspectionSelectionState & {
+ /** Phantom selected value type retained across fluent field operations. */
+ readonly [inspectionValueType]: TValue;
+ /** Phantom generated variables type returned by inspection. */
+ readonly [inspectionVariablesType]: TVariables;
+ } & (ObjectFieldKey<TValue> extends never
+ ? object
+ : {
+ /** Selects a generated response field on the current object. */
+ field<K extends ObjectFieldKey<TValue>>(
+ field: K
+ ): InspectionSelection<Present<TValue>[K], TVariables>;
+ });
+
+/** One cached generated operation-variable instance and selected value. */
+export type CachedSelection<TValue, TVariables> = {
+ variables: TVariables;
+ /** Absent when the field exists but the complete generated query is a miss. */
+ value?: TValue;
+};
+
+function createInspectionSelection<TValue, TVariables>(
+ state: InspectionSelectionState
+): InspectionSelection<TValue, TVariables> {
+ return {
+ ...state,
+ field(field: string) {
+ return createInspectionSelection({
+ ...state,
+ path: [...state.path, { field }],
+ });
+ },
+ } as unknown as InspectionSelection<TValue, TVariables>;
+}
+
+/** Starts a generated field-only selection without concrete variables. */
+export function selectAll<TData, TVariables extends AnyVariables>(
+ document: TypedDocumentNode<TData, TVariables>
+): InspectionSelection<TData, TVariables> {
+ return createInspectionSelection<TData, TVariables>({
+ document: document as TypedDocumentNode<unknown, AnyVariables>,
+ path: [],
+ });
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function validateInstances(value: unknown): CachedQueryInstanceWire[] {
+ if (!Array.isArray(value)) {
+ throw new Error('invalid cache query inspection result');
+ }
+ return value.map((instance) => {
+ if (!isRecord(instance) || !isRecord(instance.variables)) {
+ throw new Error('invalid cache query inspection instance');
+ }
+ return {
+ variables: instance.variables,
+ ...('value' in instance ? { value: instance.value } : {}),
+ };
+ });
+}
+
+/**
+ * Enumerates every cached argument variant of one generated selected field.
+ * Only the serialized document, operation name, and response-key path cross
+ * the host boundary.
+ */
+export async function inspect<TValue, TVariables extends AnyVariables>(
+ host: CacheHost,
+ selection: InspectionSelection<TValue, TVariables>
+): Promise<CachedSelection<TValue, TVariables>[]> {
+ if (selection.path.length === 0) {
+ throw new Error('cache query inspection requires a selected field');
+ }
+ const result: unknown = await host.inspectQuery({
+ query: stringifyDocument(selection.document),
+ operationName: documentOperationName(selection.document),
+ path: [...selection.path],
+ });
+ return validateInstances(result) as CachedSelection<TValue, TVariables>[];
+}
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
index 9d068634e1..04ae3375b6 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
@@ -43,7 +43,11 @@ const MUTATION = gql`
type FakeHost = CacheHost & {
reads: Array<{ opKey?: number; query: string; variables?: object }>;
writes: Array<{ opKey?: number; data: unknown; identity?: string }>;
- begins: Array<{ query: string; data: unknown }>;
+ begins: Array<{
+ query: string;
+ data: unknown;
+ linkPatches?: unknown[];
+ }>;
commits: Array<{ transactionId: string; query: string; data: unknown }>;
rollbacks: string[];
defers: Array<{ transactionId: string; error: string }>;
@@ -104,7 +108,11 @@ function makeFakeHost(): FakeHost {
return { changed: [], affectedOps: [], reset: false };
},
async beginOptimisticWrite(args): Promise<OptimisticWriteResult> {
- host.begins.push({ query: args.query, data: args.data });
+ host.begins.push({
+ query: args.query,
+ data: args.data,
+ linkPatches: args.linkPatches,
+ });
const transactionId = `txn-${host.begins.length}`;
queue.push({ transactionId, args, attemptCount: 0, leased: false });
return {
@@ -114,6 +122,9 @@ function makeFakeHost(): FakeHost {
reset: false,
};
},
+ async inspectQuery() {
+ return [];
+ },
async claimNextMutation(_owner): Promise<ClaimedMutation | undefined> {
const head = queue[0];
if (!head || head.leased) return undefined;
@@ -216,6 +227,9 @@ function harness(
const ops = makeSubject<Operation>();
const client = {
reexecuteOperation: vi.fn(),
+ query: vi.fn((_query, _variables, _context) => ({
+ toPromise: () => Promise.resolve({ data: {} }),
+ })),
mutation: vi.fn((query, variables, context) => ({
toPromise: () => {
const request = createRequest(query, variables);
@@ -519,6 +533,79 @@ describe('normalizedCacheExchange', () => {
expect(results[0]?.data).toEqual({ from: 'network' });
});
+ it('passes declarative link patches into the durable begin call', async () => {
+ const base = makeMutationOp(1, optimistic);
+ const patch = {
+ query: 'query Group { user { groupSoup { bins { items { id } } } } }',
+ operationName: 'Group',
+ variablesJson: '{}',
+ path: [
+ { field: 'user' },
+ { field: 'groupSoup' },
+ { field: 'bins' },
+ { field: 'items' },
+ ],
+ operation: {
+ kind: 'remove' as const,
+ entityKey: 'GraphqlSoupItem:task-1',
+ },
+ };
+ const op = makeOperation(base.kind, base, {
+ ...base.context,
+ normalizedCacheOptimistic: {
+ optimisticResponse: optimistic,
+ linkPatches: [patch],
+ revalidations: [],
+ },
+ });
+ const { ops } = harness(host);
+ ops.next(op);
+ await tick();
+
+ expect(host.begins[0]?.linkPatches).toEqual([patch]);
+ });
+
+ it('falls back to property-only optimism when patched setup becomes stale', async () => {
+ const base = makeMutationOp(1, optimistic);
+ const op = makeOperation(base.kind, base, {
+ ...base.context,
+ normalizedCacheOptimistic: {
+ optimisticResponse: optimistic,
+ linkPatches: [
+ {
+ query:
+ 'query Group { user { groupSoup { bins { items { id } } } } }',
+ operationName: 'Group',
+ variablesJson: '{}',
+ path: [
+ { field: 'user' },
+ { field: 'groupSoup' },
+ { field: 'bins' },
+ ],
+ operation: {
+ kind: 'remove',
+ entityKey: 'GraphqlSoupItem:task-1',
+ },
+ },
+ ],
+ revalidations: [],
+ },
+ });
+ const begin = host.beginOptimisticWrite.bind(host);
+ host.beginOptimisticWrite = async (args) => {
+ if (args.linkPatches?.length) throw new Error('stale bin');
+ return begin(args);
+ };
+ const onCacheError = vi.fn();
+ const { ops } = harness(host, undefined, { onCacheError });
+ ops.next(op);
+ await tick();
+
+ expect(onCacheError).toHaveBeenCalledOnce();
+ expect(host.begins[0]?.linkPatches).toEqual([]);
+ expect(host.commits).toHaveLength(1);
+ });
+
it('bounds queued network attempts to one minute', async () => {
const timeoutSignal = new AbortController().signal;
const existingSignal = new AbortController().signal;
@@ -573,6 +660,28 @@ describe('normalizedCacheExchange', () => {
expect(host.writes).toHaveLength(0);
});
+ it('fires commit revalidations with network-only policy', async () => {
+ const commit = host.commitOptimisticWrite.bind(host);
+ host.commitOptimisticWrite = async (transactionId, claim, args) => ({
+ ...(await commit(transactionId, claim, args)),
+ revalidations: [
+ {
+ query: stringifyDocument(QUERY),
+ operationName: 'Soup',
+ variablesJson: '{"input":{"limit":2}}',
+ },
+ ],
+ });
+ const { ops, client } = harness(host);
+ ops.next(makeMutationOp(1, optimistic));
+ await tick();
+
+ expect(vi.mocked(client.query)).toHaveBeenCalledOnce();
+ expect(vi.mocked(client.query).mock.calls[0]?.[2]).toEqual({
+ requestPolicy: 'network-only',
+ });
+ });
+
it('rolls back on a GraphQL error result', async () => {
const error = new CombinedError({ graphQLErrors: ['nope'] });
const { ops, results } = harness(host, (op) =>
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
index b5a96a0eb0..4f8588776f 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
@@ -56,6 +56,7 @@ import {
tap,
} from 'wonka';
import type { CacheHost } from '../host/types';
+import type { OptimisticWriteResult, QueryRevalidationWire } from '../protocol';
import { optimisticContextOf } from './optimistic';
/**
@@ -293,6 +294,37 @@ export function normalizedCacheExchange(
}
}
+ function revalidateAfterCommit(
+ revalidations: QueryRevalidationWire[],
+ mutation: Operation
+ ): void {
+ for (const revalidation of revalidations) {
+ try {
+ const variables: unknown = JSON.parse(revalidation.variablesJson);
+ if (
+ variables === null ||
+ typeof variables !== 'object' ||
+ Array.isArray(variables)
+ ) {
+ throw new Error('cache revalidation variables are not an object');
+ }
+ void client
+ .query(
+ replayDocument(revalidation.query, revalidation.operationName),
+ variables as Record<string, unknown>,
+ { requestPolicy: 'network-only' }
+ )
+ .toPromise()
+ .then((result) => {
+ if (result.error) throw result.error;
+ })
+ .catch((error) => options.onCacheError?.(error, mutation));
+ } catch (error) {
+ options.onCacheError?.(error, mutation);
+ }
+ }
+ }
+
async function readThenRoute(
op: Operation
): Promise<OperationResult | undefined> {
@@ -345,12 +377,36 @@ export function normalizedCacheExchange(
return;
}
try {
- const begin = await host.beginOptimisticWrite({
+ const args = {
query: queryText(op),
operationName: operationName(op),
variables: op.variables as Record<string, unknown> | undefined,
data: optimistic.optimisticResponse,
- });
+ linkPatches: optimistic.linkPatches,
+ revalidations: optimistic.revalidations,
+ };
+ let begin: OptimisticWriteResult;
+ try {
+ begin = await host.beginOptimisticWrite(args);
+ } catch (error) {
+ // A cached bin/page may disappear between inspect and begin. Do
+ // not expose a partial relation move: retain entity optimism and
+ // the post-success revalidation descriptors instead.
+ if (args.linkPatches.length === 0) throw error;
+ options.onCacheError?.(error, op);
+ begin = await host.beginOptimisticWrite({
+ ...args,
+ linkPatches: [],
+ revalidations: [
+ ...args.revalidations,
+ ...args.linkPatches.map((patch) => ({
+ query: patch.query,
+ operationName: patch.operationName,
+ variablesJson: patch.variablesJson,
+ })),
+ ],
+ });
+ }
liveQueuedOps.set(begin.transactionId, op);
scheduleDrain();
} catch (error) {
@@ -409,14 +465,19 @@ export function normalizedCacheExchange(
);
}
} else {
- await host.commitOptimisticWrite(attempt.transactionId, claim, {
- query: queryText(op),
- operationName: operationName(op),
- variables: op.variables as
- | Record<string, unknown>
- | undefined,
- data: result.data,
- });
+ const committed = await host.commitOptimisticWrite(
+ attempt.transactionId,
+ claim,
+ {
+ query: queryText(op),
+ operationName: operationName(op),
+ variables: op.variables as
+ | Record<string, unknown>
+ | undefined,
+ data: result.data,
+ }
+ );
+ revalidateAfterCommit(committed.revalidations ?? [], op);
}
} catch (error) {
options.onCacheError?.(error, op);
diff --git a/apps/web/src/lib/graphql-cache/exchange/optimistic.test.ts b/apps/web/src/lib/graphql-cache/exchange/optimistic.test.ts
new file mode 100644
index 0000000000..6fc84726ee
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/exchange/optimistic.test.ts
@@ -0,0 +1,71 @@
+import { GroupSoupMembershipDocument } from '@service-storage/graphql/generated/graphql';
+import { describe, expect, it } from 'vitest';
+import { prependUnique, remove, select, update } from './optimistic';
+
+const input = {
+ initial: {
+ groupBy: {
+ field: 'PROPERTY' as const,
+ propertyDefinitionId: 'status-def',
+ },
+ limit: 20,
+ },
+};
+
+function itemsIn(groupKey: string) {
+ return select(GroupSoupMembershipDocument, { input })
+ .field('user')
+ .field('groupSoup')
+ .field('bins')
+ .item('key', groupKey)
+ .field('items');
+}
+
+describe('typed optimistic graph updates', () => {
+ it('serializes a generated query entrypoint, variables, path, and diff', () => {
+ const removal = update(
+ itemsIn('in-progress'),
+ remove('GraphqlSoupItem:task-1')
+ );
+ const prepend = update(
+ itemsIn('completed'),
+ prependUnique('GraphqlSoupItem:task-1')
+ );
+
+ expect(removal.operationName).toBe('GroupSoupMembership');
+ expect(JSON.parse(removal.variablesJson)).toEqual({ input });
+ expect(removal.path).toEqual([
+ { field: 'user' },
+ { field: 'groupSoup' },
+ { field: 'bins' },
+ { listItem: { whereField: 'key', equals: 'in-progress' } },
+ { field: 'items' },
+ ]);
+ expect(removal.operation).toEqual({
+ kind: 'remove',
+ entityKey: 'GraphqlSoupItem:task-1',
+ });
+ expect(prepend.operation.kind).toBe('prependUnique');
+ });
+
+ it('uses generated operation result and variable types', () => {
+ const typeAssertions = () => {
+ // @ts-expect-error GroupSoupMembership requires an input variable.
+ select(GroupSoupMembershipDocument, {});
+
+ const root = select(GroupSoupMembershipDocument, { input });
+ // @ts-expect-error `missing` is not selected by this generated query.
+ root.field('missing');
+
+ const bins = root.field('user').field('groupSoup').field('bins');
+ // @ts-expect-error A bin has no `missing` scalar selector.
+ bins.item('missing', 'value');
+ // @ts-expect-error The generated bin key is a string.
+ bins.item('key', 123);
+ // @ts-expect-error Updates must target a generated list selection.
+ update(root.field('user'), remove('GraphqlUser:user-1'));
+ };
+
+ expect(typeAssertions).toBeTypeOf('function');
+ });
+});
diff --git a/apps/web/src/lib/graphql-cache/exchange/optimistic.ts b/apps/web/src/lib/graphql-cache/exchange/optimistic.ts
index 65da90d878..a7d1a2230c 100644
--- a/apps/web/src/lib/graphql-cache/exchange/optimistic.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/optimistic.ts
@@ -1,39 +1,169 @@
/**
- * Typed entry point for optimistic GraphQL mutations through the
- * normalized cache exchange.
+ * Typed entry point for durable optimistic GraphQL mutations.
*
- * The optimistic response rides in a private urql operation-context slot;
- * the exchange installs it as an in-memory cache layer before the mutation
- * is forwarded to the network, commits the layer with the real response on
- * success, and rolls it back on error. Construction is strongly typed
- * against the generated operation (`TData` must exactly match the mutation
- * selection), while the exchange boundary reads the slot as `unknown`.
+ * Callers describe relation changes through generated query documents. The
+ * fluent selection is compiled to a constrained serializable recipe before
+ * it crosses SharedWorker, Tauri IPC, WASM, or durable queue boundaries.
*/
import type { TypedDocumentNode } from '@graphql-typed-document-node/core';
-import type {
- AnyVariables,
- Client,
- Operation,
- OperationResult,
- OperationResultSource,
+import {
+ type AnyVariables,
+ type Client,
+ type Operation,
+ type OperationResult,
+ type OperationResultSource,
+ stringifyDocument,
} from '@urql/core';
+import type {
+ EmbeddedLinkPathSegment,
+ OptimisticLinkPatchWire,
+ QueryRevalidationWire,
+} from '../protocol';
+import {
+ documentOperationName,
+ type Present,
+ type StringKey,
+} from './generated-selection';
-/** Private operation-context field carrying the optimistic response. */
+/** Private operation-context field carrying serializable optimistic data. */
const OPTIMISTIC_MUTATION_CONTEXT_KEY = 'normalizedCacheOptimistic';
+declare const selectionType: unique symbol;
+declare const optimisticUpdateType: unique symbol;
+
+type JsonScalar = string | number | boolean | null;
+type ScalarKey<T> = {
+ [K in StringKey<T>]-?: Present<T[K]> extends JsonScalar ? K : never;
+}[StringKey<T>];
+type SelectionState = {
+ readonly document: TypedDocumentNode<unknown, AnyVariables>;
+ readonly variables: AnyVariables;
+ readonly path: readonly EmbeddedLinkPathSegment[];
+};
+
+/** A type-generated path through one query result. */
+export type Selection<T> = SelectionState & {
+ /** Phantom result type retained across fluent path operations. */
+ readonly [selectionType]: T;
+} & (Present<T> extends readonly (infer TItem)[]
+ ? {
+ /** Selects exactly one list item by one generated scalar field. */
+ item<K extends ScalarKey<Present<TItem>>>(
+ field: K,
+ equals: Present<Present<TItem>[K]>
+ ): Selection<Present<TItem>>;
+ }
+ : Present<T> extends object
+ ? {
+ /** Selects a generated response field on the current object. */
+ field<K extends StringKey<Present<T>>>(
+ field: K
+ ): Selection<Present<T>[K]>;
+ }
+ : object);
+
+/** A generated selection whose current value is a list. */
+export type ListSelection<TItem extends object> = Selection<readonly TItem[]>;
+
+/** An idempotent change to a normalized-link list. */
+export type LinkDiff =
+ | { kind: 'remove'; entityKey: string }
+ | { kind: 'prependUnique'; entityKey: string };
+
+/** Opaque serializable cache update produced only by {@link update}. */
+export type OptimisticUpdate = OptimisticLinkPatchWire & {
+ readonly [optimisticUpdateType]: true;
+};
+
+export type QueryRevalidation = {
+ document: TypedDocumentNode<unknown, AnyVariables>;
+ variables: AnyVariables;
+};
+
+export type OptimisticMutationOptions = {
+ updates?: readonly OptimisticUpdate[];
+ /** Relevant queries that cannot safely be updated still revalidate on success. */
+ revalidations?: readonly QueryRevalidation[];
+};
export type OptimisticMutationContext<TData = unknown> = {
optimisticResponse: TData;
+ linkPatches: OptimisticLinkPatchWire[];
+ revalidations: QueryRevalidationWire[];
};
+function serializeRevalidation(
+ revalidation: QueryRevalidation
+): QueryRevalidationWire {
+ return {
+ query: stringifyDocument(revalidation.document),
+ operationName: documentOperationName(revalidation.document),
+ variablesJson: JSON.stringify(revalidation.variables ?? {}),
+ };
+}
+
+function createSelection<T>(state: SelectionState): Selection<T> {
+ const selection = {
+ ...state,
+ field(field: string) {
+ return createSelection({
+ ...state,
+ path: [...state.path, { field }],
+ });
+ },
+ item(field: string, equals: JsonScalar) {
+ return createSelection({
+ ...state,
+ path: [...state.path, { listItem: { whereField: field, equals } }],
+ });
+ },
+ };
+ return selection as unknown as Selection<T>;
+}
+
/**
- * Executes `document` as a mutation whose `optimisticData` is applied to
- * the normalized cache immediately. Dependent cached queries update right
- * away; the returned source still resolves only with the real network
- * result (never the optimistic one).
- *
- * On clients without the normalized cache exchange the context slot is
- * ignored and this behaves exactly like `client.mutation`.
+ * Starts a strongly typed graph selection at a generated query operation.
+ * Variables and every subsequent path segment are inferred from the
+ * `TypedDocumentNode` generated by GraphQL Code Generator.
+ */
+export function select<TData, TVariables extends AnyVariables>(
+ document: TypedDocumentNode<TData, TVariables>,
+ variables: TVariables
+): Selection<TData> {
+ return createSelection<TData>({
+ document: document as TypedDocumentNode<unknown, AnyVariables>,
+ variables,
+ path: [],
+ });
+}
+
+/** Removes every occurrence of one normalized entity from a selected list. */
+export function remove(entityKey: string): LinkDiff {
+ return { kind: 'remove', entityKey };
+}
+
+/** Uniquely prepends one normalized entity to a selected list. */
+export function prependUnique(entityKey: string): LinkDiff {
+ return { kind: 'prependUnique', entityKey };
+}
+
+/** Compiles a generated graph selection and list diff into a durable update. */
+export function update<TItem extends object>(
+ selection: ListSelection<TItem>,
+ operation: LinkDiff
+): OptimisticUpdate {
+ return {
+ query: stringifyDocument(selection.document),
+ operationName: documentOperationName(selection.document),
+ variablesJson: JSON.stringify(selection.variables ?? {}),
+ path: [...selection.path],
+ operation,
+ } as OptimisticUpdate;
+}
+
+/**
+ * Executes `document` with one durable optimistic entity/link transaction.
+ * The source resolves only with the real network result.
*/
export function executeOptimisticMutation<
TData,
@@ -42,20 +172,20 @@ export function executeOptimisticMutation<
client: Client,
document: TypedDocumentNode<TData, TVariables>,
variables: TVariables,
- optimisticData: TData
+ optimisticData: TData,
+ options: OptimisticMutationOptions = {}
): OperationResultSource<OperationResult<TData, TVariables>> {
const context: OptimisticMutationContext<TData> = {
optimisticResponse: optimisticData,
+ linkPatches: [...(options.updates ?? [])],
+ revalidations: (options.revalidations ?? []).map(serializeRevalidation),
};
return client.mutation(document, variables, {
[OPTIMISTIC_MUTATION_CONTEXT_KEY]: context,
});
}
-/**
- * Reads the optimistic context off an operation at the exchange boundary,
- * where the payload is necessarily `unknown`.
- */
+/** Reads and defensively validates the private context at the exchange edge. */
export function optimisticContextOf(
op: Operation
): OptimisticMutationContext | undefined {
@@ -65,7 +195,18 @@ export function optimisticContextOf(
typeof value === 'object' &&
'optimisticResponse' in value
) {
- return value as OptimisticMutationContext;
+ const context = value as Partial<OptimisticMutationContext> & {
+ optimisticResponse: unknown;
+ };
+ return {
+ optimisticResponse: context.optimisticResponse,
+ linkPatches: Array.isArray(context.linkPatches)
+ ? context.linkPatches
+ : [],
+ revalidations: Array.isArray(context.revalidations)
+ ? context.revalidations
+ : [],
+ };
}
return undefined;
}
diff --git a/apps/web/src/lib/graphql-cache/host/noop-host.ts b/apps/web/src/lib/graphql-cache/host/noop-host.ts
index e3954cea56..12797c0a14 100644
--- a/apps/web/src/lib/graphql-cache/host/noop-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/noop-host.ts
@@ -31,6 +31,9 @@ export function createNoopCacheHost(reason: string): CacheHost {
async beginOptimisticWrite(): Promise<OptimisticWriteResult> {
throw new Error('normalized GraphQL cache is unavailable');
},
+ async inspectQuery() {
+ return [];
+ },
async claimNextMutation() {
return undefined;
},
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 f647075d6d..9f930c2705 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
@@ -93,11 +93,27 @@ describe('createTauriCacheHost', () => {
return Promise.resolve(null);
});
+ const patch = {
+ query: 'query { user { groupSoup { bins { items { id } } } } }',
+ variablesJson: '{}',
+ path: [
+ { field: 'user' },
+ { field: 'groupSoup' },
+ { field: 'bins' },
+ { field: 'items' },
+ ],
+ operation: { kind: 'remove' as const, entityKey: 'Thing:1' },
+ };
const begun = await host.beginOptimisticWrite({
query: 'mutation { m }',
data: { m: 1 },
+ linkPatches: [patch],
});
expect(begun).toEqual(optimistic);
+ expect(invokeMock).toHaveBeenCalledWith(
+ 'graphql_cache_begin_optimistic_write',
+ expect.objectContaining({ linkPatches: [patch] })
+ );
const claim = { owner: 'runner', generation: '2' };
await host.commitOptimisticWrite('1', claim, {
@@ -125,6 +141,33 @@ describe('createTauriCacheHost', () => {
);
});
+ it('inspects generated query variants through the native command', async () => {
+ const instances = [
+ {
+ variables: { input: { initial: { limit: 20 } } },
+ value: { bins: [] },
+ },
+ ];
+ invokeMock.mockImplementation((command: string) =>
+ Promise.resolve(
+ command === 'graphql_cache_inspect_query' ? instances : null
+ )
+ );
+ const host = createTauriCacheHost({ scope: 'scope-1' });
+ const request = {
+ query:
+ 'query Views($input: GroupedSoupInput!) { user { groupSoup(input: $input) { bins { key } } } }',
+ operationName: 'Views',
+ path: [{ field: 'user' }, { field: 'groupSoup' }],
+ };
+
+ await expect(host.inspectQuery(request)).resolves.toEqual(instances);
+ expect(invokeMock).toHaveBeenCalledWith(
+ 'graphql_cache_inspect_query',
+ request
+ );
+ });
+
it('delivers only own-client op keys from the broadcast event', async () => {
const host = createTauriCacheHost({ scope: 'scope-1' });
const seen: number[][] = [];
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 f164569e32..64849381d5 100644
--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts
@@ -10,13 +10,20 @@
import { invoke } from '@tauri-apps/api/core';
import { listen, type UnlistenFn } from '@tauri-apps/api/event';
import type {
+ CachedQueryInstanceWire,
ClaimedMutation,
MutationClaim,
OptimisticWriteResult,
ReadResult,
WriteResult,
} from '../protocol';
-import type { CacheHost, CacheReadArgs, CacheWriteArgs } from './types';
+import type {
+ BeginOptimisticWriteArgs,
+ CacheHost,
+ CacheReadArgs,
+ CacheWriteArgs,
+ InspectQueryArgs,
+} from './types';
/** Keep in sync with `OPS_AFFECTED_EVENT` in graphql_cache_plugin. */
const OPS_AFFECTED_EVENT = 'graphql-cache://ops-affected';
@@ -120,7 +127,7 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
},
async beginOptimisticWrite(
- args: CacheWriteArgs
+ args: BeginOptimisticWriteArgs
): Promise<OptimisticWriteResult> {
await ready;
return await request<OptimisticWriteResult>(
@@ -131,11 +138,27 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {
operationName: args.operationName,
variables: args.variables,
data: args.data,
+ linkPatches: args.linkPatches,
+ revalidations: args.revalidations,
createdAtMs: Date.now(),
}
);
},
+ async inspectQuery(
+ args: InspectQueryArgs
+ ): Promise<CachedQueryInstanceWire[]> {
+ await ready;
+ return await request<CachedQueryInstanceWire[]>(
+ 'graphql_cache_inspect_query',
+ {
+ query: args.query,
+ operationName: args.operationName,
+ path: args.path,
+ }
+ );
+ },
+
async claimNextMutation(
owner: string,
nowMs: number,
diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.ts
index 2d3af1ac75..4d838b4e08 100644
--- a/apps/web/src/lib/graphql-cache/host/types.ts
+++ b/apps/web/src/lib/graphql-cache/host/types.ts
@@ -6,9 +6,12 @@
*/
import type {
+ CachedQueryInstanceWire,
ClaimedMutation,
MutationClaim,
+ OptimisticLinkPatchWire,
OptimisticWriteResult,
+ QueryRevalidationWire,
ReadResult,
WriteResult,
} from '../protocol';
@@ -21,12 +24,25 @@ export interface CacheReadArgs {
variables?: Record<string, unknown>;
}
+export interface InspectQueryArgs {
+ query: string;
+ operationName?: string;
+ /** Response-key field path from the query root. */
+ path: Array<{ field: string }>;
+}
+
export interface CacheWriteArgs extends CacheReadArgs {
data: unknown;
/** Opaque session tag; see protocol.ts `identity`. */
identity?: string;
}
+export interface BeginOptimisticWriteArgs extends CacheWriteArgs {
+ linkPatches?: OptimisticLinkPatchWire[];
+ /** Revalidations for relevant cached fields that could not be patched. */
+ revalidations?: QueryRevalidationWire[];
+}
+
export interface CacheHost {
/** Stable id of this context; used to namespace operation ids. */
readonly clientId: string;
@@ -36,7 +52,11 @@ export interface CacheHost {
readQuery(args: CacheReadArgs): Promise<ReadResult>;
writeQuery(args: CacheWriteArgs): Promise<WriteResult>;
/** Durably queues a mutation and its optimistic response. */
- beginOptimisticWrite(args: CacheWriteArgs): Promise<OptimisticWriteResult>;
+ beginOptimisticWrite(
+ args: BeginOptimisticWriteArgs
+ ): Promise<OptimisticWriteResult>;
+ /** Enumerates cached variants of one generated query field selection. */
+ inspectQuery(args: InspectQueryArgs): Promise<CachedQueryInstanceWire[]>;
/** Claims the oldest runnable mutation; later entries are never skipped. */
claimNextMutation(
owner: string,
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 8bb7ab1d0a..23b08e6b5f 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
@@ -3,6 +3,7 @@ import { createWorkerCacheHost } from './worker-host';
describe('createWorkerCacheHost', () => {
afterEach(() => {
+ vi.useRealTimers();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
@@ -28,6 +29,123 @@ describe('createWorkerCacheHost', () => {
).resolves.toEqual({ changed: [], affectedOps: [], reset: false });
});
+ it('round-trips generated query inspection through the worker protocol', async () => {
+ const requests: unknown[] = [];
+ const instances = [
+ { variables: { input: { initial: { limit: 20 } } }, value: { bins: [] } },
+ ];
+ class FakeSharedWorker {
+ port = {
+ onmessage: null as ((event: MessageEvent) => void) | null,
+ start() {},
+ close() {},
+ postMessage: (request: { id?: number; kind: string }) => {
+ requests.push(request);
+ if (request.id === undefined) return;
+ queueMicrotask(() => {
+ this.port.onmessage?.({
+ data: {
+ id: request.id,
+ ok: true,
+ result: request.kind === 'inspect-query' ? instances : null,
+ },
+ } as MessageEvent);
+ });
+ },
+ };
+ }
+ vi.stubGlobal('SharedWorker', FakeSharedWorker);
+ const host = createWorkerCacheHost({ scope: 'scope-1' });
+ const request = {
+ query:
+ 'query Views($input: GroupedSoupInput!) { user { groupSoup(input: $input) { bins { key } } } }',
+ operationName: 'Views',
+ path: [{ field: 'user' }, { field: 'groupSoup' }],
+ };
+
+ await expect(host.inspectQuery(request)).resolves.toEqual(instances);
+ expect(requests).toContainEqual(
+ expect.objectContaining({ kind: 'inspect-query', ...request })
+ );
+ host.dispose();
+ });
+
+ it('times out reads without timing out durable mutations', async () => {
+ vi.useFakeTimers();
+ const requests: Array<{ id?: number; kind: string }> = [];
+ let respond: (id: number, result: unknown) => void = () => {
+ throw new Error('worker not initialized');
+ };
+ class FakeSharedWorker {
+ port = {
+ onmessage: null as ((event: MessageEvent) => void) | null,
+ start() {},
+ close() {},
+ postMessage: (request: { id?: number; kind: string }) => {
+ requests.push(request);
+ if (request.id === undefined) return;
+ if (request.kind === 'init') {
+ queueMicrotask(() =>
+ this.port.onmessage?.({
+ data: { id: request.id, ok: true, result: null },
+ } as MessageEvent)
+ );
+ }
+ },
+ };
+
+ constructor() {
+ respond = (id, result) =>
+ this.port.onmessage?.({
+ data: { id, ok: true, result },
+ } as MessageEvent);
+ }
+ }
+ vi.stubGlobal('SharedWorker', FakeSharedWorker);
+ const host = createWorkerCacheHost({
+ scope: 'scope-1',
+ requestTimeoutMs: 10,
+ });
+
+ const readResult = expect(
+ host.readQuery({ query: 'query Read { user { id } }' })
+ ).rejects.toThrow('cache worker timeout: read');
+ const mutationResult = host.beginOptimisticWrite({
+ query: 'mutation Rename { rename { id } }',
+ data: { rename: { id: 'doc-1' } },
+ });
+ let mutationSettled = false;
+ void mutationResult.then(
+ () => {
+ mutationSettled = true;
+ },
+ () => {
+ mutationSettled = true;
+ }
+ );
+
+ await vi.advanceTimersByTimeAsync(11);
+ await readResult;
+ expect(mutationSettled).toBe(false);
+ expect(
+ requests.filter((request) => request.kind === 'begin-optimistic-write')
+ ).toHaveLength(1);
+
+ const mutationRequest = requests.find(
+ (request) => request.kind === 'begin-optimistic-write'
+ );
+ expect(mutationRequest?.id).toBeTypeOf('number');
+ const result = {
+ transactionId: '1',
+ changed: [],
+ affectedOps: [],
+ reset: false,
+ };
+ respond(mutationRequest?.id as number, result);
+ await expect(mutationResult).resolves.toEqual(result);
+ host.dispose();
+ });
+
it('falls back to no-op when SharedWorker initialization throws', () => {
vi.stubGlobal(
'SharedWorker',
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 ba72c4e57a..f6c1495ef9 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts
@@ -4,6 +4,7 @@
*/
import {
+ type CachedQueryInstanceWire,
type CacheNotice,
type CacheRequest,
type ClaimedMutation,
@@ -15,11 +16,18 @@ import {
type WriteResult,
} from '../protocol';
import { createNoopCacheHost } from './noop-host';
-import type { CacheHost, CacheReadArgs, CacheWriteArgs } from './types';
+import type {
+ BeginOptimisticWriteArgs,
+ CacheHost,
+ CacheReadArgs,
+ CacheWriteArgs,
+ InspectQueryArgs,
+} from './types';
type Pending = {
resolve: (value: unknown) => void;
reject: (error: Error) => void;
+ timer?: ReturnType<typeof setTimeout>;
};
/** `Omit` that distributes over union members. */
@@ -31,8 +39,9 @@ export interface WorkerHostOptions {
scope: string;
hotCapacity?: number;
/**
- * Per-request timeout in ms (default 10s). A hung worker rejects the
- * pending call; the exchange degrades rejected reads to the network.
+ * Read-only request timeout in ms (default 10s). A hung worker rejects
+ * cache reads; mutating requests remain pending so callers cannot retry an
+ * operation that may already have completed durably.
*/
requestTimeoutMs?: number;
}
@@ -45,10 +54,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
}
const clientId = crypto.randomUUID();
- const pending = new Map<
- number,
- Pending & { timer: ReturnType<typeof setTimeout> }
- >();
+ const pending = new Map<number, Pending>();
const affectedSubscribers = new Set<(opKeys: number[]) => void>();
const requestTimeoutMs =
options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
@@ -73,7 +79,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
const entry = pending.get(msg.id);
if (!entry) return;
pending.delete(msg.id);
- clearTimeout(entry.timer);
+ if (entry.timer !== undefined) clearTimeout(entry.timer);
if (msg.ok) {
entry.resolve(msg.result);
} else {
@@ -112,12 +118,15 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
): Promise<unknown> {
const id = nextRequestId++;
return new Promise((resolve, reject) => {
- const timer = setTimeout(() => {
- if (pending.delete(id)) {
- reject(new Error(`cache worker timeout: ${msg.kind}`));
- }
- }, requestTimeoutMs);
- pending.set(id, { resolve, reject, timer });
+ const entry: Pending = { resolve, reject };
+ if (msg.kind === 'read' || msg.kind === 'inspect-query') {
+ entry.timer = setTimeout(() => {
+ if (pending.delete(id)) {
+ reject(new Error(`cache worker timeout: ${msg.kind}`));
+ }
+ }, requestTimeoutMs);
+ }
+ pending.set(id, entry);
post({ ...msg, id } as CacheRequest);
});
}
@@ -158,7 +167,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
},
async beginOptimisticWrite(
- args: CacheWriteArgs
+ args: BeginOptimisticWriteArgs
): Promise<OptimisticWriteResult> {
await ready;
return (await request({
@@ -168,10 +177,24 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
operationName: args.operationName,
variables: args.variables,
data: args.data,
+ linkPatches: args.linkPatches,
+ revalidations: args.revalidations,
createdAtMs: Date.now(),
})) as OptimisticWriteResult;
},
+ async inspectQuery(
+ args: InspectQueryArgs
+ ): Promise<CachedQueryInstanceWire[]> {
+ await ready;
+ return (await request({
+ kind: 'inspect-query',
+ query: args.query,
+ operationName: args.operationName,
+ path: args.path,
+ })) as CachedQueryInstanceWire[];
+ },
+
async claimNextMutation(
owner: string,
nowMs: number,
diff --git a/apps/web/src/lib/graphql-cache/index.ts b/apps/web/src/lib/graphql-cache/index.ts
index 3b4ed9585e..f89629752e 100644
--- a/apps/web/src/lib/graphql-cache/index.ts
+++ b/apps/web/src/lib/graphql-cache/index.ts
@@ -3,18 +3,35 @@
* Design doc: apps/web/docs/graphql-normalized-cache-plan.md
*/
+export {
+ type CachedSelection,
+ type InspectionSelection,
+ inspect,
+ selectAll,
+} from './exchange/inspection';
export {
executeOptimisticMutation,
- type OptimisticMutationContext,
+ type LinkDiff,
+ type ListSelection,
+ type OptimisticMutationOptions,
+ type OptimisticUpdate,
+ prependUnique,
+ type QueryRevalidation,
+ remove,
+ type Selection,
+ select,
+ update,
} from './exchange/optimistic';
export { createTauriCacheHost } from './host/tauri-host';
export type {
CacheHost,
CacheReadArgs,
CacheWriteArgs,
+ InspectQueryArgs,
} from './host/types';
export { createWorkerCacheHost } from './host/worker-host';
export type {
+ CachedQueryInstanceWire,
CachePush,
CacheRequest,
CacheResponse,
diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.ts
index 956512fe92..fca0e6e492 100644
--- a/apps/web/src/lib/graphql-cache/protocol.ts
+++ b/apps/web/src/lib/graphql-cache/protocol.ts
@@ -11,6 +11,41 @@
export type ReadResult = { kind: 'hit'; data: unknown } | { kind: 'miss' };
+export type QueryRevalidationWire = {
+ query: string;
+ operationName?: string;
+ /** Canonical JSON object, kept as text in the durable queue. */
+ variablesJson: string;
+};
+
+export type EmbeddedLinkPathSegment =
+ | { field: string }
+ | {
+ listItem: {
+ whereField: string;
+ equals: string | number | boolean | null;
+ };
+ };
+
+export type OptimisticLinkPatchWire = {
+ /** Generated GraphQL operation used as the typed graph entrypoint. */
+ query: string;
+ operationName?: string;
+ /** Variables for the entrypoint operation. */
+ variablesJson: string;
+ /** Response-key path beginning at the query root. */
+ path: EmbeddedLinkPathSegment[];
+ operation:
+ | { kind: 'remove'; entityKey: string }
+ | { kind: 'prependUnique'; entityKey: string };
+};
+
+export type CachedQueryInstanceWire = {
+ variables: Record<string, unknown>;
+ /** Selected value; omitted when the reconstructed query is a cache miss. */
+ value?: unknown;
+};
+
export type WriteResult = {
/** Entity keys whose records changed. */
changed: string[];
@@ -22,6 +57,8 @@ export type WriteResult = {
* then contains every registered operation except the origin.
*/
reset: boolean;
+ /** Present on successful optimistic settlement; empty otherwise. */
+ revalidations?: QueryRevalidationWire[];
};
/**
@@ -83,6 +120,8 @@ export type CacheRequest = { id: number } & (
operationName?: string;
variables?: Record<string, unknown>;
data: unknown;
+ linkPatches?: OptimisticLinkPatchWire[];
+ revalidations?: QueryRevalidationWire[];
createdAtMs: number;
}
| {
@@ -117,6 +156,13 @@ export type CacheRequest = { id: number } & (
leaseOwner: string;
leaseGeneration: string;
}
+ | {
+ kind: 'inspect-query';
+ query: string;
+ operationName?: string;
+ /** Response-key field path from the query root. */
+ path: Array<{ field: string }>;
+ }
| { kind: 'teardown'; opId: string }
/** External invalidation (e.g. websocket push): evict + report ops. */
| { kind: 'invalidate'; keys: string[] }
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 a3184a349b..3faf21b927 100644
--- a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
+++ b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts
@@ -9,8 +9,11 @@
*/
import type {
+ CachedQueryInstanceWire,
ClaimedMutation,
+ OptimisticLinkPatchWire,
OptimisticWriteResult,
+ QueryRevalidationWire,
ReadResult,
WriteResult,
} from '../protocol';
@@ -36,8 +39,15 @@ export interface CacheEngine {
operationName: string | undefined,
variables: Record<string, unknown> | undefined,
data: unknown,
+ linkPatches: OptimisticLinkPatchWire[] | undefined,
+ revalidations: QueryRevalidationWire[] | undefined,
createdAtMs: number
): Promise<OptimisticWriteResult>;
+ inspectQuery(
+ query: string,
+ operationName: string | undefined,
+ path: Array<{ field: string }>
+ ): Promise<CachedQueryInstanceWire[]>;
claimNextMutation(
owner: string,
nowMs: number,
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 d07521c783..a07cace5ee 100644
--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts
+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts
@@ -3,6 +3,7 @@
* protocol to page ports, and fans out invalidations.
*/
+import { match } from 'ts-pattern';
import type {
CachePush,
CacheRequest,
@@ -54,12 +55,12 @@ export class CacheWorkerCore {
}
private async dispatch(request: CacheRequest): Promise<unknown> {
- switch (request.kind) {
- case 'init': {
+ return await match(request)
+ .with({ kind: 'init' }, async (request) => {
await this.init(request.scope, request.hotCapacity);
return null;
- }
- case 'read': {
+ })
+ .with({ kind: 'read' }, async (request) => {
const engine = this.requireEngine();
const result: ReadResult = await engine.readQuery(
request.opId,
@@ -68,8 +69,8 @@ export class CacheWorkerCore {
request.variables
);
return result;
- }
- case 'write': {
+ })
+ .with({ kind: 'write' }, async (request) => {
const engine = this.requireEngine();
const result = await engine.writeQuery(
request.originOpId,
@@ -81,8 +82,8 @@ export class CacheWorkerCore {
);
this.fanOut(result);
return result;
- }
- case 'begin-optimistic-write': {
+ })
+ .with({ kind: 'begin-optimistic-write' }, async (request) => {
const engine = this.requireEngine();
const result: OptimisticWriteResult = await engine.beginOptimisticWrite(
request.originOpId,
@@ -90,20 +91,29 @@ export class CacheWorkerCore {
request.operationName,
request.variables,
request.data,
+ request.linkPatches,
+ request.revalidations,
request.createdAtMs
);
this.fanOut(result);
return result;
- }
- case 'claim-next-mutation': {
+ })
+ .with({ kind: 'inspect-query' }, async (request) => {
+ return await this.requireEngine().inspectQuery(
+ request.query,
+ request.operationName,
+ request.path
+ );
+ })
+ .with({ kind: 'claim-next-mutation' }, async (request) => {
const engine = this.requireEngine();
return await engine.claimNextMutation(
request.owner,
request.nowMs,
request.leaseExpiresAtMs
);
- }
- case 'defer-optimistic-write': {
+ })
+ .with({ kind: 'defer-optimistic-write' }, async (request) => {
const engine = this.requireEngine();
await engine.deferOptimisticWrite(
request.transactionId,
@@ -113,8 +123,8 @@ export class CacheWorkerCore {
request.error
);
return null;
- }
- case 'commit-optimistic-write': {
+ })
+ .with({ kind: 'commit-optimistic-write' }, async (request) => {
const engine = this.requireEngine();
// Committing can flush settled layers into durable storage.
const result = await engine.commitOptimisticWrite(
@@ -128,8 +138,8 @@ export class CacheWorkerCore {
);
this.fanOut(result);
return result;
- }
- case 'rollback-optimistic-write': {
+ })
+ .with({ kind: 'rollback-optimistic-write' }, async (request) => {
const engine = this.requireEngine();
const result = await engine.rollbackOptimisticWrite(
request.transactionId,
@@ -138,26 +148,27 @@ export class CacheWorkerCore {
);
this.fanOut(result);
return result;
- }
- case 'invalidate': {
+ })
+ .with({ kind: 'invalidate' }, async (request) => {
const engine = this.requireEngine();
const affectedOps = await engine.invalidateKeys(request.keys);
- this.fanOut({ changed: request.keys, affectedOps, reset: false });
+ this.fanOut({
+ changed: request.keys,
+ affectedOps,
+ reset: false,
+ revalidations: [],
+ });
return affectedOps;
- }
- case 'teardown': {
+ })
+ .with({ kind: 'teardown' }, async (request) => {
await this.requireEngine().teardownOperation(request.opId);
return null;
- }
- case 'clear': {
+ })
+ .with({ kind: 'clear' }, async () => {
await this.requireEngine().clear();
return null;
- }
- default: {
- // Compile-time exhaustiveness: a new request kind fails here.
- return request satisfies never;
- }
- }
+ })
+ .exhaustive();
}
private async init(scope: string, hotCapacity?: number): Promise<void> {
diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.ts
index 45acb51ad6..a37b02a505 100644
--- a/apps/web/src/lib/queries/properties/entity.ts
+++ b/apps/web/src/lib/queries/properties/entity.ts
@@ -1,5 +1,6 @@
import { analytics } from '@app/lib/analytics';
import { toast } from '@core/component/Toast/Toast';
+import { ENABLE_GRAPHQL_SOUP } from '@core/constant/featureFlags';
import { throwOnErr } from '@core/util/result';
import {
entityPropertyFromApi,
@@ -19,6 +20,10 @@ import type { EntityType } from '../../service-clients/service-properties/genera
import type { SoupProperty } from '../../service-clients/service-storage/generated/schemas/soupProperty';
import type { SoupPropertyValue } from '../../service-clients/service-storage/generated/schemas/soupPropertyValue';
import { setEntityProperty } from '../../service-clients/service-storage/graphql-properties';
+import {
+ getGraphqlCacheHost,
+ getGraphqlSoupClient,
+} from '../../service-clients/service-storage/graphql-soup';
import { queryClient } from '../client';
import {
getSoupEntityById,
@@ -26,6 +31,10 @@ import {
optimisticUpdateSoupEntity,
type SoupTransaction,
} from '../soup/cache';
+import {
+ buildOptimisticGroupedPropertyUpdates,
+ groupedPropertyKeys,
+} from '../soup/grouped/graphql-optimistic';
import { type MutationCallbacks, withCallbacks } from '../utils';
import { buildOptimisticSetEntityProperty } from './graphql-optimistic';
import { propertiesKeys } from './keys';
@@ -491,29 +500,65 @@ export function useBulkSaveEntityPropertiesMutation(
) {
return useMutation(() => ({
mutationFn: async (vars: BulkSaveEntityPropertiesParams) => {
- await Promise.all(
- vars.properties.map((item) => {
- const propertyValue = propertyValueToApi(
- item.apiValues,
- item.property.isMultiSelect
- );
+ const save = async (
+ item: BulkSaveEntityPropertiesParams['properties'][number]
+ ) => {
+ const propertyValue = propertyValueToApi(
+ item.apiValues,
+ item.property.isMultiSelect
+ );
+ const optimisticProperty = buildOptimisticSetEntityProperty(
+ item.property,
+ item.apiValues
+ );
+ let optimisticCache;
- return setEntityProperty({
- entityType: item.entityType,
- entityId: item.entityId,
- propertyDefinitionId: getPropertyDefinitionId(item.property),
- value: propertyValue,
- // GraphQL path only: updates the normalized property record
- // referenced by soup query results. The TanStack optimistic
- // transaction below stays until soup consumers move to
- // reactive urql queries.
- optimisticProperty: buildOptimisticSetEntityProperty(
- item.property,
- item.apiValues
- ),
- });
- })
- );
+ if (ENABLE_GRAPHQL_SOUP() && isInstantiatedProperty(item.property)) {
+ // Client construction owns host selection; force it before asking
+ // for the host used by inspect-driven relation discovery.
+ getGraphqlSoupClient();
+ const host = getGraphqlCacheHost();
+ if (host) {
+ try {
+ const oldGroupKeys = groupedPropertyKeys(item.property);
+ const newGroupKeys = groupedPropertyKeys(item.apiValues);
+ optimisticCache = await buildOptimisticGroupedPropertyUpdates({
+ host,
+ entityId: item.entityId,
+ propertyDefinitionId: item.property.propertyDefinitionId,
+ oldGroupKeys: oldGroupKeys ?? [],
+ newGroupKeys: newGroupKeys ?? [],
+ revalidateOnly:
+ oldGroupKeys === undefined || newGroupKeys === undefined,
+ });
+ } catch (error) {
+ // Relation discovery is an optimization. Property writes still
+ // proceed with normalized entity optimism when cache inspection
+ // is unavailable.
+ console.warn('Failed to build grouped Soup optimism', error);
+ }
+ }
+ }
+
+ return setEntityProperty({
+ entityType: item.entityType,
+ entityId: item.entityId,
+ propertyDefinitionId: getPropertyDefinitionId(item.property),
+ value: propertyValue,
+ // The TanStack optimistic transaction below stays as a transitional
+ // render mirror until grouped Soup is a live urql subscription.
+ optimisticProperty,
+ optimisticCache,
+ });
+ };
+
+ if (ENABLE_GRAPHQL_SOUP()) {
+ // Begin each durable layer sequentially so later relation recipes see
+ // the effective result of earlier property edits.
+ for (const item of vars.properties) await save(item);
+ } else {
+ await Promise.all(vars.properties.map(save));
+ }
},
...withCallbacks<
void,
diff --git a/apps/web/src/lib/queries/soup/grouped/graphql-operation-registry.test.ts b/apps/web/src/lib/queries/soup/grouped/graphql-operation-registry.test.ts
new file mode 100644
index 0000000000..425fb1c4ef
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/grouped/graphql-operation-registry.test.ts
@@ -0,0 +1,47 @@
+import type { GroupedSoupInput } from '@service-storage/graphql/generated/graphql';
+import { describe, expect, it } from 'vitest';
+import {
+ groupedSoupInputKey,
+ registerGroupedSoupContinuation,
+} from './graphql-operation-registry';
+import { groupPagesByLogicalView } from './graphql-optimistic';
+
+describe('grouped GraphQL operation registry', () => {
+ it('groups JSON-equivalent inputs when optional fields are undefined', () => {
+ const withUndefined: GroupedSoupInput = {
+ initial: {
+ groupBy: {
+ field: 'PROPERTY',
+ propertyDefinitionId: 'status-def',
+ entityType: undefined,
+ },
+ limit: undefined,
+ },
+ };
+ const roundTripped = JSON.parse(
+ JSON.stringify(withUndefined)
+ ) as GroupedSoupInput;
+ const continuation: GroupedSoupInput = {
+ continuation: {
+ groupBy: {
+ field: 'PROPERTY',
+ propertyDefinitionId: 'status-def',
+ },
+ groupKey: 'in-progress',
+ cursor: 'undefined-regression-cursor',
+ },
+ };
+
+ expect(groupedSoupInputKey(withUndefined)).toBe(
+ groupedSoupInputKey(roundTripped)
+ );
+
+ registerGroupedSoupContinuation(withUndefined, continuation);
+ const views = groupPagesByLogicalView([
+ { input: roundTripped, bins: [] },
+ { input: continuation, bins: [] },
+ ]);
+
+ expect([...views.values()].map((pages) => pages.length)).toEqual([2]);
+ });
+});
diff --git a/apps/web/src/lib/queries/soup/grouped/graphql-operation-registry.ts b/apps/web/src/lib/queries/soup/grouped/graphql-operation-registry.ts
new file mode 100644
index 0000000000..b0344f1839
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/grouped/graphql-operation-registry.ts
@@ -0,0 +1,38 @@
+import type { GroupedSoupInput } from '@service-storage/graphql/generated/graphql';
+
+const continuationToInitial = new Map<string, string>();
+
+function canonical(value: unknown): string {
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
+ if (value !== null && typeof value === 'object') {
+ return `{${Object.entries(value as Record<string, unknown>)
+ .filter(([, item]) => item !== undefined)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`)
+ .join(',')}}`;
+ }
+ return JSON.stringify(value);
+}
+
+export function groupedSoupInputKey(input: unknown): string {
+ return canonical(input);
+}
+
+/** Associates one loaded continuation page with its initial logical view. */
+export function registerGroupedSoupContinuation(
+ initial: GroupedSoupInput,
+ continuation: GroupedSoupInput
+): void {
+ continuationToInitial.set(
+ groupedSoupInputKey(continuation),
+ groupedSoupInputKey(initial)
+ );
+}
+
+/** Returns the initial-view key for an initial or registered continuation. */
+export function groupedSoupLogicalViewKey(input: unknown): string | undefined {
+ if (input !== null && typeof input === 'object' && 'initial' in input) {
+ return groupedSoupInputKey(input);
+ }
+ return continuationToInitial.get(groupedSoupInputKey(input));
+}
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
new file mode 100644
index 0000000000..9b0f00f12a
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.test.ts
@@ -0,0 +1,238 @@
+import type { CacheHost } from '@graphql-cache/host/types';
+import { describe, expect, it, vi } from 'vitest';
+import { registerGroupedSoupContinuation } from './graphql-operation-registry';
+import { buildOptimisticGroupedPropertyUpdates } from './graphql-optimistic';
+
+const input = {
+ initial: {
+ groupBy: {
+ field: 'PROPERTY' as const,
+ propertyDefinitionId: 'status-def',
+ },
+ limit: 20,
+ },
+};
+
+const continuationInput = {
+ continuation: {
+ groupBy: {
+ field: 'PROPERTY' as const,
+ propertyDefinitionId: 'status-def',
+ },
+ groupKey: 'in-progress',
+ cursor: 'cursor-1',
+ },
+};
+
+function host(args?: {
+ destination?: boolean;
+ includeUnrelated?: boolean;
+ continuation?: boolean;
+ initialContainsItem?: boolean;
+ miss?: boolean;
+ onInspect?: () => void;
+ sourceKey?: string;
+}): CacheHost {
+ const value = (containsItem: boolean) => ({
+ bins: [
+ {
+ key: args?.sourceKey ?? 'in-progress',
+ totalCount: 1,
+ nextCursor: null,
+ items: containsItem ? [{ id: 'task-1' }] : [],
+ },
+ ...(args?.destination === false
+ ? []
+ : [
+ {
+ key: 'completed',
+ totalCount: 0,
+ nextCursor: null,
+ items: [],
+ },
+ ]),
+ ],
+ });
+ const instances: Array<{
+ variables: { input: typeof input | typeof continuationInput };
+ value?: ReturnType<typeof value>;
+ }> = [
+ {
+ variables: { input },
+ ...(args?.miss
+ ? {}
+ : { value: value(args?.initialContainsItem !== false) }),
+ },
+ ];
+ if (args?.continuation) {
+ instances.push({
+ variables: { input: continuationInput },
+ value: value(true),
+ });
+ }
+ if (args?.includeUnrelated) {
+ instances.push({
+ variables: {
+ input: {
+ initial: {
+ groupBy: {
+ field: 'PROPERTY',
+ propertyDefinitionId: 'priority-def',
+ },
+ limit: 20,
+ },
+ },
+ },
+ value: value(true),
+ });
+ }
+
+ return {
+ clientId: 'test',
+ async inspectQuery() {
+ args?.onInspect?.();
+ return instances;
+ },
+ } as unknown as CacheHost;
+}
+
+describe('buildOptimisticGroupedPropertyUpdates', () => {
+ it('builds source removal then destination prepend for a status move', async () => {
+ const result = await buildOptimisticGroupedPropertyUpdates({
+ host: host({ includeUnrelated: true }),
+ entityId: 'task-1',
+ propertyDefinitionId: 'status-def',
+ oldGroupKeys: ['in-progress'],
+ newGroupKeys: ['completed'],
+ });
+
+ expect(result.updates).toHaveLength(2);
+ expect(result.updates.map((patch) => patch.operation)).toEqual([
+ { kind: 'remove', entityKey: 'GraphqlSoupItem:task-1' },
+ { kind: 'prependUnique', entityKey: 'GraphqlSoupItem:task-1' },
+ ]);
+ expect(result.updates.map((update) => update.path)).toEqual([
+ [
+ { field: 'user' },
+ { field: 'groupSoup' },
+ { field: 'bins' },
+ { listItem: { whereField: 'key', equals: 'in-progress' } },
+ { field: 'items' },
+ ],
+ [
+ { field: 'user' },
+ { field: 'groupSoup' },
+ { field: 'bins' },
+ { listItem: { whereField: 'key', equals: 'completed' } },
+ { field: 'items' },
+ ],
+ ]);
+ expect(result.revalidations).toHaveLength(1);
+ });
+
+ it('does not make a partial move when the destination bin is absent', async () => {
+ const result = await buildOptimisticGroupedPropertyUpdates({
+ host: host({ destination: false }),
+ entityId: 'task-1',
+ propertyDefinitionId: 'status-def',
+ oldGroupKeys: ['in-progress'],
+ newGroupKeys: ['completed'],
+ });
+
+ expect(result.updates).toEqual([]);
+ expect(result.revalidations).toHaveLength(1);
+ });
+
+ it('removes from a registered continuation and prepends to its initial page', async () => {
+ registerGroupedSoupContinuation(input, continuationInput);
+ const result = await buildOptimisticGroupedPropertyUpdates({
+ host: host({ continuation: true, initialContainsItem: false }),
+ entityId: 'task-1',
+ propertyDefinitionId: 'status-def',
+ oldGroupKeys: ['in-progress'],
+ newGroupKeys: ['completed'],
+ });
+
+ expect(
+ result.updates.map(
+ (update) =>
+ (JSON.parse(update.variablesJson) as { input: unknown }).input
+ )
+ ).toEqual([continuationInput, input]);
+ expect(result.updates.map((patch) => patch.operation.kind)).toEqual([
+ 'remove',
+ 'prependUnique',
+ ]);
+ });
+
+ it('uses set differences for multi-value changes', async () => {
+ const result = await buildOptimisticGroupedPropertyUpdates({
+ host: host(),
+ entityId: 'task-1',
+ propertyDefinitionId: 'status-def',
+ oldGroupKeys: ['in-progress', 'shared'],
+ newGroupKeys: ['shared', 'completed'],
+ });
+
+ expect(result.updates.map((patch) => patch.operation.kind)).toEqual([
+ 'remove',
+ 'prependUnique',
+ ]);
+ });
+
+ it('prepends an addition-only multi-value change from an existing group', async () => {
+ const result = await buildOptimisticGroupedPropertyUpdates({
+ host: host({ sourceKey: 'shared' }),
+ entityId: 'task-1',
+ propertyDefinitionId: 'status-def',
+ oldGroupKeys: ['shared'],
+ newGroupKeys: ['shared', 'completed'],
+ });
+
+ expect(result.updates.map((patch) => patch.operation)).toEqual([
+ { kind: 'prependUnique', entityKey: 'GraphqlSoupItem:task-1' },
+ ]);
+ });
+
+ it('revalidates a relevant cached variant whose complete query is a miss', async () => {
+ const result = await buildOptimisticGroupedPropertyUpdates({
+ host: host({ miss: true }),
+ entityId: 'task-1',
+ propertyDefinitionId: 'status-def',
+ oldGroupKeys: ['in-progress'],
+ newGroupKeys: ['completed'],
+ });
+
+ expect(result.updates).toEqual([]);
+ expect(result.revalidations).toHaveLength(1);
+ expect(result.revalidations[0]?.variables).toEqual({ input });
+ });
+
+ it('skips inspection when group-key sets are equivalent', async () => {
+ const onInspect = vi.fn();
+ const result = await buildOptimisticGroupedPropertyUpdates({
+ host: host({ onInspect }),
+ entityId: 'task-1',
+ propertyDefinitionId: 'status-def',
+ oldGroupKeys: ['in-progress', 'in-progress'],
+ newGroupKeys: ['in-progress'],
+ });
+
+ expect(result).toEqual({ updates: [], revalidations: [] });
+ expect(onInspect).not.toHaveBeenCalled();
+ });
+
+ it('returns revalidation only for unsupported values', async () => {
+ const result = await buildOptimisticGroupedPropertyUpdates({
+ host: host(),
+ entityId: 'task-1',
+ propertyDefinitionId: 'status-def',
+ oldGroupKeys: [],
+ newGroupKeys: [],
+ revalidateOnly: true,
+ });
+
+ expect(result.updates).toEqual([]);
+ expect(result.revalidations).toHaveLength(1);
+ });
+});
diff --git a/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.ts b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.ts
new file mode 100644
index 0000000000..993e272c84
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/grouped/graphql-optimistic.ts
@@ -0,0 +1,214 @@
+import { inspect, selectAll } from '@graphql-cache/exchange/inspection';
+import {
+ type OptimisticUpdate,
+ prependUnique,
+ type QueryRevalidation,
+ remove,
+ select,
+ update,
+} from '@graphql-cache/exchange/optimistic';
+import type { CacheHost } from '@graphql-cache/host/types';
+import {
+ type GroupedSoupInput,
+ GroupSoupMembershipDocument,
+ type GroupSoupMembershipQuery,
+} from '../../../service-clients/service-storage/graphql/generated/graphql';
+import { groupedSoupLogicalViewKey } from './graphql-operation-registry';
+import { NOT_SET_GROUP_KEY } from './types';
+
+type BuildArgs = {
+ host: CacheHost;
+ entityId: string;
+ propertyDefinitionId: string;
+ oldGroupKeys: readonly string[];
+ newGroupKeys: readonly string[];
+ /** Unsupported/date values still discover and revalidate relevant fields. */
+ revalidateOnly?: boolean;
+};
+
+export type OptimisticGroupedPropertyUpdates = {
+ updates: OptimisticUpdate[];
+ revalidations: QueryRevalidation[];
+};
+
+type GroupPage = {
+ input: GroupedSoupInput;
+ bins: GroupSoupMembershipQuery['user']['groupSoup']['bins'];
+};
+
+type GroupKeyDiff = {
+ removed: string[];
+ added: string[];
+};
+
+/** Returns changed group keys, or nothing when both sets are equivalent. */
+export function diffGroupKeys(
+ oldGroupKeys: readonly string[],
+ newGroupKeys: readonly string[]
+): GroupKeyDiff | undefined {
+ const oldKeys = new Set(oldGroupKeys);
+ const newKeys = new Set(newGroupKeys);
+ const removed = [...oldKeys].filter((key) => !newKeys.has(key));
+ const added = [...newKeys].filter((key) => !oldKeys.has(key));
+ return removed.length > 0 || added.length > 0
+ ? { removed, added }
+ : undefined;
+}
+
+/** True when one generated grouped input targets the changed property. */
+export function isRelevantPropertyGrouping(
+ input: GroupedSoupInput,
+ propertyDefinitionId: string
+): boolean {
+ const page = input.initial ?? input.continuation;
+ return (
+ page.groupBy.field === 'PROPERTY' &&
+ String(page.groupBy.propertyDefinitionId) === propertyDefinitionId
+ );
+}
+
+function isInitialInput(
+ input: GroupedSoupInput
+): input is Extract<GroupedSoupInput, { initial: object }> {
+ return input.initial !== undefined;
+}
+
+/** Associates loaded initial/continuation pages by frontend logical view. */
+export function groupPagesByLogicalView(
+ pages: readonly GroupPage[]
+): Map<string, GroupPage[]> {
+ const views = new Map<string, GroupPage[]>();
+ for (const page of pages) {
+ const logicalView = groupedSoupLogicalViewKey(page.input);
+ if (!logicalView) continue;
+ const grouped = views.get(logicalView) ?? [];
+ grouped.push(page);
+ views.set(logicalView, grouped);
+ }
+ return views;
+}
+
+/**
+ * Discovers every cached property-grouped field and creates constrained link
+ * recipes only where the loaded membership proves the move is applicable.
+ * Missing bins/pages are left untouched and revalidated after success.
+ */
+export async function buildOptimisticGroupedPropertyUpdates(
+ args: BuildArgs
+): Promise<OptimisticGroupedPropertyUpdates> {
+ const changes = diffGroupKeys(args.oldGroupKeys, args.newGroupKeys);
+ if (!changes && !args.revalidateOnly) {
+ return { updates: [], revalidations: [] };
+ }
+
+ const cachedViews = await inspect(
+ args.host,
+ selectAll(GroupSoupMembershipDocument).field('user').field('groupSoup')
+ );
+ const relevantViews = cachedViews.filter(({ variables }) =>
+ isRelevantPropertyGrouping(variables.input, args.propertyDefinitionId)
+ );
+ const revalidations: QueryRevalidation[] = relevantViews.map(
+ ({ variables }) => ({
+ document: GroupSoupMembershipDocument,
+ variables,
+ })
+ );
+ if (args.revalidateOnly || !changes) {
+ return { updates: [], revalidations };
+ }
+
+ const views = groupPagesByLogicalView(
+ relevantViews.flatMap(({ variables, value }) =>
+ value ? [{ input: variables.input, bins: value.bins }] : []
+ )
+ );
+ const { removed, added } = changes;
+ const updates: OptimisticUpdate[] = [];
+ const itemEntityKey = `GraphqlSoupItem:${args.entityId}`;
+ for (const pages of views.values()) {
+ const sourceGroupKeys = removed.length > 0 ? removed : args.oldGroupKeys;
+ const sourcePages = pages.filter((page) =>
+ sourceGroupKeys.some((key) =>
+ page.bins
+ .find((bin) => bin.key === key)
+ ?.items.some((item) => item.id === args.entityId)
+ )
+ );
+ if (sourcePages.length === 0) continue;
+
+ const destinationPages = pages.filter(
+ (page) =>
+ isInitialInput(page.input) &&
+ added.every((key) => page.bins.some((bin) => bin.key === key))
+ );
+ // Never expose a source-only move when this logical view has nowhere to
+ // show the destination. Revalidation will recover absent/new groups.
+ if (added.length > 0 && destinationPages.length === 0) continue;
+
+ for (const page of sourcePages) {
+ for (const key of removed) {
+ const source = page.bins.find((bin) => bin.key === key);
+ if (!source?.items.some((item) => item.id === args.entityId)) continue;
+ const items = select(GroupSoupMembershipDocument, {
+ input: page.input,
+ })
+ .field('user')
+ .field('groupSoup')
+ .field('bins')
+ .item('key', key)
+ .field('items');
+ updates.push(update(items, remove(itemEntityKey)));
+ }
+ }
+ for (const page of destinationPages) {
+ for (const key of added) {
+ const items = select(GroupSoupMembershipDocument, {
+ input: page.input,
+ })
+ .field('user')
+ .field('groupSoup')
+ .field('bins')
+ .item('key', key)
+ .field('items');
+ updates.push(update(items, prependUnique(itemEntityKey)));
+ }
+ }
+ }
+
+ return { updates, revalidations };
+}
+
+/** Group keys reproducible for the first optimistic implementation. */
+export function groupedPropertyKeys(value: {
+ valueType: string;
+ values?: readonly string[] | null;
+ refs?: readonly { entity_id: string }[] | null;
+ value?: unknown;
+}): string[] | undefined {
+ switch (value.valueType) {
+ case 'SELECT_STRING':
+ case 'SELECT_NUMBER': {
+ const values =
+ value.values ??
+ (Array.isArray(value.value) ? (value.value as string[]) : []);
+ return values.length > 0 ? [...values] : [NOT_SET_GROUP_KEY];
+ }
+ case 'ENTITY': {
+ const refs = 'refs' in value ? value.refs : undefined;
+ if (refs) {
+ return refs.length > 0
+ ? refs.map((reference) => reference.entity_id)
+ : [NOT_SET_GROUP_KEY];
+ }
+ const existing = Array.isArray(value.value)
+ ? (value.value as { entity_id: string }[])
+ : null;
+ return existing && existing.length > 0
+ ? existing.map((reference) => reference.entity_id)
+ : [NOT_SET_GROUP_KEY];
+ }
+ default:
+ return undefined;
+ }
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts b/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts
index a0cbc33c83..192194717c 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-properties.test.ts
@@ -188,6 +188,8 @@ describe('setEntityProperty', () => {
expect(context).toEqual({
normalizedCacheOptimistic: {
optimisticResponse: { setEntityProperty: optimistic },
+ linkPatches: [],
+ revalidations: [],
},
});
});
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts b/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts
index 0cbff4b5bc..bc27d3d7e1 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-properties.ts
@@ -12,7 +12,10 @@
import { ENABLE_GRAPHQL_SOUP } from '@core/constant/featureFlags';
import { throwOnErr } from '@core/util/result';
-import { executeOptimisticMutation } from '@graphql-cache/index';
+import {
+ executeOptimisticMutation,
+ type OptimisticMutationOptions,
+} from '@graphql-cache/index';
import { match } from 'ts-pattern';
import { propertiesServiceClient } from '../service-properties/client';
import type { EntityReference } from '../service-properties/generated/schemas/entityReference';
@@ -134,6 +137,8 @@ export type SetEntityPropertyArgs = {
* responds, so those run without optimism and rely on invalidation.
*/
optimisticProperty?: SoupPropertyFieldsFragment | undefined;
+ /** Mutation-scoped persistent normalized-cache relation recipes. */
+ optimisticCache?: OptimisticMutationOptions;
};
/**
@@ -173,7 +178,8 @@ export async function setEntityProperty(
variables,
{
setEntityProperty: args.optimisticProperty,
- } satisfies SetEntityPropertyMutation
+ } satisfies SetEntityPropertyMutation,
+ args.optimisticCache
).toPromise()
: await client.mutation(SetEntityPropertyDocument, variables).toPromise();
if (result.error) {
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
index 4ef64ace7c..5ecf35e512 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
@@ -7,6 +7,7 @@ import { fetchToken } from '@core/util/fetchWithToken';
import { isTauri } from '@core/util/platform';
import { platformFetch } from '@core/util/platformFetch';
import { normalizedCacheExchange } from '@graphql-cache/exchange/normalized-cache-exchange';
+import type { CacheHost } from '@graphql-cache/host/types';
import {
createTauriCacheHost,
createWorkerCacheHost,
@@ -83,6 +84,12 @@ export function graphqlCacheEnabled(): boolean {
}
let cachedClient: Client | undefined;
+let cacheHost: CacheHost | undefined;
+
+/** Returns the persistent normalized-cache host after client initialization. */
+export function getGraphqlCacheHost(): CacheHost | undefined {
+ return cacheHost?.disabled ? undefined : cacheHost;
+}
/**
* Resolves the urql client, lazily assembling the cached client on first
@@ -100,6 +107,7 @@ export function getGraphqlSoupClient(): Client {
const host = isTauri()
? createTauriCacheHost({ scope })
: createWorkerCacheHost({ scope });
+ cacheHost = host;
registerCacheHost(host);
return createClient({
url: `${dssHost}/items/soup/graphql`,
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index c2f843c3f8..aa52aa21ca 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -715,6 +715,13 @@ export type SoupInput =
| { continuation?: never; /** Start a new Soup query. */
initial: SoupInitialInput; };
+export type GroupSoupMembershipQueryVariables = Exact<{
+ input: GroupedSoupInput;
+}>;
+
+
+export type GroupSoupMembershipQuery = { user: { id: string, groupSoup: { bins: Array<{ key: string, totalCount: number, nextCursor: string | null, items: Array<{ id: string }> }> } } };
+
export type GroupSoupQueryVariables = Exact<{
input: GroupedSoupInput;
}>;
@@ -938,6 +945,7 @@ export const SoupPropertyFieldsFragmentDoc = {"kind":"Document","definitions":[{
export const SoupNotificationFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"done"}},{"kind":"Field","name":{"kind":"Name","value":"seen"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}}]} as unknown as DocumentNode<SoupNotificationFieldsFragment, unknown>;
export const SoupChannelMessageFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}}]} as unknown as DocumentNode<SoupChannelMessageFieldsFragment, unknown>;
export const SoupItemFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupItemFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"frecencyScore"}},{"kind":"Field","name":{"kind":"Name","value":"entity"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"isPersistent"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"parentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}},{"kind":"Field","name":{"kind":"Name","value":"senderPhotoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"isImportant"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"sortTs"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"sfsPhotoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"messageListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"labelListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestContentMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"internalDateTs"}},{"kind":"Field","name":{"kind":"Name","value":"sentAt"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isStarred"}},{"kind":"Field","name":{"kind":"Name","value":"isSent"}},{"kind":"Field","name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","name":{"kind":"Name","value":"from"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"to"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bcc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bodyParsed"}},{"kind":"Field","name":{"kind":"Name","value":"bodyText"}},{"kind":"Field","name":{"kind":"Name","value":"bodyHtmlSanitized"}},{"kind":"Field","name":{"kind":"Name","value":"bodyMacro"}},{"kind":"Field","name":{"kind":"Name","value":"bodyReplyless"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"channelName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"organizationId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestNonThreadMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveUpdatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"replyCount"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}},{"kind":"Field","name":{"kind":"Name","value":"createdBy"}},{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"summary"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"durationMs"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"attended"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"crmTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmCompanyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"emailSync"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupForeignEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntitySource"}},{"kind":"Field","name":{"kind":"Name","value":"storedForId"}},{"kind":"Field","name":{"kind":"Name","value":"storedForAuthEntity"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"done"}},{"kind":"Field","name":{"kind":"Name","value":"seen"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}}]} as unknown as DocumentNode<SoupItemFieldsFragment, unknown>;
+export const GroupSoupMembershipDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GroupSoupMembership"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"GroupedSoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"groupSoup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"bins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<GroupSoupMembershipQuery, GroupSoupMembershipQueryVariables>;
export const GroupSoupDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GroupSoup"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"GroupedSoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"groupSoup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"bins"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"key"}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}},{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupItemFields"}}]}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"done"}},{"kind":"Field","name":{"kind":"Name","value":"seen"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupItemFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"frecencyScore"}},{"kind":"Field","name":{"kind":"Name","value":"entity"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"isPersistent"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"parentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}},{"kind":"Field","name":{"kind":"Name","value":"senderPhotoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"isImportant"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"sortTs"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"sfsPhotoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"messageListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"labelListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestContentMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"internalDateTs"}},{"kind":"Field","name":{"kind":"Name","value":"sentAt"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isStarred"}},{"kind":"Field","name":{"kind":"Name","value":"isSent"}},{"kind":"Field","name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","name":{"kind":"Name","value":"from"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"to"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bcc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bodyParsed"}},{"kind":"Field","name":{"kind":"Name","value":"bodyText"}},{"kind":"Field","name":{"kind":"Name","value":"bodyHtmlSanitized"}},{"kind":"Field","name":{"kind":"Name","value":"bodyMacro"}},{"kind":"Field","name":{"kind":"Name","value":"bodyReplyless"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"channelName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"organizationId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestNonThreadMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveUpdatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"replyCount"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}},{"kind":"Field","name":{"kind":"Name","value":"createdBy"}},{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"summary"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"durationMs"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"attended"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"crmTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmCompanyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"emailSync"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupForeignEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntitySource"}},{"kind":"Field","name":{"kind":"Name","value":"storedForId"}},{"kind":"Field","name":{"kind":"Name","value":"storedForAuthEntity"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GroupSoupQuery, GroupSoupQueryVariables>;
export const SetEntityPropertyDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SetEntityProperty"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SetEntityPropertyInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"setEntityProperty"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}}]}}]} as unknown as DocumentNode<SetEntityPropertyMutation, SetEntityPropertyMutationVariables>;
export const SoupDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Soup"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupItemFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}},{"kind":"Field","name":{"kind":"Name","value":"hasMore"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlProperty"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"propertyDefinitionId"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupNotificationFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupNotification"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"eventType"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"sent"}},{"kind":"Field","name":{"kind":"Name","value":"done"}},{"kind":"Field","name":{"kind":"Name","value":"seen"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupChannelMessageFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelMessage"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"mentions"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupItemFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupItem"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"frecencyScore"}},{"kind":"Field","name":{"kind":"Name","value":"entity"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupDocument"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"documentName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"fileType"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"subType"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"kind"}},{"kind":"Field","name":{"kind":"Name","value":"isCompleted"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChat"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"chatName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"isPersistent"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupProject"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"projectName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"parentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupEmailThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"providerId"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"inboxVisible"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","alias":{"kind":"Name","value":"emailName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"senderEmail"}},{"kind":"Field","name":{"kind":"Name","value":"senderName"}},{"kind":"Field","name":{"kind":"Name","value":"senderPhotoUrl"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isDraft"}},{"kind":"Field","name":{"kind":"Name","value":"isImportant"}},{"kind":"Field","name":{"kind":"Name","value":"projectId"}},{"kind":"Field","name":{"kind":"Name","value":"sortTs"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"sfsPhotoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"attachments"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"providerAttachmentId"}},{"kind":"Field","name":{"kind":"Name","value":"filename"}},{"kind":"Field","name":{"kind":"Name","value":"mimeType"}},{"kind":"Field","name":{"kind":"Name","value":"sizeBytes"}},{"kind":"Field","name":{"kind":"Name","value":"contentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"messageListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"labelListVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestContentMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"linkId"}},{"kind":"Field","name":{"kind":"Name","value":"subject"}},{"kind":"Field","name":{"kind":"Name","value":"snippet"}},{"kind":"Field","name":{"kind":"Name","value":"internalDateTs"}},{"kind":"Field","name":{"kind":"Name","value":"sentAt"}},{"kind":"Field","name":{"kind":"Name","value":"isRead"}},{"kind":"Field","name":{"kind":"Name","value":"isStarred"}},{"kind":"Field","name":{"kind":"Name","value":"isSent"}},{"kind":"Field","name":{"kind":"Name","value":"hasAttachments"}},{"kind":"Field","name":{"kind":"Name","value":"from"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"to"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bcc"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"photoUrl"}}]}},{"kind":"Field","name":{"kind":"Name","value":"labels"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"providerLabelId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"bodyParsed"}},{"kind":"Field","name":{"kind":"Name","value":"bodyText"}},{"kind":"Field","name":{"kind":"Name","value":"bodyHtmlSanitized"}},{"kind":"Field","name":{"kind":"Name","value":"bodyMacro"}},{"kind":"Field","name":{"kind":"Name","value":"bodyReplyless"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"channelName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"channelType"}},{"kind":"Field","name":{"kind":"Name","value":"ownerId"}},{"kind":"Field","name":{"kind":"Name","value":"organizationId"}},{"kind":"Field","alias":{"kind":"Name","value":"channelTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"interactedAt"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"latestNonThreadMessage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupChannelMessageFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannelThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"senderId"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveUpdatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"replyCount"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCall"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"channelId"}},{"kind":"Field","name":{"kind":"Name","value":"channelName"}},{"kind":"Field","name":{"kind":"Name","value":"createdBy"}},{"kind":"Field","name":{"kind":"Name","value":"customName"}},{"kind":"Field","name":{"kind":"Name","value":"summary"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"durationMs"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"attended"}},{"kind":"Field","name":{"kind":"Name","value":"participants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"userId"}},{"kind":"Field","name":{"kind":"Name","value":"joinedAt"}},{"kind":"Field","name":{"kind":"Name","value":"leftAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"crmTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"crmCompanyName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"emailSync"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}},{"kind":"Field","name":{"kind":"Name","value":"domains"}},{"kind":"Field","name":{"kind":"Name","value":"properties"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupForeignEntity"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntityId"}},{"kind":"Field","name":{"kind":"Name","value":"foreignEntitySource"}},{"kind":"Field","name":{"kind":"Name","value":"storedForId"}},{"kind":"Field","name":{"kind":"Name","value":"storedForAuthEntity"}},{"kind":"Field","name":{"kind":"Name","value":"metadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"notifications"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupNotificationFields"}}]}}]}}]}}]}}]} as unknown as DocumentNode<SoupQuery, SoupQueryVariables>;
\ No newline at end of file
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/group-soup-membership.graphql b/apps/web/src/lib/service-clients/service-storage/graphql/group-soup-membership.graphql
new file mode 100644
index 0000000000..0347ccae60
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/group-soup-membership.graphql
@@ -0,0 +1,15 @@
+query GroupSoupMembership($input: GroupedSoupInput!) {
+ user {
+ id
+ groupSoup(input: $input) {
+ bins {
+ key
+ totalCount
+ nextCursor
+ items {
+ id
+ }
+ }
+ }
+ }
+}
diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
index 808bd8fc20..00483158b2 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs
@@ -13,7 +13,10 @@ use crate::engine::{
ClaimedMutationWire, EngineHandle, OptimisticWriteResultWire, ReadResultWire, WriteResultWire,
};
use crate::{CacheState, InitializedCache, emit_ops_affected};
+use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};
+use cache_core::query_inspection::CachedQueryInstance;
use cache_sqlite::SqliteStorage;
+use serde::Deserialize;
use tauri::{AppHandle, Manager, Runtime, State};
type Variables = serde_json::Map<String, serde_json::Value>;
@@ -118,6 +121,8 @@ pub async fn graphql_cache_begin_optimistic_write<R: Runtime>(
operation_name: Option<String>,
variables: Option<Variables>,
data: serde_json::Value,
+ link_patches: Option<Vec<OptimisticLinkPatch>>,
+ revalidations: Option<Vec<QueryRevalidation>>,
created_at_ms: i64,
) -> Result<OptimisticWriteResultWire, String> {
let result = engine_handle(&state)?
@@ -127,6 +132,8 @@ pub async fn graphql_cache_begin_optimistic_write<R: Runtime>(
operation_name,
variables.unwrap_or_default(),
data,
+ link_patches.unwrap_or_default(),
+ revalidations.unwrap_or_default(),
created_at_ms,
)
.await?;
@@ -134,6 +141,30 @@ pub async fn graphql_cache_begin_optimistic_write<R: Runtime>(
Ok(result)
}
+/// One field-only response-key path segment for query inspection.
+#[derive(Debug, Deserialize)]
+pub struct InspectionPathSegment {
+ /// Generated GraphQL response key (alias when present).
+ pub field: String,
+}
+
+/// Enumerates cached variants of one generated query field.
+#[tauri::command]
+pub async fn graphql_cache_inspect_query(
+ state: State<'_, CacheState>,
+ query: String,
+ operation_name: Option<String>,
+ path: Vec<InspectionPathSegment>,
+) -> Result<Vec<CachedQueryInstance>, String> {
+ engine_handle(&state)?
+ .inspect_query(
+ query,
+ operation_name,
+ path.into_iter().map(|segment| segment.field).collect(),
+ )
+ .await
+}
+
/// Claims the oldest runnable queued mutation.
#[tauri::command]
pub async fn graphql_cache_claim_next_mutation(
diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
index c9632e8691..a53c676afe 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs
@@ -12,7 +12,9 @@
//! internally — the same scheme as the `cache-wasm` shell.
use cache_core::deps::OpId;
-use cache_core::engine::{Engine, ReadResult, WriteResult};
+use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult, WriteResult};
+use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};
+use cache_core::query_inspection::{CachedQueryInstance, QueryInspection};
use cache_core::queue::{ClaimedMutation, MutationClaimRequest, MutationClaimToken};
use cache_core::value::EntityKey;
use cache_sqlite::SqliteStorage;
@@ -45,6 +47,8 @@ pub struct WriteResultWire {
/// True when the identity witness wiped and rebound the cache before
/// this write (silent restart).
pub reset: bool,
+ /// Queries to fetch after successful optimistic settlement.
+ pub revalidations: Vec<QueryRevalidation>,
}
/// Mirrors `OptimisticWriteResult` in
@@ -151,6 +155,7 @@ fn wire_write_result(ops: &OpInterner, result: WriteResult) -> WriteResultWire {
changed: result.changed.into_iter().map(|k| k.0).collect(),
affected_ops: ops.names(result.affected_ops),
reset: result.reset,
+ revalidations: result.revalidations,
}
}
@@ -201,6 +206,26 @@ impl EngineHandle {
.map_err(|e| e.to_string())
}
+ /// Enumerates cached variants of one generated query field.
+ pub async fn inspect_query(
+ &self,
+ query: String,
+ operation_name: Option<String>,
+ path: Vec<String>,
+ ) -> Result<Vec<CachedQueryInstance>, String> {
+ self.inner
+ .lock()
+ .await
+ .engine
+ .inspect_query(&QueryInspection {
+ query,
+ operation_name,
+ path,
+ })
+ .await
+ .map_err(|error| error.to_string())
+ }
+
/// Normalizes and stores a network response.
pub async fn write(
&self,
@@ -236,6 +261,8 @@ impl EngineHandle {
operation_name: Option<String>,
variables: Variables,
data: serde_json::Value,
+ link_patches: Vec<OptimisticLinkPatch>,
+ revalidations: Vec<QueryRevalidation>,
created_at_ms: i64,
) -> Result<OptimisticWriteResultWire, String> {
let mut state = self.inner.lock().await;
@@ -244,11 +271,15 @@ impl EngineHandle {
engine
.begin_optimistic_write(
origin,
- &query,
- operation_name.as_deref(),
- &variables,
- &data,
- created_at_ms,
+ BeginOptimisticWrite {
+ query: &query,
+ operation_name: operation_name.as_deref(),
+ variables: &variables,
+ data: &data,
+ link_patches: &link_patches,
+ revalidations: &revalidations,
+ created_at_ms,
+ },
)
.await
.map(|(transaction, result)| OptimisticWriteResultWire {
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 715953ac9b..648ffd1c97 100644
--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs
@@ -78,6 +78,36 @@ fn write_then_read_round_trips() {
assert_eq!(data, soup_data(false));
}
+#[test]
+fn query_inspection_serializes_generated_variables_and_value() {
+ let handle = spawn_handle();
+ write(&handle, None, soup_data(false), None);
+
+ let instances = block_on(handle.inspect_query(
+ QUERY.to_string(),
+ Some("Soup".to_string()),
+ vec!["user".to_string(), "soup".to_string()],
+ ))
+ .unwrap();
+ assert_eq!(instances.len(), 1);
+ assert_eq!(instances[0].variables, variables());
+ assert_eq!(
+ instances[0].value.as_ref().unwrap()["hasMore"],
+ serde_json::json!(false)
+ );
+ assert_eq!(
+ serde_json::to_value(&instances).unwrap(),
+ serde_json::json!([{
+ "variables": {"input": {"limit": 1}},
+ "value": {
+ "nextCursor": null,
+ "hasMore": false,
+ "items": [{"id": "doc-1"}]
+ }
+ }])
+ );
+}
+
#[test]
fn registered_op_is_affected_by_later_writes() {
let handle = spawn_handle();
@@ -118,6 +148,8 @@ fn optimistic_layer_commits_durably() {
Some("Soup".to_string()),
variables(),
soup_data(true),
+ vec![],
+ vec![],
0,
))
.unwrap();
@@ -159,6 +191,8 @@ fn rollback_drops_optimistic_contribution() {
Some("Soup".to_string()),
variables(),
soup_data(true),
+ vec![],
+ vec![],
0,
))
.unwrap();
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index e870565c63..596114447f 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -230,6 +230,7 @@ pub fn run() {
graphql_cache_plugin::commands::graphql_cache_read,
graphql_cache_plugin::commands::graphql_cache_write,
graphql_cache_plugin::commands::graphql_cache_begin_optimistic_write,
+ graphql_cache_plugin::commands::graphql_cache_inspect_query,
graphql_cache_plugin::commands::graphql_cache_claim_next_mutation,
graphql_cache_plugin::commands::graphql_cache_defer_optimistic_write,
graphql_cache_plugin::commands::graphql_cache_commit_optimistic_write,
diff --git a/crates/client/cache-core/src/document.rs b/crates/client/cache-core/src/document.rs
index 44a47f10d4..9547774709 100644
--- a/crates/client/cache-core/src/document.rs
+++ b/crates/client/cache-core/src/document.rs
@@ -66,14 +66,14 @@ pub enum OperationKind {
Mutation,
}
-#[derive(Debug)]
+#[derive(Debug, Clone)]
pub struct Operation {
pub name: Option<String>,
pub kind: OperationKind,
pub selection_set: Vec<Selection>,
}
-#[derive(Debug)]
+#[derive(Debug, Clone)]
pub struct Document {
pub operations: Vec<Operation>,
}
diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rs
index 8a7b528a8d..1d07c1f626 100644
--- a/crates/client/cache-core/src/engine.rs
+++ b/crates/client/cache-core/src/engine.rs
@@ -5,10 +5,19 @@
use crate::denormalize::{DenormalizeError, ReadOutcome, RecordSource, denormalize};
use crate::deps::{DepIndex, OpId};
use crate::document::{Document, DocumentError, OperationKind};
+use crate::link_patch::{
+ LinkPatchError, OptimisticLinkPatch, QueryRevalidation, apply_link_patches,
+ deduplicate_patches, missing_patch_record,
+};
use crate::normalize::{NormalizeError, RecordUpdates, normalize};
+use crate::query_inspection::{
+ CachedQueryInstance, OwnerResolution, QueryInspection, QueryInspectionError, prepare,
+ recover_variants, resolve_owner, selected_result_value,
+};
use crate::queue::{
ClaimedMutation, MutationClaimRequest, MutationClaimToken, MutationId, MutationRequest,
- NewQueuedMutation, PersistedOptimisticLayer, QueuedMutation, StoredMutation,
+ NewQueuedMutation, OptimisticSource, PersistedOptimisticLayer, QueuedMutation, StoredMutation,
+ decode_optimistic_source, encode_optimistic_source,
};
use crate::store::Storage;
use crate::value::{EntityKey, Record, canonical_json};
@@ -26,6 +35,10 @@ pub enum EngineError<S: std::error::Error + 'static> {
Normalize(#[from] NormalizeError),
#[error(transparent)]
Denormalize(#[from] DenormalizeError),
+ #[error(transparent)]
+ LinkPatch(#[from] LinkPatchError),
+ #[error(transparent)]
+ QueryInspection(#[from] QueryInspectionError),
#[error("unknown or already-settled optimistic transaction {0}")]
UnknownTransaction(OptimisticTransactionId),
#[error("stale claim for optimistic transaction {0}")]
@@ -62,6 +75,26 @@ pub struct WriteResult {
/// before this response was written. Hosts must broadcast this to other
/// engine instances sharing the same storage.
pub reset: bool,
+ /// Queries that should be revalidated after a successful settlement.
+ pub revalidations: Vec<QueryRevalidation>,
+}
+
+/// Borrowed inputs for atomically beginning one optimistic mutation.
+pub struct BeginOptimisticWrite<'a> {
+ /// GraphQL mutation document.
+ pub query: &'a str,
+ /// Selected operation name.
+ pub operation_name: Option<&'a str>,
+ /// Mutation variables.
+ pub variables: &'a serde_json::Map<String, Json>,
+ /// Optimistic mutation response.
+ pub data: &'a Json,
+ /// Ordered constrained relation recipes.
+ pub link_patches: &'a [OptimisticLinkPatch],
+ /// Revalidations for relevant fields that could not be patched.
+ pub revalidations: &'a [QueryRevalidation],
+ /// Wall-clock enqueue timestamp.
+ pub created_at_ms: i64,
}
/// Engine-assigned id of one optimistic mutation transaction. Never reuse
@@ -76,6 +109,8 @@ pub type OptimisticTransactionId = MutationId;
struct OptimisticLayer {
id: OptimisticTransactionId,
updates: RecordUpdates,
+ link_patches: Vec<OptimisticLinkPatch>,
+ revalidations: Vec<QueryRevalidation>,
}
/// Reserved storage key holding the identity bound to this cache. The
@@ -129,7 +164,8 @@ impl<S: Storage> Engine<S> {
}
/// Hydrates durable optimistic layers before the first operation. Queue
- /// order is the optimistic composition order.
+ /// order is the optimistic composition order. Relation recipes are
+ /// reconstructed against the durable base and preceding layers.
async fn hydrate_optimistic(&mut self) -> Result<(), EngineError<S::Error>> {
if self.optimistic_hydrated {
return Ok(());
@@ -139,7 +175,7 @@ impl<S: Storage> Engine<S> {
.load_mutation_queue()
.await
.map_err(EngineError::Storage)?;
- self.optimistic = Self::normalize_queued_layers(&mut self.docs, queued)?;
+ self.optimistic = self.rebuild_queued_layers(queued).await?;
self.optimistic_hydrated = true;
Ok(())
}
@@ -153,62 +189,88 @@ impl<S: Storage> Engine<S> {
.load_mutation_queue()
.await
.map_err(EngineError::Storage)?;
- let replacement = Self::normalize_queued_layers(&mut self.docs, queued)?;
- let candidates: BTreeSet<EntityKey> = self
- .optimistic
- .iter()
- .chain(&replacement)
- .flat_map(|layer| layer.updates.keys().cloned())
- .collect();
+ let old_candidates = layer_keys(&self.optimistic);
+ let old_bases = self.load_bases(&old_candidates).await?;
+ let before = effective_records(&old_bases, &self.optimistic, &old_candidates);
+ let replacement = self.rebuild_queued_layers(queued).await?;
+ let mut candidates = old_candidates;
+ candidates.extend(layer_keys(&replacement));
let bases = self.load_bases(&candidates).await?;
- let before = effective_records(&bases, &self.optimistic, &candidates);
+ let mut before_all = effective_records(&bases, &self.optimistic, &candidates);
+ before_all.extend(before);
+ let after = effective_records(&bases, &replacement, &candidates);
self.optimistic = replacement;
self.optimistic_hydrated = true;
- let after = effective_records(&bases, &self.optimistic, &candidates);
let changed: BTreeSet<EntityKey> = candidates
.into_iter()
- .filter(|key| before.get(key) != after.get(key))
+ .filter(|key| before_all.get(key) != after.get(key))
.collect();
let affected_ops = self.deps.ops_for_keys(changed.iter());
Ok(WriteResult {
changed,
affected_ops,
reset: false,
+ revalidations: Vec::new(),
})
}
- fn normalize_queued_layers(
- docs: &mut HashMap<String, Document>,
+ async fn rebuild_queued_layers(
+ &mut self,
queued: Vec<QueuedMutation>,
) -> Result<Vec<OptimisticLayer>, EngineError<S::Error>> {
- queued
- .into_iter()
- .map(|queued| {
- let variables: Json = serde_json::from_str(&queued.mutation.request.variables_json)
- .map_err(|error| EngineError::InvalidQueuedMutation {
- id: queued.id,
- detail: format!("invalid variables: {error}"),
- })?;
- let Json::Object(variables) = variables else {
- return Err(EngineError::InvalidQueuedMutation {
- id: queued.id,
- detail: "variables are not an object".to_string(),
- });
- };
- let data: Json = serde_json::from_str(&queued.optimistic.optimistic_data_json)
- .map_err(|error| EngineError::InvalidQueuedMutation {
- id: queued.id,
- detail: format!("invalid optimistic response: {error}"),
- })?;
- let document = Self::document(docs, &queued.mutation.request.query)?;
- let operation =
- document.operation(queued.mutation.request.operation_name.as_deref())?;
- Ok(OptimisticLayer {
+ let mut layers = Vec::with_capacity(queued.len());
+ for queued in queued {
+ let variables: Json = serde_json::from_str(&queued.mutation.request.variables_json)
+ .map_err(|error| EngineError::InvalidQueuedMutation {
id: queued.id,
- updates: normalize(operation, &variables, &data)?,
- })
- })
- .collect()
+ detail: format!("invalid variables: {error}"),
+ })?;
+ let Json::Object(variables) = variables else {
+ return Err(EngineError::InvalidQueuedMutation {
+ id: queued.id,
+ detail: "variables are not an object".to_string(),
+ });
+ };
+ let source = decode_optimistic_source(&queued.optimistic.optimistic_data_json)
+ .map_err(|detail| EngineError::InvalidQueuedMutation {
+ id: queued.id,
+ detail: format!("invalid optimistic response: {detail}"),
+ })?;
+ let document = Self::document(&mut self.docs, &queued.mutation.request.query)?;
+ let operation =
+ document.operation(queued.mutation.request.operation_name.as_deref())?;
+ let mut updates = normalize(operation, &variables, &source.mutation_data)?;
+ let patches = deduplicate_patches(&source.link_patches).map_err(|error| {
+ EngineError::InvalidQueuedMutation {
+ id: queued.id,
+ detail: error.to_string(),
+ }
+ })?;
+ let candidates: BTreeSet<EntityKey> = updates.keys().cloned().collect();
+ let (candidates, bases) = self
+ .load_link_patch_bases(candidates, &layers, &updates, &patches)
+ .await?;
+ let composed = effective_records(&bases, &layers, &candidates);
+ let mut effective = present_records(composed);
+ merge_updates_into_effective(&mut effective, &updates);
+ // Missing query fields after a format wipe are intentionally not
+ // recreated from stale recipes during hydration.
+ apply_link_patches(&mut effective, &mut updates, &patches, true)?;
+ layers.push(OptimisticLayer {
+ id: queued.id,
+ updates,
+ link_patches: patches,
+ revalidations: deduplicate_revalidations(
+ source.revalidations.into_iter().chain(
+ source
+ .link_patches
+ .iter()
+ .map(OptimisticLinkPatch::revalidation),
+ ),
+ ),
+ });
+ }
+ Ok(layers)
}
/// The identity binding of this cache, hydrating it from storage on
@@ -395,13 +457,33 @@ impl<S: Storage> Engine<S> {
}
}
+ let mut candidates = layer_keys(&self.optimistic);
+ candidates.extend(updates.keys().cloned());
+ let bases_before = self.load_bases(&candidates).await?;
+ let before = effective_records(&bases_before, &self.optimistic, &candidates);
let changed = self.persist_updates(updates).await?;
+ if !self.optimistic.is_empty() {
+ let queued = self
+ .storage
+ .load_mutation_queue()
+ .await
+ .map_err(EngineError::Storage)?;
+ self.optimistic = self.rebuild_queued_layers(queued).await?;
+ candidates.extend(layer_keys(&self.optimistic));
+ }
+ let bases_after = self.load_bases(&candidates).await?;
+ let after = effective_records(&bases_after, &self.optimistic, &candidates);
+ let visible_changed: BTreeSet<EntityKey> = candidates
+ .into_iter()
+ .filter(|key| before.get(key) != after.get(key))
+ .collect();
+
let mut affected_ops = if reset {
// Everything anyone had cached is gone: re-execute all ops.
self.deps.all_ops()
} else {
- self.deps.ops_for_keys(changed.iter())
+ self.deps.ops_for_keys(visible_changed.iter())
};
if let Some(origin) = origin_op {
affected_ops.remove(&origin);
@@ -410,6 +492,7 @@ impl<S: Storage> Engine<S> {
changed,
affected_ops,
reset,
+ revalidations: Vec::new(),
})
}
@@ -483,24 +566,50 @@ impl<S: Storage> Engine<S> {
pub async fn begin_optimistic_write(
&mut self,
origin_op: Option<OpId>,
- query: &str,
- operation_name: Option<&str>,
- variables: &serde_json::Map<String, Json>,
- data: &Json,
- created_at_ms: i64,
+ input: BeginOptimisticWrite<'_>,
) -> Result<(OptimisticTransactionId, WriteResult), EngineError<S::Error>> {
+ let BeginOptimisticWrite {
+ query,
+ operation_name,
+ variables,
+ data,
+ link_patches,
+ revalidations,
+ created_at_ms,
+ } = input;
self.hydrate_optimistic().await?;
let doc = Self::document(&mut self.docs, query)?;
let op = doc.operation(operation_name)?;
- let updates = normalize(op, variables, data)?;
+ let mut updates = normalize(op, variables, data)?;
+ let patches = deduplicate_patches(link_patches)?;
+ let revalidations = deduplicate_revalidations(
+ revalidations
+ .iter()
+ .cloned()
+ .chain(patches.iter().map(OptimisticLinkPatch::revalidation)),
+ );
let candidates: BTreeSet<EntityKey> = updates.keys().cloned().collect();
- let bases = self.load_bases(&candidates).await?;
+ let optimistic = self.optimistic.clone();
+ let (candidates, bases) = self
+ .load_link_patch_bases(candidates, &optimistic, &updates, &patches)
+ .await?;
let before = effective_records(&bases, &self.optimistic, &candidates);
+ let mut effective = present_records(before.clone());
+ merge_updates_into_effective(&mut effective, &updates);
+ // This stages on clones internally, so no part of an invalid patch
+ // set can become visible or durable.
+ apply_link_patches(&mut effective, &mut updates, &patches, false)?;
+
let identity = match self.bound_identity().await? {
IdentityState::Bound(identity) => Some(identity),
IdentityState::NotHydrated | IdentityState::Missing => None,
};
+ let source = OptimisticSource {
+ mutation_data: data.clone(),
+ link_patches: patches.clone(),
+ revalidations: revalidations.clone(),
+ };
let id = self
.storage
.enqueue_mutation(NewQueuedMutation {
@@ -514,13 +623,18 @@ impl<S: Storage> Engine<S> {
created_at_ms,
),
optimistic: PersistedOptimisticLayer {
- optimistic_data_json: canonical_json(data),
+ optimistic_data_json: encode_optimistic_source(&source),
normalized_updates: updates.clone(),
},
})
.await
.map_err(EngineError::Storage)?;
- self.optimistic.push(OptimisticLayer { id, updates });
+ self.optimistic.push(OptimisticLayer {
+ id,
+ updates,
+ link_patches: patches,
+ revalidations,
+ });
let after = effective_records(&bases, &self.optimistic, &candidates);
let changed: BTreeSet<EntityKey> = candidates
@@ -537,6 +651,7 @@ impl<S: Storage> Engine<S> {
changed,
affected_ops,
reset: false,
+ revalidations: Vec::new(),
},
))
}
@@ -592,15 +707,25 @@ impl<S: Storage> Engine<S> {
.iter()
.position(|layer| layer.id == transaction)
.ok_or(EngineError::UnknownTransaction(transaction))?;
+ let recipes = self.optimistic[index].link_patches.clone();
+ let revalidations = self.optimistic[index].revalidations.clone();
let doc = Self::document(&mut self.docs, query)?;
let op = doc.operation(operation_name)?;
- let updates = normalize(op, variables, data)?;
+ let mut updates = normalize(op, variables, data)?;
- let mut candidates: BTreeSet<EntityKey> =
- self.optimistic[index].updates.keys().cloned().collect();
+ let mut candidates = layer_keys(&self.optimistic);
candidates.extend(updates.keys().cloned());
- let bases = self.load_bases(&candidates).await?;
+ let (mut candidates, bases) = self
+ .load_link_patch_bases(candidates, &[], &updates, &recipes)
+ .await?;
let before = effective_records(&bases, &self.optimistic, &candidates);
+
+ // Reapply the idempotent recipes to the latest durable base, never a
+ // captured optimistic query snapshot. Stale/missing fields are skipped
+ // and recovered by the returned revalidations.
+ let mut effective = bases.clone();
+ merge_updates_into_effective(&mut effective, &updates);
+ apply_link_patches(&mut effective, &mut updates, &recipes, true)?;
let (durable_changed, entries) = stage_updates(&bases, updates);
if !self
.storage
@@ -610,14 +735,23 @@ impl<S: Storage> Engine<S> {
{
return Err(EngineError::StaleMutationClaim(transaction));
}
-
- let mut settled_bases = bases;
for (key, record) in entries {
- settled_bases.insert(key.clone(), record.clone());
self.hot.put(key, record);
}
- self.optimistic.remove(index);
- let after = effective_records(&settled_bases, &self.optimistic, &candidates);
+
+ // Reconstruct every later recipe against the settled base. This is
+ // required when an earlier layer is committed or rolled back: later
+ // layers must not retain a whole-field snapshot of the old base.
+ let queued = self
+ .storage
+ .load_mutation_queue()
+ .await
+ .map_err(EngineError::Storage)?;
+ let replacement = self.rebuild_queued_layers(queued).await?;
+ candidates.extend(layer_keys(&replacement));
+ let settled_bases = self.load_bases(&candidates).await?;
+ let after = effective_records(&settled_bases, &replacement, &candidates);
+ self.optimistic = replacement;
let visible_changed: BTreeSet<EntityKey> = candidates
.into_iter()
.filter(|key| before.get(key) != after.get(key))
@@ -627,6 +761,7 @@ impl<S: Storage> Engine<S> {
changed: durable_changed,
affected_ops,
reset: false,
+ revalidations,
})
}
@@ -638,13 +773,11 @@ impl<S: Storage> Engine<S> {
claim: MutationClaimToken,
) -> Result<WriteResult, EngineError<S::Error>> {
self.hydrate_optimistic().await?;
- let index = self
- .optimistic
+ self.optimistic
.iter()
.position(|layer| layer.id == transaction)
.ok_or(EngineError::UnknownTransaction(transaction))?;
- let candidates: BTreeSet<EntityKey> =
- self.optimistic[index].updates.keys().cloned().collect();
+ let mut candidates = layer_keys(&self.optimistic);
let bases = self.load_bases(&candidates).await?;
let before = effective_records(&bases, &self.optimistic, &candidates);
if !self
@@ -655,8 +788,16 @@ impl<S: Storage> Engine<S> {
{
return Err(EngineError::StaleMutationClaim(transaction));
}
- self.optimistic.remove(index);
- let after = effective_records(&bases, &self.optimistic, &candidates);
+ let queued = self
+ .storage
+ .load_mutation_queue()
+ .await
+ .map_err(EngineError::Storage)?;
+ let replacement = self.rebuild_queued_layers(queued).await?;
+ candidates.extend(layer_keys(&replacement));
+ let current_bases = self.load_bases(&candidates).await?;
+ let after = effective_records(&current_bases, &replacement, &candidates);
+ self.optimistic = replacement;
let visible_changed: BTreeSet<EntityKey> = candidates
.into_iter()
.filter(|key| before.get(key) != after.get(key))
@@ -666,9 +807,39 @@ impl<S: Storage> Engine<S> {
changed: BTreeSet::new(),
affected_ops,
reset: false,
+ revalidations: Vec::new(),
})
}
+ /// Loads every normalized record reached while resolving query-rooted
+ /// link updates, including records currently outside the hot tier.
+ async fn load_link_patch_bases(
+ &mut self,
+ mut candidates: BTreeSet<EntityKey>,
+ layers: &[OptimisticLayer],
+ pending_updates: &RecordUpdates,
+ patches: &[OptimisticLinkPatch],
+ ) -> Result<(BTreeSet<EntityKey>, HashMap<EntityKey, Record>), EngineError<S::Error>> {
+ if !patches.is_empty() {
+ candidates.insert(EntityKey::root());
+ }
+ loop {
+ let bases = self.load_bases(&candidates).await?;
+ let composed = effective_records(&bases, layers, &candidates);
+ let mut effective = present_records(composed);
+ merge_updates_into_effective(&mut effective, pending_updates);
+ let missing: BTreeSet<_> = patches
+ .iter()
+ .filter_map(|patch| missing_patch_record(&effective, patch))
+ .filter(|key| !candidates.contains(key))
+ .collect();
+ if missing.is_empty() {
+ return Ok((candidates, bases));
+ }
+ candidates.extend(missing);
+ }
+ }
+
/// Loads current durable records (hot tier, then storage) for `keys`
/// without touching LRU recency or persisting anything.
async fn load_bases(
@@ -700,6 +871,55 @@ impl<S: Storage> Engine<S> {
Ok(out)
}
+ /// Enumerates cached argument variants of one generated query field.
+ ///
+ /// Normalized owners, canonical field keys, cold records, and optimistic
+ /// layers remain internal. Every recovered variable set is read through
+ /// the ordinary denormalizer so inspection has cache-only read semantics.
+ pub async fn inspect_query(
+ &mut self,
+ inspection: &QueryInspection,
+ ) -> Result<Vec<CachedQueryInstance>, EngineError<S::Error>> {
+ self.hydrate_optimistic().await?;
+ let operation = Self::document(&mut self.docs, &inspection.query)?
+ .operation(inspection.operation_name.as_deref())?
+ .clone();
+ let prepared = prepare(&operation, &inspection.path)?;
+
+ let mut candidates = BTreeSet::from([EntityKey::root()]);
+ let owner = loop {
+ let bases = self.load_bases(&candidates).await?;
+ let effective =
+ present_records(effective_records(&bases, &self.optimistic, &candidates));
+ match resolve_owner(&effective, &operation, &inspection.path)? {
+ OwnerResolution::Owner(owner) => break owner,
+ OwnerResolution::Absent => return Ok(Vec::new()),
+ OwnerResolution::NeedRecord(key) if !candidates.contains(&key) => {
+ candidates.insert(key);
+ }
+ OwnerResolution::NeedRecord(_) => return Ok(Vec::new()),
+ }
+ };
+ let variables = recover_variants(&owner, &prepared)?;
+ let mut instances = Vec::with_capacity(variables.len());
+ for variables in variables {
+ let value = match self
+ .read_query(
+ None,
+ &inspection.query,
+ inspection.operation_name.as_deref(),
+ &variables,
+ )
+ .await?
+ {
+ ReadResult::Hit { data } => Some(selected_result_value(&data, &inspection.path)?),
+ ReadResult::Miss => None,
+ };
+ instances.push(CachedQueryInstance { variables, value });
+ }
+ Ok(instances)
+ }
+
/// Reacts to a reset performed by *another* engine instance sharing the
/// same storage (cross-tab broadcast): drops all local in-memory state
/// and returns every local active operation for re-execution.
@@ -853,3 +1073,42 @@ fn effective_records(
})
.collect()
}
+
+fn present_records(records: HashMap<EntityKey, Option<Record>>) -> HashMap<EntityKey, Record> {
+ records
+ .into_iter()
+ .filter_map(|(key, record)| record.map(|record| (key, record)))
+ .collect()
+}
+
+fn merge_updates_into_effective(
+ effective: &mut HashMap<EntityKey, Record>,
+ updates: &RecordUpdates,
+) {
+ for (key, update) in updates {
+ effective
+ .entry(key.clone())
+ .or_default()
+ .merge(update.clone());
+ }
+}
+
+fn layer_keys(layers: &[OptimisticLayer]) -> BTreeSet<EntityKey> {
+ layers
+ .iter()
+ .flat_map(|layer| layer.updates.keys().cloned())
+ .collect()
+}
+
+fn deduplicate_revalidations(
+ revalidations: impl IntoIterator<Item = QueryRevalidation>,
+) -> Vec<QueryRevalidation> {
+ let mut unique = BTreeSet::new();
+ for mut revalidation in revalidations {
+ if let Ok(variables) = serde_json::from_str::<Json>(&revalidation.variables_json) {
+ revalidation.variables_json = canonical_json(&variables);
+ }
+ unique.insert(revalidation);
+ }
+ unique.into_iter().collect()
+}
diff --git a/crates/client/cache-core/src/lib.rs b/crates/client/cache-core/src/lib.rs
index 64bda7a914..e60678578f 100644
--- a/crates/client/cache-core/src/lib.rs
+++ b/crates/client/cache-core/src/lib.rs
@@ -7,8 +7,11 @@ pub mod denormalize;
pub mod deps;
pub mod document;
pub mod engine;
+pub mod link_patch;
pub mod meta;
pub mod normalize;
+pub mod query_inspection;
+mod query_path;
pub mod queue;
pub mod store;
pub mod value;
diff --git a/crates/client/cache-core/src/link_patch.rs b/crates/client/cache-core/src/link_patch.rs
new file mode 100644
index 0000000000..9df894accf
--- /dev/null
+++ b/crates/client/cache-core/src/link_patch.rs
@@ -0,0 +1,820 @@
+//! Constrained optimistic updates for link lists nested in embedded values.
+//!
+//! Patch recipes are transport-neutral and serializable so they can be kept
+//! with durable optimistic mutations and replayed after a restart.
+
+use crate::document::{Document, FieldNode, OperationKind, Selection};
+use crate::meta;
+use crate::normalize::RecordUpdates;
+use crate::query_path::{
+ selected_field as find_selected_field, selected_storage_key as resolve_selected_storage_key,
+ selected_type as resolve_selected_type,
+};
+use crate::value::{CacheNumber, CacheValue, EntityKey, FieldKey, Record, canonical_json};
+use serde::{Deserialize, Serialize};
+use serde_json::Value as Json;
+use std::collections::{BTreeSet, HashMap};
+use thiserror::Error;
+
+/// Maximum number of link recipes accepted for one mutation.
+pub const MAX_PATCHES: usize = 128;
+/// Maximum number of path segments accepted for one recipe.
+pub const MAX_PATH_DEPTH: usize = 16;
+/// Maximum list length traversed by one recipe.
+pub const MAX_TRAVERSED_LIST: usize = 10_000;
+
+/// One constrained step through an embedded cache value.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(untagged)]
+pub enum LinkPathSegment {
+ /// Selects a field on the current embedded object.
+ Field {
+ /// Exact cache field key. Nested GroupSoup fields have no arguments.
+ field: FieldKey,
+ },
+ /// Selects exactly one embedded object in the current list by a scalar field.
+ ListItem {
+ /// Scalar matching constraint.
+ #[serde(rename = "listItem")]
+ list_item: ListItemByScalar,
+ },
+}
+
+/// Scalar selector for an embedded list item.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ListItemByScalar {
+ /// Field on the embedded object to inspect.
+ pub where_field: FieldKey,
+ /// JSON-compatible scalar value that must compare equal.
+ pub equals: Json,
+}
+
+/// Idempotent operation on the selected normalized-link list.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum LinkOperation {
+ /// Removes every occurrence of the entity reference.
+ Remove {
+ /// Normalized entity key to remove.
+ #[serde(rename = "entityKey")]
+ entity_key: EntityKey,
+ },
+ /// Removes every occurrence and inserts one reference at the front.
+ PrependUnique {
+ /// Normalized entity key to prepend.
+ #[serde(rename = "entityKey")]
+ entity_key: EntityKey,
+ },
+}
+
+impl LinkOperation {
+ fn entity_key(&self) -> &EntityKey {
+ match self {
+ Self::Remove { entity_key } | Self::PrependUnique { entity_key } => entity_key,
+ }
+ }
+}
+
+/// A query that should be fetched after a successful mutation settlement.
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct QueryRevalidation {
+ /// GraphQL query document text.
+ pub query: String,
+ /// Selected operation when the document contains multiple operations.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub operation_name: Option<String>,
+ /// Canonical JSON object containing query variables.
+ pub variables_json: String,
+}
+
+/// One mutation-scoped update rooted at a generated GraphQL query.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OptimisticLinkPatch {
+ /// GraphQL query document that gives the path its typed entrypoint.
+ pub query: String,
+ /// Selected operation when the document contains multiple operations.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub operation_name: Option<String>,
+ /// Canonical JSON object containing the query variables.
+ pub variables_json: String,
+ /// Response-key traversal beginning at the query root.
+ pub path: Vec<LinkPathSegment>,
+ /// Idempotent relation operation.
+ pub operation: LinkOperation,
+}
+
+impl OptimisticLinkPatch {
+ /// Query to refresh after this optimistic update commits.
+ pub fn revalidation(&self) -> QueryRevalidation {
+ QueryRevalidation {
+ query: self.query.clone(),
+ operation_name: self.operation_name.clone(),
+ variables_json: self.variables_json.clone(),
+ }
+ }
+}
+
+/// Failure to validate or apply a constrained link recipe.
+#[derive(Debug, Clone, PartialEq, Eq, Error)]
+pub enum LinkPatchError {
+ /// Too many recipes were supplied.
+ #[error("link patch count {actual} exceeds limit {maximum}")]
+ TooManyPatches { actual: usize, maximum: usize },
+ /// A recipe path is empty or too deep.
+ #[error("invalid link patch path depth {0}")]
+ InvalidDepth(usize),
+ /// A normalized entity key is malformed.
+ #[error("invalid normalized entity key `{0}`")]
+ InvalidEntityKey(String),
+ /// The selected normalized record is absent.
+ #[error("link update record `{0}` is missing")]
+ MissingParent(EntityKey),
+ /// The selected record field is absent.
+ #[error("link update field `{field}` is missing on `{parent}`")]
+ MissingField { parent: String, field: String },
+ /// The generated query entrypoint or variables are invalid.
+ #[error("invalid link update entrypoint: {0}")]
+ InvalidEntrypoint(String),
+ /// A response-key path field was not selected by the query.
+ #[error("query does not select `{field}` on `{type_name}`")]
+ UnselectedField { type_name: String, field: String },
+ /// A path step encountered a value of the wrong shape.
+ #[error("link patch path encountered an incompatible cache value")]
+ WrongShape,
+ /// A traversed list exceeds the defensive limit.
+ #[error("link patch traversed list length {actual} exceeds limit {maximum}")]
+ ListTooLarge { actual: usize, maximum: usize },
+ /// A list selector did not resolve exactly one embedded object.
+ #[error("link patch list selector matched {0} items instead of exactly one")]
+ SelectorMatchCount(usize),
+ /// A selector value is not a JSON scalar.
+ #[error("link patch selector values must be JSON scalars")]
+ NonScalarSelector,
+ /// The final list contains values other than normalized refs or nulls.
+ #[error("link patch target list contains non-link values")]
+ NonLinkTarget,
+}
+
+/// Removes exact duplicate recipes while retaining the first occurrence and
+/// preserving caller order for conflicting operations.
+pub fn deduplicate_patches(
+ patches: &[OptimisticLinkPatch],
+) -> Result<Vec<OptimisticLinkPatch>, LinkPatchError> {
+ if patches.len() > MAX_PATCHES {
+ return Err(LinkPatchError::TooManyPatches {
+ actual: patches.len(),
+ maximum: MAX_PATCHES,
+ });
+ }
+ let mut seen = BTreeSet::new();
+ let mut out = Vec::with_capacity(patches.len());
+ for patch in patches {
+ validate_recipe(patch)?;
+ let encoded = serde_json::to_value(patch).expect("link patch serializes");
+ if seen.insert(canonical_json(&encoded)) {
+ out.push(patch.clone());
+ }
+ }
+ Ok(out)
+}
+
+fn validate_recipe(patch: &OptimisticLinkPatch) -> Result<(), LinkPatchError> {
+ if patch.path.is_empty() || patch.path.len() > MAX_PATH_DEPTH {
+ return Err(LinkPatchError::InvalidDepth(patch.path.len()));
+ }
+ validate_entrypoint(patch)?;
+ validate_entity_key(patch.operation.entity_key())?;
+ for segment in &patch.path {
+ if let LinkPathSegment::ListItem { list_item } = segment
+ && !is_json_scalar(&list_item.equals)
+ {
+ return Err(LinkPatchError::NonScalarSelector);
+ }
+ }
+ Ok(())
+}
+
+fn validate_entrypoint(
+ patch: &OptimisticLinkPatch,
+) -> Result<serde_json::Map<String, Json>, LinkPatchError> {
+ let document = Document::parse(&patch.query)
+ .map_err(|error| LinkPatchError::InvalidEntrypoint(error.to_string()))?;
+ let operation = document
+ .operation(patch.operation_name.as_deref())
+ .map_err(|error| LinkPatchError::InvalidEntrypoint(error.to_string()))?;
+ if operation.kind != OperationKind::Query {
+ return Err(LinkPatchError::InvalidEntrypoint(
+ "link update entrypoint must be a query".to_string(),
+ ));
+ }
+ let variables: Json = serde_json::from_str(&patch.variables_json)
+ .map_err(|error| LinkPatchError::InvalidEntrypoint(error.to_string()))?;
+ let Json::Object(variables) = variables else {
+ return Err(LinkPatchError::InvalidEntrypoint(
+ "entrypoint variables must be an object".to_string(),
+ ));
+ };
+ Ok(variables)
+}
+
+fn validate_entity_key(key: &EntityKey) -> Result<(), LinkPatchError> {
+ let Some((typename, value)) = key.0.split_once(':') else {
+ return Err(LinkPatchError::InvalidEntityKey(key.0.clone()));
+ };
+ let valid_name = !typename.is_empty()
+ && typename.chars().enumerate().all(|(index, ch)| {
+ ch == '_' || ch.is_ascii_alphabetic() || (index > 0 && ch.is_ascii_digit())
+ });
+ if !valid_name || value.is_empty() || value.chars().any(char::is_whitespace) {
+ return Err(LinkPatchError::InvalidEntityKey(key.0.clone()));
+ }
+ Ok(())
+}
+
+fn is_json_scalar(value: &Json) -> bool {
+ matches!(
+ value,
+ Json::Null | Json::Bool(_) | Json::Number(_) | Json::String(_)
+ )
+}
+
+/// Applies an already ordered patch set against effective records and writes
+/// only changed parent fields into `updates`.
+///
+/// When `skip_not_applicable` is true, stale/missing recipes are ignored. This
+/// mode is used during hydration and successful settlement, where stale query
+/// fields must never be recreated.
+pub fn apply_link_patches(
+ effective: &mut HashMap<EntityKey, Record>,
+ updates: &mut RecordUpdates,
+ patches: &[OptimisticLinkPatch],
+ skip_not_applicable: bool,
+) -> Result<(), LinkPatchError> {
+ let patches = deduplicate_patches(patches)?;
+
+ // Work on clones so strict validation is all-or-nothing.
+ let mut staged_effective = effective.clone();
+ let mut staged_updates = updates.clone();
+ for patch in &patches {
+ if let Err(error) = apply_one(&mut staged_effective, &mut staged_updates, patch) {
+ if skip_not_applicable {
+ continue;
+ }
+ return Err(error);
+ }
+ }
+ *effective = staged_effective;
+ *updates = staged_updates;
+ Ok(())
+}
+
+fn apply_one(
+ effective: &mut HashMap<EntityKey, Record>,
+ updates: &mut RecordUpdates,
+ patch: &OptimisticLinkPatch,
+) -> Result<(), LinkPatchError> {
+ let resolved = resolve_target(effective, patch)?;
+ let record = effective
+ .get_mut(&resolved.parent_entity_key)
+ .ok_or_else(|| LinkPatchError::MissingParent(resolved.parent_entity_key.clone()))?;
+ let mut field_value = record
+ .fields
+ .get(&resolved.field_key)
+ .cloned()
+ .ok_or_else(|| LinkPatchError::MissingField {
+ parent: resolved.parent_entity_key.0.clone(),
+ field: resolved.field_key.clone(),
+ })?;
+ let target = traverse(&mut field_value, &resolved.path)?;
+ let CacheValue::List(links) = target else {
+ return Err(LinkPatchError::WrongShape);
+ };
+ if links.len() > MAX_TRAVERSED_LIST {
+ return Err(LinkPatchError::ListTooLarge {
+ actual: links.len(),
+ maximum: MAX_TRAVERSED_LIST,
+ });
+ }
+ if links
+ .iter()
+ .any(|value| !matches!(value, CacheValue::Ref(_) | CacheValue::Null))
+ {
+ return Err(LinkPatchError::NonLinkTarget);
+ }
+
+ let entity_key = patch.operation.entity_key();
+ links.retain(|value| !matches!(value, CacheValue::Ref(key) if key == entity_key));
+ if matches!(patch.operation, LinkOperation::PrependUnique { .. }) {
+ links.insert(0, CacheValue::Ref(entity_key.clone()));
+ }
+
+ record
+ .fields
+ .insert(resolved.field_key.clone(), field_value.clone());
+ updates
+ .entry(resolved.parent_entity_key)
+ .or_default()
+ .fields
+ .insert(resolved.field_key, field_value);
+ Ok(())
+}
+
+#[derive(Debug)]
+struct ResolvedTarget {
+ parent_entity_key: EntityKey,
+ field_key: FieldKey,
+ path: Vec<LinkPathSegment>,
+}
+
+/// Returns the next normalized record required to resolve one query-rooted
+/// update. Engines use this to hydrate graph links from cold storage before
+/// applying the update.
+pub fn missing_patch_record(
+ effective: &HashMap<EntityKey, Record>,
+ patch: &OptimisticLinkPatch,
+) -> Option<EntityKey> {
+ match resolve_target(effective, patch) {
+ Err(LinkPatchError::MissingParent(key)) => Some(key),
+ _ => None,
+ }
+}
+
+fn resolve_target(
+ effective: &HashMap<EntityKey, Record>,
+ patch: &OptimisticLinkPatch,
+) -> Result<ResolvedTarget, LinkPatchError> {
+ let variables = validate_entrypoint(patch)?;
+ let document = Document::parse(&patch.query)
+ .map_err(|error| LinkPatchError::InvalidEntrypoint(error.to_string()))?;
+ let operation = document
+ .operation(patch.operation_name.as_deref())
+ .map_err(|error| LinkPatchError::InvalidEntrypoint(error.to_string()))?;
+ resolve_from_record(
+ effective,
+ &EntityKey::root(),
+ meta::QUERY_ROOT_TYPE,
+ &operation.selection_set,
+ &variables,
+ &patch.path,
+ )
+}
+
+fn resolve_from_record(
+ effective: &HashMap<EntityKey, Record>,
+ owner: &EntityKey,
+ type_name: &str,
+ selections: &[Selection],
+ variables: &serde_json::Map<String, Json>,
+ path: &[LinkPathSegment],
+) -> Result<ResolvedTarget, LinkPatchError> {
+ let Some(LinkPathSegment::Field {
+ field: response_key,
+ }) = path.first()
+ else {
+ return Err(LinkPatchError::WrongShape);
+ };
+ let record = effective
+ .get(owner)
+ .ok_or_else(|| LinkPatchError::MissingParent(owner.clone()))?;
+ let concrete = record.typename().unwrap_or(type_name);
+ let selected = selected_field(selections, concrete, response_key)?;
+ let storage_key = selected_storage_key(selected, variables)?;
+ let value = record
+ .fields
+ .get(&storage_key)
+ .ok_or_else(|| LinkPatchError::MissingField {
+ parent: owner.0.clone(),
+ field: storage_key.clone(),
+ })?;
+ let named_type = selected_type(concrete, selected)?;
+ resolve_from_value(
+ effective,
+ variables,
+ ValueCursor {
+ value,
+ owner: owner.clone(),
+ anchor_field: storage_key,
+ relative_path: Vec::new(),
+ type_name: named_type,
+ selections: &selected.selection_set,
+ },
+ &path[1..],
+ )
+}
+
+struct ValueCursor<'a> {
+ value: &'a CacheValue,
+ owner: EntityKey,
+ anchor_field: FieldKey,
+ relative_path: Vec<LinkPathSegment>,
+ type_name: &'a str,
+ selections: &'a [Selection],
+}
+
+fn resolve_from_value(
+ effective: &HashMap<EntityKey, Record>,
+ variables: &serde_json::Map<String, Json>,
+ cursor: ValueCursor<'_>,
+ path: &[LinkPathSegment],
+) -> Result<ResolvedTarget, LinkPatchError> {
+ if path.is_empty() {
+ return Ok(ResolvedTarget {
+ parent_entity_key: cursor.owner,
+ field_key: cursor.anchor_field,
+ path: cursor.relative_path,
+ });
+ }
+
+ if let CacheValue::Ref(key) = cursor.value {
+ return resolve_from_record(
+ effective,
+ key,
+ cursor.type_name,
+ cursor.selections,
+ variables,
+ path,
+ );
+ }
+
+ match (&path[0], cursor.value) {
+ (
+ LinkPathSegment::Field {
+ field: response_key,
+ },
+ CacheValue::Object(object),
+ ) => {
+ let concrete = object
+ .get("__typename")
+ .and_then(|value| match value {
+ CacheValue::String(value) => Some(value.as_str()),
+ _ => None,
+ })
+ .unwrap_or(cursor.type_name);
+ let selected = selected_field(cursor.selections, concrete, response_key)?;
+ let storage_key = selected_storage_key(selected, variables)?;
+ let child = object.get(&storage_key).ok_or(LinkPatchError::WrongShape)?;
+ let mut child_path = cursor.relative_path;
+ child_path.push(LinkPathSegment::Field {
+ field: storage_key.clone(),
+ });
+ resolve_from_value(
+ effective,
+ variables,
+ ValueCursor {
+ value: child,
+ owner: cursor.owner,
+ anchor_field: cursor.anchor_field,
+ relative_path: child_path,
+ type_name: selected_type(concrete, selected)?,
+ selections: &selected.selection_set,
+ },
+ &path[1..],
+ )
+ }
+ (LinkPathSegment::ListItem { list_item }, CacheValue::List(items)) => {
+ if items.len() > MAX_TRAVERSED_LIST {
+ return Err(LinkPatchError::ListTooLarge {
+ actual: items.len(),
+ maximum: MAX_TRAVERSED_LIST,
+ });
+ }
+ let selector =
+ selected_field(cursor.selections, cursor.type_name, &list_item.where_field)?;
+ let selector_key = selected_storage_key(selector, variables)?;
+ let matches: Vec<_> = items
+ .iter()
+ .enumerate()
+ .filter_map(|(index, value)| {
+ let CacheValue::Object(object) = value else {
+ return None;
+ };
+ object
+ .get(&selector_key)
+ .is_some_and(|value| cache_scalar_equals(value, &list_item.equals))
+ .then_some(index)
+ })
+ .collect();
+ if matches.len() != 1 {
+ return Err(LinkPatchError::SelectorMatchCount(matches.len()));
+ }
+ let mut item_path = cursor.relative_path;
+ item_path.push(LinkPathSegment::ListItem {
+ list_item: ListItemByScalar {
+ where_field: selector_key,
+ equals: list_item.equals.clone(),
+ },
+ });
+ resolve_from_value(
+ effective,
+ variables,
+ ValueCursor {
+ value: &items[matches[0]],
+ owner: cursor.owner,
+ anchor_field: cursor.anchor_field,
+ relative_path: item_path,
+ type_name: cursor.type_name,
+ selections: cursor.selections,
+ },
+ &path[1..],
+ )
+ }
+ _ => Err(LinkPatchError::WrongShape),
+ }
+}
+
+fn selected_field<'a>(
+ selections: &'a [Selection],
+ concrete: &str,
+ response_key: &str,
+) -> Result<&'a FieldNode, LinkPatchError> {
+ find_selected_field(selections, concrete, response_key).ok_or_else(|| {
+ LinkPatchError::UnselectedField {
+ type_name: concrete.to_string(),
+ field: response_key.to_string(),
+ }
+ })
+}
+
+fn selected_storage_key(
+ field: &FieldNode,
+ variables: &serde_json::Map<String, Json>,
+) -> Result<FieldKey, LinkPatchError> {
+ resolve_selected_storage_key(field, variables)
+ .map_err(|error| LinkPatchError::InvalidEntrypoint(error.to_string()))
+}
+
+fn selected_type(concrete: &str, field: &FieldNode) -> Result<&'static str, LinkPatchError> {
+ resolve_selected_type(concrete, field).ok_or_else(|| LinkPatchError::UnselectedField {
+ type_name: concrete.to_string(),
+ field: field.response_key.clone(),
+ })
+}
+
+fn traverse<'a>(
+ mut current: &'a mut CacheValue,
+ path: &[LinkPathSegment],
+) -> Result<&'a mut CacheValue, LinkPatchError> {
+ for segment in path {
+ current = match segment {
+ LinkPathSegment::Field { field } => {
+ let CacheValue::Object(object) = current else {
+ return Err(LinkPatchError::WrongShape);
+ };
+ object.get_mut(field).ok_or(LinkPatchError::WrongShape)?
+ }
+ LinkPathSegment::ListItem { list_item } => {
+ let CacheValue::List(items) = current else {
+ return Err(LinkPatchError::WrongShape);
+ };
+ if items.len() > MAX_TRAVERSED_LIST {
+ return Err(LinkPatchError::ListTooLarge {
+ actual: items.len(),
+ maximum: MAX_TRAVERSED_LIST,
+ });
+ }
+ let matches: Vec<usize> = items
+ .iter()
+ .enumerate()
+ .filter_map(|(index, value)| {
+ let CacheValue::Object(object) = value else {
+ return None;
+ };
+ object
+ .get(&list_item.where_field)
+ .is_some_and(|value| cache_scalar_equals(value, &list_item.equals))
+ .then_some(index)
+ })
+ .collect();
+ if matches.len() != 1 {
+ return Err(LinkPatchError::SelectorMatchCount(matches.len()));
+ }
+ &mut items[matches[0]]
+ }
+ };
+ }
+ Ok(current)
+}
+
+fn cache_scalar_equals(value: &CacheValue, expected: &Json) -> bool {
+ match (value, expected) {
+ (CacheValue::Null, Json::Null) => true,
+ (CacheValue::Bool(actual), Json::Bool(expected)) => actual == expected,
+ (CacheValue::String(actual), Json::String(expected)) => actual == expected,
+ (CacheValue::Number(actual), Json::Number(expected)) => {
+ cache_number_equals_json(*actual, expected)
+ }
+ _ => false,
+ }
+}
+
+fn cache_number_equals_json(actual: CacheNumber, expected: &serde_json::Number) -> bool {
+ actual.to_json() == *expected
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+ use std::collections::BTreeMap;
+
+ const QUERY: &str = "query { user { groupSoup { bins { key items { id } } } } }";
+
+ fn record() -> (EntityKey, Record) {
+ let parent = EntityKey("GraphqlUser:user-1".into());
+ let bin = |key: &str, items: Vec<CacheValue>| {
+ CacheValue::Object(BTreeMap::from([
+ ("key".into(), CacheValue::String(key.into())),
+ ("items".into(), CacheValue::List(items)),
+ ]))
+ };
+ let grouped = CacheValue::Object(BTreeMap::from([(
+ "bins".into(),
+ CacheValue::List(vec![
+ bin(
+ "in-progress",
+ vec![
+ CacheValue::Ref(EntityKey("GraphqlSoupItem:task-1".into())),
+ CacheValue::Ref(EntityKey("GraphqlSoupItem:task-1".into())),
+ ],
+ ),
+ bin("completed", vec![]),
+ ]),
+ )]));
+ let record = Record {
+ fields: BTreeMap::from([("groupSoup".into(), grouped)]),
+ };
+ (parent, record)
+ }
+
+ fn patch(bin: &str, operation: LinkOperation) -> OptimisticLinkPatch {
+ OptimisticLinkPatch {
+ query: QUERY.into(),
+ operation_name: None,
+ variables_json: "{}".into(),
+ path: vec![
+ LinkPathSegment::Field {
+ field: "user".into(),
+ },
+ LinkPathSegment::Field {
+ field: "groupSoup".into(),
+ },
+ LinkPathSegment::Field {
+ field: "bins".into(),
+ },
+ LinkPathSegment::ListItem {
+ list_item: ListItemByScalar {
+ where_field: "key".into(),
+ equals: json!(bin),
+ },
+ },
+ LinkPathSegment::Field {
+ field: "items".into(),
+ },
+ ],
+ operation,
+ }
+ }
+
+ #[test]
+ fn remove_and_prepend_compose_without_touching_unrelated_values() {
+ let (parent, initial) = record();
+ let mut effective = HashMap::from([
+ (
+ EntityKey::root(),
+ Record {
+ fields: BTreeMap::from([("user".into(), CacheValue::Ref(parent.clone()))]),
+ },
+ ),
+ (parent.clone(), initial.clone()),
+ ]);
+ let mut updates = RecordUpdates::new();
+ apply_link_patches(
+ &mut effective,
+ &mut updates,
+ &[
+ patch(
+ "in-progress",
+ LinkOperation::Remove {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ ),
+ patch(
+ "completed",
+ LinkOperation::PrependUnique {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ ),
+ ],
+ false,
+ )
+ .unwrap();
+
+ let changed = effective.get(&parent).unwrap();
+ assert_ne!(changed, &initial);
+ let CacheValue::Object(grouped) = &changed.fields["groupSoup"] else {
+ panic!()
+ };
+ let CacheValue::List(bins) = &grouped["bins"] else {
+ panic!()
+ };
+ let CacheValue::Object(source) = &bins[0] else {
+ panic!()
+ };
+ assert_eq!(source["items"], CacheValue::List(vec![]));
+ let CacheValue::Object(destination) = &bins[1] else {
+ panic!()
+ };
+ assert_eq!(
+ destination["items"],
+ CacheValue::List(vec![CacheValue::Ref(EntityKey(
+ "GraphqlSoupItem:task-1".into()
+ ))])
+ );
+ assert_eq!(updates.len(), 1);
+ }
+
+ #[test]
+ fn strict_patch_set_has_no_partial_writes() {
+ let (parent, initial) = record();
+ let mut effective = HashMap::from([
+ (
+ EntityKey::root(),
+ Record {
+ fields: BTreeMap::from([("user".into(), CacheValue::Ref(parent.clone()))]),
+ },
+ ),
+ (parent, initial.clone()),
+ ]);
+ let mut updates = RecordUpdates::new();
+ let result = apply_link_patches(
+ &mut effective,
+ &mut updates,
+ &[
+ patch(
+ "in-progress",
+ LinkOperation::Remove {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ ),
+ patch(
+ "missing",
+ LinkOperation::PrependUnique {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ ),
+ ],
+ false,
+ );
+ assert_eq!(result, Err(LinkPatchError::SelectorMatchCount(0)));
+ assert_eq!(
+ effective.get(&EntityKey("GraphqlUser:user-1".into())),
+ Some(&initial)
+ );
+ assert!(updates.is_empty());
+ }
+
+ #[test]
+ fn rejects_non_ref_target_and_invalid_keys() {
+ let (parent, mut initial) = record();
+ let CacheValue::Object(grouped) = initial.fields.get_mut("groupSoup").unwrap() else {
+ panic!()
+ };
+ let CacheValue::List(bins) = grouped.get_mut("bins").unwrap() else {
+ panic!()
+ };
+ let CacheValue::Object(source) = &mut bins[0] else {
+ panic!()
+ };
+ source.insert(
+ "items".into(),
+ CacheValue::List(vec![CacheValue::String("bad".into())]),
+ );
+ let mut effective = HashMap::from([
+ (
+ EntityKey::root(),
+ Record {
+ fields: BTreeMap::from([("user".into(), CacheValue::Ref(parent.clone()))]),
+ },
+ ),
+ (parent, initial),
+ ]);
+ let mut updates = RecordUpdates::new();
+ assert_eq!(
+ apply_link_patches(
+ &mut effective,
+ &mut updates,
+ &[patch(
+ "in-progress",
+ LinkOperation::Remove {
+ entity_key: EntityKey("bad".into())
+ }
+ )],
+ false,
+ ),
+ Err(LinkPatchError::InvalidEntityKey("bad".into()))
+ );
+ }
+}
diff --git a/crates/client/cache-core/src/query_inspection.rs b/crates/client/cache-core/src/query_inspection.rs
new file mode 100644
index 0000000000..23483cab41
--- /dev/null
+++ b/crates/client/cache-core/src/query_inspection.rs
@@ -0,0 +1,423 @@
+//! Typed-query cache inspection primitives.
+//!
+//! Inspection discovers argument-qualified instances of one selected field
+//! without exposing normalized entity or field keys to host callers.
+
+use crate::document::{ArgValue, FieldNode, Operation, OperationKind, Selection, resolve_args_key};
+use crate::meta::{self, FieldKind};
+use crate::query_path::{
+ possible_selected_fields, selected_field, selected_storage_key, selected_type,
+};
+use crate::value::{CacheValue, EntityKey, Record, canonical_json};
+use serde::Serialize;
+use serde_json::Value as Json;
+use std::collections::{BTreeMap, BTreeSet, HashMap};
+use thiserror::Error;
+
+#[cfg(test)]
+mod test;
+
+/// Maximum field-only path depth accepted by query inspection.
+pub const MAX_INSPECTION_PATH_DEPTH: usize = 16;
+/// Maximum cached argument variants returned by one inspection.
+pub const MAX_INSPECTED_VARIANTS: usize = 128;
+
+/// A generated query and selected response-key path to inspect.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct QueryInspection {
+ /// Serialized GraphQL operation document.
+ pub query: String,
+ /// Selected operation for multi-operation documents.
+ pub operation_name: Option<String>,
+ /// Field-only response-key path beginning at the query root.
+ pub path: Vec<String>,
+}
+
+/// One cached argument variant reconstructed as generated query variables.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CachedQueryInstance {
+ /// Variables recovered from the selected field's normalized arguments.
+ pub variables: serde_json::Map<String, Json>,
+ /// Selected value in the effective cache view. Absent on a query miss.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub value: Option<Json>,
+}
+
+/// Validation or traversal failure for query inspection.
+#[derive(Debug, Clone, PartialEq, Eq, Error)]
+pub enum QueryInspectionError {
+ /// The selected operation is not a query.
+ #[error("query inspection entrypoint must be a query")]
+ NotQuery,
+ /// The path is empty or exceeds the defensive limit.
+ #[error("invalid query inspection path depth {0}")]
+ InvalidDepth(usize),
+ /// A response key is not selected at the current schema type.
+ #[error("query does not select `{field}` on `{type_name}`")]
+ UnselectedField { type_name: String, field: String },
+ /// More than one selected field can supply a response key.
+ #[error("query inspection path `{field}` is ambiguous on `{type_name}`")]
+ AmbiguousField { type_name: String, field: String },
+ /// A prefix path field depends on operation variables.
+ #[error("query inspection prefix field `{0}` contains an unbound variable")]
+ VariablePrefix(String),
+ /// An operation variable cannot be recovered from the final field.
+ #[error("operation variable `{0}` cannot be recovered from the inspected field")]
+ UnrecoverableVariable(String),
+ /// The final selected field is not an object-valued field.
+ #[error("query inspection final field must select an object value")]
+ NonCompositeFinalField,
+ /// A path field cannot be traversed as an object.
+ #[error("query inspection path encountered an incompatible cache value")]
+ WrongShape,
+ /// The selected field owner has too many cached argument variants.
+ #[error("query inspection variant count {actual} exceeds limit {maximum}")]
+ TooManyVariants { actual: usize, maximum: usize },
+ /// A complete query result unexpectedly lacks the validated path.
+ #[error("complete query result does not contain the inspected path")]
+ MissingResultPath,
+}
+
+/// Validated information needed to enumerate an inspection.
+pub(crate) struct PreparedInspection {
+ required_variables: BTreeSet<String>,
+}
+
+/// The effective owner record and final selected field.
+pub(crate) struct InspectionOwner {
+ pub fields: BTreeMap<String, CacheValue>,
+ pub field: FieldNode,
+}
+
+/// Result of resolving the owner through currently loaded effective records.
+pub(crate) enum OwnerResolution {
+ Owner(InspectionOwner),
+ NeedRecord(EntityKey),
+ Absent,
+}
+
+/// Validates the query-rooted path and variable recoverability constraints.
+pub(crate) fn prepare(
+ operation: &Operation,
+ path: &[String],
+) -> Result<PreparedInspection, QueryInspectionError> {
+ if operation.kind != OperationKind::Query {
+ return Err(QueryInspectionError::NotQuery);
+ }
+ if path.is_empty() || path.len() > MAX_INSPECTION_PATH_DEPTH {
+ return Err(QueryInspectionError::InvalidDepth(path.len()));
+ }
+
+ let mut selections = operation.selection_set.as_slice();
+ let mut type_name = meta::QUERY_ROOT_TYPE;
+ let mut final_variables = BTreeSet::new();
+ for (index, response_key) in path.iter().enumerate() {
+ let mut fields = Vec::new();
+ possible_selected_fields(selections, type_name, response_key, &mut fields);
+ let field = match fields.as_slice() {
+ [] => {
+ return Err(QueryInspectionError::UnselectedField {
+ type_name: type_name.to_string(),
+ field: response_key.clone(),
+ });
+ }
+ [field] => *field,
+ _ => {
+ return Err(QueryInspectionError::AmbiguousField {
+ type_name: type_name.to_string(),
+ field: response_key.clone(),
+ });
+ }
+ };
+
+ let mut variables = BTreeSet::new();
+ collect_field_variables(field, &mut variables);
+ if index + 1 == path.len() {
+ final_variables = variables;
+ } else if !variables.is_empty() {
+ return Err(QueryInspectionError::VariablePrefix(response_key.clone()));
+ }
+
+ let Some(metadata) = meta::field_meta(type_name, &field.name) else {
+ return Err(QueryInspectionError::UnselectedField {
+ type_name: type_name.to_string(),
+ field: response_key.clone(),
+ });
+ };
+ if metadata.ty.kind != FieldKind::Composite {
+ return if index + 1 == path.len() {
+ Err(QueryInspectionError::NonCompositeFinalField)
+ } else {
+ Err(QueryInspectionError::WrongShape)
+ };
+ }
+ type_name = metadata.ty.name;
+ selections = &field.selection_set;
+ }
+
+ let mut required_variables = BTreeSet::new();
+ collect_selection_variables(&operation.selection_set, &mut required_variables);
+ if let Some(variable) = required_variables
+ .iter()
+ .find(|variable| !final_variables.contains(*variable))
+ {
+ return Err(QueryInspectionError::UnrecoverableVariable(
+ variable.clone(),
+ ));
+ }
+
+ Ok(PreparedInspection { required_variables })
+}
+
+/// Resolves the record/object that owns the final selected field.
+pub(crate) fn resolve_owner(
+ records: &HashMap<EntityKey, Record>,
+ operation: &Operation,
+ path: &[String],
+) -> Result<OwnerResolution, QueryInspectionError> {
+ resolve_record_owner(
+ records,
+ &EntityKey::root(),
+ meta::QUERY_ROOT_TYPE,
+ &operation.selection_set,
+ path,
+ )
+}
+
+fn resolve_record_owner(
+ records: &HashMap<EntityKey, Record>,
+ key: &EntityKey,
+ declared_type: &str,
+ selections: &[Selection],
+ path: &[String],
+) -> Result<OwnerResolution, QueryInspectionError> {
+ let Some(record) = records.get(key) else {
+ return Ok(OwnerResolution::NeedRecord(key.clone()));
+ };
+ let concrete = record.typename().unwrap_or(declared_type);
+ resolve_fields_owner(records, &record.fields, concrete, selections, path)
+}
+
+fn resolve_fields_owner(
+ records: &HashMap<EntityKey, Record>,
+ fields: &BTreeMap<String, CacheValue>,
+ concrete: &str,
+ selections: &[Selection],
+ path: &[String],
+) -> Result<OwnerResolution, QueryInspectionError> {
+ let response_key = &path[0];
+ let Some(field) = selected_field(selections, concrete, response_key) else {
+ return Ok(OwnerResolution::Absent);
+ };
+ if path.len() == 1 {
+ return Ok(OwnerResolution::Owner(InspectionOwner {
+ fields: fields.clone(),
+ field: field.clone(),
+ }));
+ }
+
+ let storage_key = selected_storage_key(field, &serde_json::Map::new())
+ .map_err(|_| QueryInspectionError::VariablePrefix(response_key.clone()))?;
+ let Some(value) = fields.get(&storage_key) else {
+ return Ok(OwnerResolution::Absent);
+ };
+ let next_type =
+ selected_type(concrete, field).ok_or_else(|| QueryInspectionError::UnselectedField {
+ type_name: concrete.to_string(),
+ field: response_key.clone(),
+ })?;
+ match value {
+ CacheValue::Ref(key) => {
+ resolve_record_owner(records, key, next_type, &field.selection_set, &path[1..])
+ }
+ CacheValue::Object(object) => {
+ let concrete = object
+ .get("__typename")
+ .and_then(|value| match value {
+ CacheValue::String(value) => Some(value.as_str()),
+ _ => None,
+ })
+ .unwrap_or(next_type);
+ resolve_fields_owner(records, object, concrete, &field.selection_set, &path[1..])
+ }
+ CacheValue::Null => Ok(OwnerResolution::Absent),
+ _ => Err(QueryInspectionError::WrongShape),
+ }
+}
+
+/// Recovers and canonically deduplicates variables from matching owner fields.
+pub(crate) fn recover_variants(
+ owner: &InspectionOwner,
+ prepared: &PreparedInspection,
+) -> Result<Vec<serde_json::Map<String, Json>>, QueryInspectionError> {
+ let mut matching = 0usize;
+ let mut unique = BTreeMap::new();
+ for storage_key in owner.fields.keys() {
+ let Some(stored_arguments) = parse_stored_arguments(storage_key, &owner.field.name) else {
+ continue;
+ };
+ matching += 1;
+ if matching > MAX_INSPECTED_VARIANTS {
+ return Err(QueryInspectionError::TooManyVariants {
+ actual: matching,
+ maximum: MAX_INSPECTED_VARIANTS,
+ });
+ }
+ let Some(variables) = invert_arguments(&owner.field, &stored_arguments) else {
+ continue;
+ };
+ if prepared
+ .required_variables
+ .iter()
+ .any(|variable| !variables.contains_key(variable))
+ {
+ continue;
+ }
+ let key = canonical_json(&Json::Object(variables.clone()));
+ unique.entry(key).or_insert(variables);
+ }
+ Ok(unique.into_values().collect())
+}
+
+fn parse_stored_arguments(
+ storage_key: &str,
+ field_name: &str,
+) -> Option<serde_json::Map<String, Json>> {
+ if storage_key == field_name {
+ return Some(serde_json::Map::new());
+ }
+ let encoded = storage_key
+ .strip_prefix(field_name)?
+ .strip_prefix('(')?
+ .strip_suffix(')')?;
+ let Json::Object(arguments) = serde_json::from_str(encoded).ok()? else {
+ return None;
+ };
+ Some(arguments)
+}
+
+fn invert_arguments(
+ field: &FieldNode,
+ stored: &serde_json::Map<String, Json>,
+) -> Option<serde_json::Map<String, Json>> {
+ if stored.len() != field.arguments.len() {
+ return None;
+ }
+ let mut variables = serde_json::Map::new();
+ for (name, expression) in &field.arguments {
+ bind_expression(expression, stored.get(name)?, &mut variables)?;
+ }
+ let resolved = resolve_args_key(field, &variables).ok()?;
+ let resolved = resolved
+ .as_deref()
+ .map(|arguments| format!("{}({arguments})", field.name))
+ .unwrap_or_else(|| field.name.clone());
+ let stored_key = if stored.is_empty() {
+ field.name.clone()
+ } else {
+ format!(
+ "{}({})",
+ field.name,
+ canonical_json(&Json::Object(stored.clone()))
+ )
+ };
+ (resolved == stored_key).then_some(variables)
+}
+
+fn bind_expression(
+ expression: &ArgValue,
+ stored: &Json,
+ variables: &mut serde_json::Map<String, Json>,
+) -> Option<()> {
+ match expression {
+ ArgValue::Const(expected) => (expected == stored).then_some(()),
+ ArgValue::Variable(name) => match variables.get(name) {
+ Some(bound) => (bound == stored).then_some(()),
+ None => {
+ variables.insert(name.clone(), stored.clone());
+ Some(())
+ }
+ },
+ ArgValue::List(expressions) => {
+ let Json::Array(stored) = stored else {
+ return None;
+ };
+ if expressions.len() != stored.len() {
+ return None;
+ }
+ for (expression, stored) in expressions.iter().zip(stored) {
+ bind_expression(expression, stored, variables)?;
+ }
+ Some(())
+ }
+ ArgValue::Object(expressions) => {
+ let Json::Object(stored) = stored else {
+ return None;
+ };
+ if expressions.len() != stored.len() {
+ return None;
+ }
+ for (name, expression) in expressions {
+ bind_expression(expression, stored.get(name)?, variables)?;
+ }
+ Some(())
+ }
+ }
+}
+
+fn collect_selection_variables(selections: &[Selection], out: &mut BTreeSet<String>) {
+ for selection in selections {
+ match selection {
+ Selection::Field(field) => {
+ collect_field_variables(field, out);
+ collect_selection_variables(&field.selection_set, out);
+ }
+ Selection::Fragment { selection_set, .. } => {
+ collect_selection_variables(selection_set, out);
+ }
+ }
+ }
+}
+
+fn collect_field_variables(field: &FieldNode, out: &mut BTreeSet<String>) {
+ for (_, value) in &field.arguments {
+ collect_arg_variables(value, out);
+ }
+}
+
+fn collect_arg_variables(value: &ArgValue, out: &mut BTreeSet<String>) {
+ match value {
+ ArgValue::Variable(name) => {
+ out.insert(name.clone());
+ }
+ ArgValue::List(values) => {
+ for value in values {
+ collect_arg_variables(value, out);
+ }
+ }
+ ArgValue::Object(fields) => {
+ for (_, value) in fields {
+ collect_arg_variables(value, out);
+ }
+ }
+ ArgValue::Const(_) => {}
+ }
+}
+
+/// Extracts the selected value from one complete denormalized query result.
+pub(crate) fn selected_result_value(
+ data: &Json,
+ path: &[String],
+) -> Result<Json, QueryInspectionError> {
+ let mut current = data;
+ for field in path {
+ let Json::Object(object) = current else {
+ return Err(QueryInspectionError::MissingResultPath);
+ };
+ current = object
+ .get(field)
+ .ok_or(QueryInspectionError::MissingResultPath)?;
+ }
+ Ok(current.clone())
+}
diff --git a/crates/client/cache-core/src/query_inspection/test.rs b/crates/client/cache-core/src/query_inspection/test.rs
new file mode 100644
index 0000000000..0110b7a102
--- /dev/null
+++ b/crates/client/cache-core/src/query_inspection/test.rs
@@ -0,0 +1,31 @@
+use super::*;
+
+#[test]
+fn concrete_union_member_outside_selected_fragment_is_absent() {
+ let fields = BTreeMap::from([(
+ "__typename".to_string(),
+ CacheValue::String("GraphqlSoupChannel".to_string()),
+ )]);
+ // These are selections beneath the GraphqlSoupEntity union. The cached
+ // channel does not match the document-only fragment containing properties.
+ let selections = vec![Selection::Fragment {
+ type_condition: Some("GraphqlSoupDocument".to_string()),
+ selection_set: vec![Selection::Field(FieldNode {
+ response_key: "properties".to_string(),
+ name: "properties".to_string(),
+ arguments: Vec::new(),
+ selection_set: Vec::new(),
+ })],
+ }];
+
+ let result = resolve_fields_owner(
+ &HashMap::new(),
+ &fields,
+ "GraphqlSoupChannel",
+ &selections,
+ &["properties".to_string()],
+ )
+ .unwrap();
+
+ assert!(matches!(result, OwnerResolution::Absent));
+}
diff --git a/crates/client/cache-core/src/query_path.rs b/crates/client/cache-core/src/query_path.rs
new file mode 100644
index 0000000000..8dde8bd2a0
--- /dev/null
+++ b/crates/client/cache-core/src/query_path.rs
@@ -0,0 +1,94 @@
+//! Shared GraphQL response-path helpers used by query-rooted cache APIs.
+
+use crate::document::{FieldNode, MissingVariable, Selection, resolve_args_key};
+use crate::meta;
+use crate::value::{FieldKey, field_key};
+use serde_json::Value as Json;
+
+/// Finds the first field selected under `response_key` for a concrete type.
+///
+/// GraphQL response-key merging is deliberately left to each caller: link
+/// patches retain their existing first-match behavior, while inspection
+/// performs a separate ambiguity check before traversal.
+pub(crate) fn selected_field<'a>(
+ selections: &'a [Selection],
+ concrete: &str,
+ response_key: &str,
+) -> Option<&'a FieldNode> {
+ for selection in selections {
+ match selection {
+ Selection::Field(field) if field.response_key == response_key => return Some(field),
+ Selection::Field(_) => {}
+ Selection::Fragment {
+ type_condition,
+ selection_set,
+ } if type_condition
+ .as_deref()
+ .is_none_or(|condition| meta::type_matches(concrete, condition)) =>
+ {
+ if let Some(field) = selected_field(selection_set, concrete, response_key) {
+ return Some(field);
+ }
+ }
+ Selection::Fragment { .. } => {}
+ }
+ }
+ None
+}
+
+/// Collects fields with a response key that can apply to `type_name`.
+///
+/// Unlike [`selected_field`], this treats abstract type overlaps as possible
+/// so inspection can reject ambiguous paths before consulting cache data.
+pub(crate) fn possible_selected_fields<'a>(
+ selections: &'a [Selection],
+ type_name: &str,
+ response_key: &str,
+ out: &mut Vec<&'a FieldNode>,
+) {
+ for selection in selections {
+ match selection {
+ Selection::Field(field) if field.response_key == response_key => out.push(field),
+ Selection::Field(_) => {}
+ Selection::Fragment {
+ type_condition,
+ selection_set,
+ } if type_condition
+ .as_deref()
+ .is_none_or(|condition| types_overlap(type_name, condition)) =>
+ {
+ possible_selected_fields(selection_set, type_name, response_key, out);
+ }
+ Selection::Fragment { .. } => {}
+ }
+ }
+}
+
+fn types_overlap(left: &str, right: &str) -> bool {
+ if left == right || meta::type_matches(left, right) || meta::type_matches(right, left) {
+ return true;
+ }
+ let Some(left) = meta::type_meta(left) else {
+ return false;
+ };
+ let Some(right) = meta::type_meta(right) else {
+ return false;
+ };
+ left.possible_types
+ .iter()
+ .any(|possible| right.possible_types.contains(possible))
+}
+
+/// Resolves one selected field to its normalized storage key.
+pub(crate) fn selected_storage_key(
+ field: &FieldNode,
+ variables: &serde_json::Map<String, Json>,
+) -> Result<FieldKey, MissingVariable> {
+ let arguments = resolve_args_key(field, variables)?;
+ Ok(field_key(&field.name, arguments.as_deref()))
+}
+
+/// Returns the named schema type selected by `field` on `concrete`.
+pub(crate) fn selected_type(concrete: &str, field: &FieldNode) -> Option<&'static str> {
+ meta::field_meta(concrete, &field.name).map(|metadata| metadata.ty.name)
+}
diff --git a/crates/client/cache-core/src/queue.rs b/crates/client/cache-core/src/queue.rs
index aec8f3c5be..377c73de39 100644
--- a/crates/client/cache-core/src/queue.rs
+++ b/crates/client/cache-core/src/queue.rs
@@ -5,8 +5,11 @@
//! credentials and urql operation context are deliberately excluded: replay
//! reconstructs an operation using the current client configuration.
+use crate::link_patch::{OptimisticLinkPatch, QueryRevalidation};
use crate::normalize::RecordUpdates;
+use crate::value::canonical_json;
use serde::{Deserialize, Serialize};
+use serde_json::Value as Json;
/// Durable, monotonically increasing mutation identifier and queue position.
pub type MutationId = u64;
@@ -61,11 +64,80 @@ impl StoredMutation {
}
}
+/// Current version of the durable optimistic source envelope.
+pub const OPTIMISTIC_SOURCE_VERSION: u8 = 2;
+
+const OPTIMISTIC_SOURCE_ENVELOPE_PREFIX: &str = "@macro-cache/optimistic-source:";
+
+/// Durable source needed to reconstruct one optimistic layer statefully.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct OptimisticSource {
+ /// Optimistic GraphQL mutation response.
+ pub mutation_data: Json,
+ /// Ordered constrained relation recipes.
+ #[serde(default)]
+ pub link_patches: Vec<OptimisticLinkPatch>,
+ /// Revalidations for relevant fields that could not be patched.
+ #[serde(default)]
+ pub revalidations: Vec<QueryRevalidation>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct OptimisticSourceEnvelope {
+ version: u8,
+ mutation_data: Json,
+ #[serde(default)]
+ link_patches: Vec<OptimisticLinkPatch>,
+ #[serde(default)]
+ revalidations: Vec<QueryRevalidation>,
+}
+
+/// Encodes an optimistic source with a reserved prefix and versioned JSON envelope.
+pub fn encode_optimistic_source(source: &OptimisticSource) -> String {
+ let envelope = canonical_json(
+ &serde_json::to_value(OptimisticSourceEnvelope {
+ version: OPTIMISTIC_SOURCE_VERSION,
+ mutation_data: source.mutation_data.clone(),
+ link_patches: source.link_patches.clone(),
+ revalidations: source.revalidations.clone(),
+ })
+ .expect("optimistic source serializes"),
+ );
+ format!("{OPTIMISTIC_SOURCE_ENVELOPE_PREFIX}{envelope}")
+}
+
+/// Decodes a versioned optimistic source, treating legacy raw JSON as the
+/// optimistic mutation response with no relation recipes.
+pub fn decode_optimistic_source(value: &str) -> Result<OptimisticSource, String> {
+ let Some(envelope) = value.strip_prefix(OPTIMISTIC_SOURCE_ENVELOPE_PREFIX) else {
+ return Ok(OptimisticSource {
+ mutation_data: serde_json::from_str(value).map_err(|error| error.to_string())?,
+ link_patches: Vec::new(),
+ revalidations: Vec::new(),
+ });
+ };
+ let envelope: OptimisticSourceEnvelope =
+ serde_json::from_str(envelope).map_err(|error| error.to_string())?;
+ if envelope.version != OPTIMISTIC_SOURCE_VERSION {
+ return Err(format!(
+ "unsupported optimistic source version {}",
+ envelope.version
+ ));
+ }
+ Ok(OptimisticSource {
+ mutation_data: envelope.mutation_data,
+ link_patches: envelope.link_patches,
+ revalidations: envelope.revalidations,
+ })
+}
+
/// One durable optimistic layer paired one-to-one with a queued mutation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PersistedOptimisticLayer {
- /// Canonical JSON optimistic response, retained for re-normalization after
- /// a record-schema change.
+ /// Encoded optimistic source, retained for re-normalization after a
+ /// record-schema change.
pub optimistic_data_json: String,
/// Normalized contribution used to hydrate the effective cache view.
pub normalized_updates: RecordUpdates,
diff --git a/crates/client/cache-core/src/store.rs b/crates/client/cache-core/src/store.rs
index e9c7148108..2374680f86 100644
--- a/crates/client/cache-core/src/store.rs
+++ b/crates/client/cache-core/src/store.rs
@@ -90,7 +90,7 @@ pub trait Storage: MaybeSend {
}
/// Hash-map storage for tests and as the Phase 1 default.
-#[derive(Debug, Default)]
+#[derive(Clone, Debug, Default)]
pub struct InMemoryStorage {
records: HashMap<EntityKey, Record>,
mutations: BTreeMap<
diff --git a/crates/client/cache-core/tests/grouped_optimistic.rs b/crates/client/cache-core/tests/grouped_optimistic.rs
new file mode 100644
index 0000000000..0a79034a3c
--- /dev/null
+++ b/crates/client/cache-core/tests/grouped_optimistic.rs
@@ -0,0 +1,405 @@
+//! GroupSoup nested-link optimistic transaction integration tests.
+
+use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult};
+use cache_core::link_patch::{
+ LinkOperation, LinkPathSegment, ListItemByScalar, OptimisticLinkPatch,
+};
+use cache_core::queue::{MutationClaimRequest, MutationClaimToken};
+use cache_core::store::InMemoryStorage;
+use cache_core::value::EntityKey;
+use pollster::block_on;
+use serde_json::{Value as Json, json};
+
+const GROUP_QUERY: &str = r#"
+query GroupSoup($input: GroupedSoupInput!) {
+ user {
+ id
+ groupSoup(input: $input) {
+ bins {
+ key
+ totalCount
+ nextCursor
+ items {
+ id
+ entity {
+ __typename
+ ... on GraphqlSoupDocument {
+ id
+ properties {
+ id
+ propertyDefinitionId
+ value {
+ __typename
+ ... on GraphqlSelectOptionPropertyValue { optionIds }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+"#;
+
+const MUTATION: &str = r#"
+mutation SetEntityProperty($input: SetEntityPropertyInput!) {
+ setEntityProperty(input: $input) {
+ id
+ propertyDefinitionId
+ value {
+ __typename
+ ... on GraphqlSelectOptionPropertyValue { optionIds }
+ }
+ }
+}
+"#;
+
+fn object(value: Json) -> serde_json::Map<String, Json> {
+ let Json::Object(value) = value else {
+ unreachable!()
+ };
+ value
+}
+
+fn query_variables() -> serde_json::Map<String, Json> {
+ object(json!({
+ "input": {
+ "groupBy": { "property": { "propertyDefinitionId": "status-def" } },
+ "limit": 20
+ }
+ }))
+}
+
+fn mutation_variables(option: &str) -> serde_json::Map<String, Json> {
+ object(json!({
+ "input": {
+ "entityType": "DOCUMENT",
+ "entityId": "task-1",
+ "propertyDefinitionId": "status-def",
+ "value": { "selectOption": option }
+ }
+ }))
+}
+
+fn property(option: &str) -> Json {
+ json!({
+ "id": "property-1",
+ "propertyDefinitionId": "status-def",
+ "value": {
+ "__typename": "GraphqlSelectOptionPropertyValue",
+ "optionIds": [option]
+ }
+ })
+}
+
+fn group_page() -> Json {
+ json!({
+ "user": {
+ "id": "user-1",
+ "groupSoup": {
+ "bins": [
+ {
+ "key": "in-progress",
+ "totalCount": 1,
+ "nextCursor": "source-cursor",
+ "items": [{
+ "id": "task-1",
+ "entity": {
+ "__typename": "GraphqlSoupDocument",
+ "id": "task-1",
+ "properties": [property("in-progress")]
+ }
+ }]
+ },
+ {
+ "key": "completed",
+ "totalCount": 0,
+ "nextCursor": "destination-cursor",
+ "items": []
+ }
+ ]
+ }
+ }
+ })
+}
+
+fn mutation_response(option: &str) -> Json {
+ json!({ "setEntityProperty": property(option) })
+}
+
+fn patch(bin: &str, operation: LinkOperation) -> OptimisticLinkPatch {
+ OptimisticLinkPatch {
+ query: GROUP_QUERY.into(),
+ operation_name: Some("GroupSoup".into()),
+ variables_json: serde_json::to_string(&query_variables()).unwrap(),
+ path: vec![
+ LinkPathSegment::Field {
+ field: "user".into(),
+ },
+ LinkPathSegment::Field {
+ field: "groupSoup".into(),
+ },
+ LinkPathSegment::Field {
+ field: "bins".into(),
+ },
+ LinkPathSegment::ListItem {
+ list_item: ListItemByScalar {
+ where_field: "key".into(),
+ equals: json!(bin),
+ },
+ },
+ LinkPathSegment::Field {
+ field: "items".into(),
+ },
+ ],
+ operation,
+ }
+}
+
+async fn read_group(engine: &mut Engine<InMemoryStorage>) -> Json {
+ match engine
+ .read_query(None, GROUP_QUERY, Some("GroupSoup"), &query_variables())
+ .await
+ .unwrap()
+ {
+ ReadResult::Hit { data } => data,
+ ReadResult::Miss => panic!("expected GroupSoup cache hit"),
+ }
+}
+
+async fn setup() -> Engine<InMemoryStorage> {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ engine
+ .write_query(
+ None,
+ GROUP_QUERY,
+ Some("GroupSoup"),
+ &query_variables(),
+ &group_page(),
+ None,
+ )
+ .await
+ .unwrap();
+ engine
+}
+
+async fn claim(engine: &mut Engine<InMemoryStorage>, id: u64) -> MutationClaimToken {
+ let claimed = engine
+ .claim_next_mutation(MutationClaimRequest {
+ owner: "runner".into(),
+ now_ms: 1,
+ lease_expires_at_ms: 100,
+ })
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(claimed.queued.id, id);
+ MutationClaimToken {
+ owner: "runner".into(),
+ generation: claimed.lease_generation,
+ }
+}
+
+#[test]
+fn cache_only_read_observes_move_and_rollback_restores_it() {
+ block_on(async {
+ let mut engine = setup().await;
+ let patches = [
+ patch(
+ "in-progress",
+ LinkOperation::Remove {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ ),
+ patch(
+ "completed",
+ LinkOperation::PrependUnique {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ ),
+ ];
+ let (transaction, _) = engine
+ .begin_optimistic_write(
+ None,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_variables("completed"),
+ data: &mutation_response("completed"),
+ link_patches: &patches,
+ revalidations: &[],
+ created_at_ms: 0,
+ },
+ )
+ .await
+ .unwrap();
+
+ let optimistic = read_group(&mut engine).await;
+ let bins = optimistic["user"]["groupSoup"]["bins"].as_array().unwrap();
+ assert!(bins[0]["items"].as_array().unwrap().is_empty());
+ assert_eq!(bins[1]["items"][0]["id"], json!("task-1"));
+ // Server-owned pagination metadata is deliberately untouched.
+ assert_eq!(bins[0]["totalCount"], json!(1));
+ assert_eq!(bins[1]["totalCount"], json!(0));
+ assert_eq!(bins[1]["nextCursor"], json!("destination-cursor"));
+
+ // Durable recipes reconstruct the complete property + relation layer
+ // after an application restart.
+ let mut reopened = Engine::new(engine.storage().clone());
+ let hydrated = read_group(&mut reopened).await;
+ assert!(
+ hydrated["user"]["groupSoup"]["bins"][0]["items"]
+ .as_array()
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ hydrated["user"]["groupSoup"]["bins"][1]["items"][0]["id"],
+ json!("task-1")
+ );
+
+ let claim = claim(&mut engine, transaction).await;
+ engine
+ .rollback_optimistic_write(transaction, claim)
+ .await
+ .unwrap();
+ let restored = read_group(&mut engine).await;
+ assert_eq!(
+ restored["user"]["groupSoup"]["bins"][0]["items"][0]["id"],
+ json!("task-1")
+ );
+ assert!(
+ restored["user"]["groupSoup"]["bins"][1]["items"]
+ .as_array()
+ .unwrap()
+ .is_empty()
+ );
+ });
+}
+
+#[test]
+fn success_reapplies_recipe_and_returns_deduplicated_revalidation() {
+ block_on(async {
+ let mut engine = setup().await;
+ let patches = [
+ patch(
+ "in-progress",
+ LinkOperation::Remove {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ ),
+ patch(
+ "completed",
+ LinkOperation::PrependUnique {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ ),
+ ];
+ let (transaction, _) = engine
+ .begin_optimistic_write(
+ None,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_variables("completed"),
+ data: &mutation_response("completed"),
+ link_patches: &patches,
+ revalidations: &[],
+ created_at_ms: 0,
+ },
+ )
+ .await
+ .unwrap();
+
+ // A concurrent authoritative write lands while the mutation is
+ // pending. Settlement must patch this latest base, not promote the
+ // earlier optimistic field snapshot over it.
+ let mut concurrent = group_page();
+ concurrent["user"]["groupSoup"]["bins"][1]["items"] = json!([{
+ "id": "task-2",
+ "entity": {
+ "__typename": "GraphqlSoupDocument",
+ "id": "task-2",
+ "properties": []
+ }
+ }]);
+ engine
+ .write_query(
+ None,
+ GROUP_QUERY,
+ Some("GroupSoup"),
+ &query_variables(),
+ &concurrent,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let claim = claim(&mut engine, transaction).await;
+ let result = engine
+ .commit_optimistic_write(
+ transaction,
+ claim,
+ MUTATION,
+ Some("SetEntityProperty"),
+ &mutation_variables("completed"),
+ &mutation_response("completed"),
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.revalidations.len(), 1);
+ let committed = read_group(&mut engine).await;
+ assert_eq!(
+ committed["user"]["groupSoup"]["bins"][1]["items"][0]["id"],
+ json!("task-1")
+ );
+ assert_eq!(
+ committed["user"]["groupSoup"]["bins"][1]["items"][1]["id"],
+ json!("task-2")
+ );
+ });
+}
+
+#[test]
+fn missing_destination_rejects_the_whole_patch_set_without_enqueueing() {
+ block_on(async {
+ let mut engine = setup().await;
+ let patches = [
+ patch(
+ "in-progress",
+ LinkOperation::Remove {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ ),
+ patch(
+ "missing",
+ LinkOperation::PrependUnique {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ ),
+ ];
+ assert!(
+ engine
+ .begin_optimistic_write(
+ None,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_variables("completed"),
+ data: &mutation_response("completed"),
+ link_patches: &patches,
+ revalidations: &[],
+ created_at_ms: 0,
+ },
+ )
+ .await
+ .is_err()
+ );
+ let original = read_group(&mut engine).await;
+ assert_eq!(
+ original["user"]["groupSoup"]["bins"][0]["items"][0]["id"],
+ json!("task-1")
+ );
+ });
+}
diff --git a/crates/client/cache-core/tests/mutation_queue.rs b/crates/client/cache-core/tests/mutation_queue.rs
index 1a98ab68cc..ba9e696108 100644
--- a/crates/client/cache-core/tests/mutation_queue.rs
+++ b/crates/client/cache-core/tests/mutation_queue.rs
@@ -1,10 +1,36 @@
use cache_core::queue::{
- MutationClaimRequest, MutationClaimToken, MutationRequest, NewQueuedMutation,
- PersistedOptimisticLayer, StoredMutation,
+ MutationClaimRequest, MutationClaimToken, MutationRequest, NewQueuedMutation, OptimisticSource,
+ PersistedOptimisticLayer, StoredMutation, decode_optimistic_source, encode_optimistic_source,
};
use cache_core::store::{InMemoryStorage, Storage};
use cache_core::value::{CacheValue, EntityKey, Record};
use pollster::block_on;
+use serde_json::json;
+
+#[test]
+fn optimistic_source_supports_versioned_and_legacy_json() {
+ let source = OptimisticSource {
+ mutation_data: json!({"rename": {"name": "next"}}),
+ link_patches: Vec::new(),
+ revalidations: Vec::new(),
+ };
+ assert_eq!(
+ decode_optimistic_source(&encode_optimistic_source(&source)).unwrap(),
+ source
+ );
+ assert_eq!(
+ decode_optimistic_source(
+ r#"{"version":2,"mutationData":{"name":"collision"},"rename":{"name":"legacy"}}"#
+ )
+ .unwrap()
+ .mutation_data,
+ json!({
+ "version": 2,
+ "mutationData": {"name": "collision"},
+ "rename": {"name": "legacy"}
+ })
+ );
+}
fn queued(value: &str, created_at_ms: i64) -> NewQueuedMutation {
let mut update = Record::default();
diff --git a/crates/client/cache-core/tests/optimistic.rs b/crates/client/cache-core/tests/optimistic.rs
index 488e0266de..23bc405301 100644
--- a/crates/client/cache-core/tests/optimistic.rs
+++ b/crates/client/cache-core/tests/optimistic.rs
@@ -1,7 +1,7 @@
//! Durable optimistic mutation tests: enqueue/read/claim/retry/commit/fail,
//! strict ordering, and lifecycle resets.
-use cache_core::engine::{Engine, EngineError, ReadResult};
+use cache_core::engine::{BeginOptimisticWrite, Engine, EngineError, ReadResult};
use cache_core::queue::{MutationClaimRequest, MutationClaimToken};
use cache_core::store::{InMemoryStorage, Storage};
use cache_core::value::{CacheValue, EntityKey};
@@ -190,11 +190,15 @@ fn begin_persists_mutation_and_optimistic_layer() {
let (transaction, result) = engine
.begin_optimistic_write(
None,
- MUTATION,
- Some("SetEntityProperty"),
- &mutation_vars("doing"),
- &mutation_response("Status", "doing"),
- 123,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("doing"),
+ data: &mutation_response("Status", "doing"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 123,
+ },
)
.await
.unwrap();
@@ -223,11 +227,15 @@ fn claimed_success_atomically_commits_real_response() {
let (transaction, _) = engine
.begin_optimistic_write(
None,
- MUTATION,
- Some("SetEntityProperty"),
- &mutation_vars("doing"),
- &mutation_response("Status", "doing"),
- 0,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("doing"),
+ data: &mutation_response("Status", "doing"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 0,
+ },
)
.await
.unwrap();
@@ -270,22 +278,30 @@ fn retryable_failure_keeps_optimistic_layer_and_blocks_later_mutations() {
let (first, _) = engine
.begin_optimistic_write(
None,
- MUTATION,
- Some("SetEntityProperty"),
- &mutation_vars("a"),
- &mutation_response("Status", "a"),
- 0,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("a"),
+ data: &mutation_response("Status", "a"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 0,
+ },
)
.await
.unwrap();
let (second, _) = engine
.begin_optimistic_write(
None,
- MUTATION,
- Some("SetEntityProperty"),
- &mutation_vars("b"),
- &mutation_response("Status", "b"),
- 1,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("b"),
+ data: &mutation_response("Status", "b"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 1,
+ },
)
.await
.unwrap();
@@ -323,22 +339,30 @@ fn permanent_failure_rolls_back_only_the_claimed_head() {
let (first, _) = engine
.begin_optimistic_write(
None,
- MUTATION,
- Some("SetEntityProperty"),
- &mutation_vars("a"),
- &mutation_response("Status", "a"),
- 0,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("a"),
+ data: &mutation_response("Status", "a"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 0,
+ },
)
.await
.unwrap();
engine
.begin_optimistic_write(
None,
- MUTATION,
- Some("SetEntityProperty"),
- &mutation_vars("b"),
- &mutation_response("Status", "b"),
- 1,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("b"),
+ data: &mutation_response("Status", "b"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 1,
+ },
)
.await
.unwrap();
@@ -365,11 +389,15 @@ fn stale_claim_cannot_settle_mutation() {
let (transaction, _) = engine
.begin_optimistic_write(
None,
- MUTATION,
- Some("SetEntityProperty"),
- &mutation_vars("doing"),
- &mutation_response("Status", "doing"),
- 0,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("doing"),
+ data: &mutation_response("Status", "doing"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 0,
+ },
)
.await
.unwrap();
@@ -409,11 +437,15 @@ fn clear_and_identity_reset_drop_durable_queue() {
engine
.begin_optimistic_write(
None,
- MUTATION,
- Some("SetEntityProperty"),
- &mutation_vars("doing"),
- &mutation_response("Status", "doing"),
- 0,
+ BeginOptimisticWrite {
+ query: MUTATION,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_vars("doing"),
+ data: &mutation_response("Status", "doing"),
+ link_patches: &[],
+ revalidations: &[],
+ created_at_ms: 0,
+ },
)
.await
.unwrap();
diff --git a/crates/client/cache-core/tests/query_inspection.rs b/crates/client/cache-core/tests/query_inspection.rs
new file mode 100644
index 0000000000..60ab857f79
--- /dev/null
+++ b/crates/client/cache-core/tests/query_inspection.rs
@@ -0,0 +1,460 @@
+//! Generated-query cache inspection integration tests.
+
+use cache_core::engine::{BeginOptimisticWrite, Engine};
+use cache_core::link_patch::{
+ LinkOperation, LinkPathSegment, ListItemByScalar, OptimisticLinkPatch,
+};
+use cache_core::query_inspection::{MAX_INSPECTED_VARIANTS, QueryInspection, QueryInspectionError};
+use cache_core::store::InMemoryStorage;
+use cache_core::value::EntityKey;
+use pollster::block_on;
+use serde_json::{Value as Json, json};
+
+const GROUP_QUERY: &str = r#"
+query GroupViews($input: GroupedSoupInput!) {
+ user {
+ id
+ groupSoup(input: $input) {
+ bins { key nextCursor items { id } }
+ }
+ }
+}
+"#;
+
+const SHORT_GROUP_QUERY: &str = r#"
+query GroupViews($input: GroupedSoupInput!) {
+ user { id groupSoup(input: $input) { bins { key items { id } } } }
+}
+"#;
+
+fn object(value: Json) -> serde_json::Map<String, Json> {
+ let Json::Object(value) = value else {
+ unreachable!()
+ };
+ value
+}
+
+fn initial(limit: usize) -> serde_json::Map<String, Json> {
+ object(json!({"input": {"initial": {
+ "groupBy": {"field": "PROPERTY", "propertyDefinitionId": "status-def"},
+ "limit": limit
+ }}}))
+}
+
+fn continuation(cursor: &str) -> serde_json::Map<String, Json> {
+ object(json!({"input": {"continuation": {
+ "groupBy": {"field": "PROPERTY", "propertyDefinitionId": "status-def"},
+ "groupKey": "in-progress",
+ "cursor": cursor
+ }}}))
+}
+
+fn page(item: &str, next_cursor: Option<&str>) -> Json {
+ json!({"user": {"id": "user-1", "groupSoup": {"bins": [{
+ "key": "in-progress",
+ "nextCursor": next_cursor,
+ "items": [{"id": item}]
+ }]}}})
+}
+
+fn inspection(query: &str, path: &[&str]) -> QueryInspection {
+ QueryInspection {
+ query: query.to_string(),
+ operation_name: Some("GroupViews".to_string()),
+ path: path.iter().map(|part| (*part).to_string()).collect(),
+ }
+}
+
+async fn write_group(
+ engine: &mut Engine<InMemoryStorage>,
+ query: &str,
+ variables: &serde_json::Map<String, Json>,
+ data: &Json,
+) {
+ engine
+ .write_query(None, query, Some("GroupViews"), variables, data, None)
+ .await
+ .unwrap();
+}
+
+#[test]
+fn enumerates_variants_aliases_and_misses_in_canonical_order() {
+ block_on(async {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ write_group(
+ &mut engine,
+ GROUP_QUERY,
+ &initial(20),
+ &page("task-1", None),
+ )
+ .await;
+ write_group(
+ &mut engine,
+ GROUP_QUERY,
+ &continuation("cursor-1"),
+ &page("task-2", Some("cursor-2")),
+ )
+ .await;
+ // This creates a third `groupSoup` variant, but not enough selected
+ // fields for the full inspection query to be a hit.
+ write_group(
+ &mut engine,
+ SHORT_GROUP_QUERY,
+ &initial(50),
+ &page("task-3", None),
+ )
+ .await;
+
+ // A different schema field on the same normalized user is ignored.
+ let soup_query =
+ "query Soup($input: SoupInput!) { user { id soup(input: $input) { hasMore } } }";
+ engine
+ .write_query(
+ None,
+ soup_query,
+ Some("Soup"),
+ &object(json!({"input": {"initial": {"limit": 20}}})),
+ &json!({"user": {"id": "user-1", "soup": {"hasMore": false}}}),
+ None,
+ )
+ .await
+ .unwrap();
+
+ let aliased = GROUP_QUERY
+ .replace("user {", "viewer: user {")
+ .replace("groupSoup(input:", "grouped: groupSoup(input:");
+ let results = engine
+ .inspect_query(&inspection(&aliased, &["viewer", "grouped"]))
+ .await
+ .unwrap();
+
+ assert_eq!(results.len(), 3);
+ assert!(results.windows(2).all(|pair| {
+ serde_json::to_string(&pair[0].variables).unwrap()
+ < serde_json::to_string(&pair[1].variables).unwrap()
+ }));
+ let miss = results
+ .iter()
+ .find(|result| result.variables == initial(50))
+ .unwrap();
+ assert_eq!(miss.value, None);
+ let hit = results
+ .iter()
+ .find(|result| result.variables == initial(20))
+ .unwrap();
+ assert_eq!(
+ hit.value.as_ref().unwrap()["bins"][0]["items"][0]["id"],
+ "task-1"
+ );
+ });
+}
+
+#[test]
+fn recovers_nested_constants_lists_and_repeated_variables() {
+ block_on(async {
+ let query = r#"
+query GroupViews($same: String!, $cursor: String!) {
+ user {
+ id
+ groupSoup(input: {
+ markers: [$same, "fixed"]
+ continuation: {
+ groupBy: { field: $same, propertyDefinitionId: $same }
+ groupKey: "in-progress"
+ cursor: $cursor
+ }
+ }) { bins { key nextCursor items { id } } }
+ }
+}
+"#;
+ let variables = object(json!({"same": "PROPERTY", "cursor": "cursor-1"}));
+ let mut engine = Engine::new(InMemoryStorage::new());
+ write_group(&mut engine, query, &variables, &page("task-1", None)).await;
+
+ let results = engine
+ .inspect_query(&inspection(query, &["user", "groupSoup"]))
+ .await
+ .unwrap();
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].variables, variables);
+
+ // The same stored arguments do not match a different constant.
+ let mismatch = query.replace("groupKey: \"in-progress\"", "groupKey: \"done\"");
+ assert!(
+ engine
+ .inspect_query(&inspection(&mismatch, &["user", "groupSoup"]))
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ });
+}
+
+#[test]
+fn traverses_constant_only_prefix_fields() {
+ block_on(async {
+ let query = GROUP_QUERY.replace("user {", "user(scope: \"all\") {");
+ let mut engine = Engine::new(InMemoryStorage::new());
+ write_group(&mut engine, &query, &initial(20), &page("task-1", None)).await;
+
+ let results = engine
+ .inspect_query(&inspection(&query, &["user", "groupSoup"]))
+ .await
+ .unwrap();
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].variables, initial(20));
+ });
+}
+
+#[test]
+fn loads_a_cold_normalized_owner() {
+ block_on(async {
+ let mut writer = Engine::with_capacity(InMemoryStorage::new(), 1);
+ write_group(
+ &mut writer,
+ GROUP_QUERY,
+ &initial(20),
+ &page("task-1", None),
+ )
+ .await;
+
+ let mut reopened = Engine::with_capacity(writer.storage().clone(), 1);
+ let results = reopened
+ .inspect_query(&inspection(GROUP_QUERY, &["user", "groupSoup"]))
+ .await
+ .unwrap();
+ assert_eq!(results.len(), 1);
+ assert!(results[0].value.is_some());
+ });
+}
+
+#[test]
+fn inspection_reads_the_effective_optimistic_view() {
+ block_on(async {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ let variables = initial(20);
+ let data = json!({"user": {"id": "user-1", "groupSoup": {"bins": [
+ {"key": "in-progress", "nextCursor": null, "items": [{"id": "task-1"}]},
+ {"key": "completed", "nextCursor": null, "items": []}
+ ]}}});
+ write_group(&mut engine, GROUP_QUERY, &variables, &data).await;
+
+ let patch = OptimisticLinkPatch {
+ query: GROUP_QUERY.to_string(),
+ operation_name: Some("GroupViews".to_string()),
+ variables_json: serde_json::to_string(&variables).unwrap(),
+ path: vec![
+ LinkPathSegment::Field {
+ field: "user".into(),
+ },
+ LinkPathSegment::Field {
+ field: "groupSoup".into(),
+ },
+ LinkPathSegment::Field {
+ field: "bins".into(),
+ },
+ LinkPathSegment::ListItem {
+ list_item: ListItemByScalar {
+ where_field: "key".into(),
+ equals: json!("in-progress"),
+ },
+ },
+ LinkPathSegment::Field {
+ field: "items".into(),
+ },
+ ],
+ operation: LinkOperation::Remove {
+ entity_key: EntityKey("GraphqlSoupItem:task-1".into()),
+ },
+ };
+ let mutation = r#"
+mutation SetEntityProperty($input: SetEntityPropertyInput!) {
+ setEntityProperty(input: $input) { id }
+}
+"#;
+ let mutation_variables = object(json!({"input": {
+ "entityType": "DOCUMENT",
+ "entityId": "task-1",
+ "propertyDefinitionId": "status-def"
+ }}));
+ engine
+ .begin_optimistic_write(
+ None,
+ BeginOptimisticWrite {
+ query: mutation,
+ operation_name: Some("SetEntityProperty"),
+ variables: &mutation_variables,
+ data: &json!({"setEntityProperty": {"id": "property-1"}}),
+ link_patches: &[patch],
+ revalidations: &[],
+ created_at_ms: 0,
+ },
+ )
+ .await
+ .unwrap();
+
+ let results = engine
+ .inspect_query(&inspection(GROUP_QUERY, &["user", "groupSoup"]))
+ .await
+ .unwrap();
+ assert!(
+ results[0].value.as_ref().unwrap()["bins"][0]["items"]
+ .as_array()
+ .unwrap()
+ .is_empty()
+ );
+ });
+}
+
+#[test]
+fn rejects_invalid_entrypoints_paths_variables_and_limits() {
+ block_on(async {
+ let mut engine = Engine::new(InMemoryStorage::new());
+ write_group(
+ &mut engine,
+ GROUP_QUERY,
+ &initial(20),
+ &page("task-1", None),
+ )
+ .await;
+
+ let mutation = QueryInspection {
+ query: "mutation GroupViews { renameFile(input: {}) { id } }".into(),
+ operation_name: Some("GroupViews".into()),
+ path: vec!["renameFile".into()],
+ };
+ assert!(matches!(
+ engine.inspect_query(&mutation).await.unwrap_err(),
+ cache_core::engine::EngineError::QueryInspection(QueryInspectionError::NotQuery)
+ ));
+ assert!(matches!(
+ engine
+ .inspect_query(&inspection(GROUP_QUERY, &[]))
+ .await
+ .unwrap_err(),
+ cache_core::engine::EngineError::QueryInspection(QueryInspectionError::InvalidDepth(0))
+ ));
+ assert!(matches!(
+ engine
+ .inspect_query(&inspection(GROUP_QUERY, &["user", "id"]))
+ .await
+ .unwrap_err(),
+ cache_core::engine::EngineError::QueryInspection(
+ QueryInspectionError::NonCompositeFinalField
+ )
+ ));
+ let too_deep = vec!["user"; 17];
+ assert!(matches!(
+ engine
+ .inspect_query(&inspection(GROUP_QUERY, &too_deep))
+ .await
+ .unwrap_err(),
+ cache_core::engine::EngineError::QueryInspection(QueryInspectionError::InvalidDepth(
+ 17
+ ))
+ ));
+ let list_path_query = r#"
+query GroupViews {
+ user {
+ groupSoup(input: { initial: {
+ groupBy: { field: PROPERTY, propertyDefinitionId: "status-def" }
+ limit: 20
+ } }) { bins { items { id } } }
+ }
+}
+"#;
+ write_group(
+ &mut engine,
+ list_path_query,
+ &serde_json::Map::new(),
+ &page("task-1", None),
+ )
+ .await;
+ assert!(matches!(
+ engine
+ .inspect_query(&inspection(
+ list_path_query,
+ &["user", "groupSoup", "bins", "items"]
+ ))
+ .await
+ .unwrap_err(),
+ cache_core::engine::EngineError::QueryInspection(QueryInspectionError::WrongShape)
+ ));
+ assert!(matches!(
+ engine
+ .inspect_query(&inspection(GROUP_QUERY, &["user", "missing"]))
+ .await
+ .unwrap_err(),
+ cache_core::engine::EngineError::QueryInspection(
+ QueryInspectionError::UnselectedField { .. }
+ )
+ ));
+
+ let prefix_variable = r#"
+query GroupViews($id: String!, $input: GroupedSoupInput!) {
+ user(id: $id) { groupSoup(input: $input) { bins { key } } }
+}
+"#;
+ assert!(matches!(
+ engine
+ .inspect_query(&inspection(prefix_variable, &["user", "groupSoup"]))
+ .await
+ .unwrap_err(),
+ cache_core::engine::EngineError::QueryInspection(QueryInspectionError::VariablePrefix(
+ _
+ ))
+ ));
+
+ let unresolved = r#"
+query GroupViews($input: GroupedSoupInput!, $other: Int!) {
+ user { groupSoup(input: $input) { bins(limit: $other) { key } } }
+}
+"#;
+ assert!(matches!(
+ engine
+ .inspect_query(&inspection(unresolved, &["user", "groupSoup"]))
+ .await
+ .unwrap_err(),
+ cache_core::engine::EngineError::QueryInspection(
+ QueryInspectionError::UnrecoverableVariable(_)
+ )
+ ));
+
+ let ambiguous = r#"
+query GroupViews($input: GroupedSoupInput!) {
+ user {
+ groupSoup(input: $input) { bins { key } }
+ groupSoup(input: $input) { bins { key } }
+ }
+}
+"#;
+ assert!(matches!(
+ engine
+ .inspect_query(&inspection(ambiguous, &["user", "groupSoup"]))
+ .await
+ .unwrap_err(),
+ cache_core::engine::EngineError::QueryInspection(
+ QueryInspectionError::AmbiguousField { .. }
+ )
+ ));
+
+ for limit in 0..=MAX_INSPECTED_VARIANTS {
+ write_group(
+ &mut engine,
+ GROUP_QUERY,
+ &initial(1_000 + limit),
+ &page("task-1", None),
+ )
+ .await;
+ }
+ assert!(matches!(
+ engine
+ .inspect_query(&inspection(GROUP_QUERY, &["user", "groupSoup"]))
+ .await
+ .unwrap_err(),
+ cache_core::engine::EngineError::QueryInspection(
+ QueryInspectionError::TooManyVariants { .. }
+ )
+ ));
+ });
+}
diff --git a/crates/client/cache-sqlite/tests/mutation_queue.rs b/crates/client/cache-sqlite/tests/mutation_queue.rs
index 1abe4d10cc..5b98125833 100644
--- a/crates/client/cache-sqlite/tests/mutation_queue.rs
+++ b/crates/client/cache-sqlite/tests/mutation_queue.rs
@@ -117,7 +117,7 @@ fn queue_and_optimistic_layer_survive_reopen() {
}
#[test]
-fn engine_hydrates_optimistic_layer_after_restart() {
+fn restart_hydration_preserves_legacy_json_with_envelope_keys() {
use cache_core::engine::{Engine, ReadResult};
use serde_json::json;
@@ -143,10 +143,14 @@ fn engine_hydrates_optimistic_layer_after_restart() {
}}],
"hasMore": false
}}});
- let optimistic = json!({"setEntityProperty": {
- "id": "prop-1",
- "displayName": "Stage"
- }});
+ let optimistic = json!({
+ "version": 2,
+ "mutationData": {"colliding": true},
+ "setEntityProperty": {
+ "id": "prop-1",
+ "displayName": "Stage"
+ }
+ });
let mut engine = Engine::new(SqliteStorage::open(&path, "scope-1").unwrap());
engine
@@ -160,18 +164,28 @@ fn engine_hydrates_optimistic_layer_after_restart() {
)
.await
.unwrap();
- engine
- .begin_optimistic_write(
- None,
- CACHE_MUTATION,
- Some("SetEntityProperty"),
- &mutation_vars,
- &optimistic,
- 10,
- )
+ drop(engine);
+
+ let mut storage = SqliteStorage::open(&path, "scope-1").unwrap();
+ storage
+ .enqueue_mutation(NewQueuedMutation {
+ mutation: StoredMutation::new(
+ MutationRequest {
+ query: CACHE_MUTATION.to_string(),
+ operation_name: Some("SetEntityProperty".to_string()),
+ variables_json: serde_json::to_string(&mutation_vars).unwrap(),
+ identity: Some("user-1".to_string()),
+ },
+ 10,
+ ),
+ optimistic: PersistedOptimisticLayer {
+ optimistic_data_json: serde_json::to_string(&optimistic).unwrap(),
+ normalized_updates: Default::default(),
+ },
+ })
.await
.unwrap();
- drop(engine);
+ drop(storage);
let mut reopened = Engine::new(SqliteStorage::open(&path, "scope-1").unwrap());
let ReadResult::Hit { data } = reopened
diff --git a/crates/client/cache-wasm/Cargo.toml b/crates/client/cache-wasm/Cargo.toml
index e132b7a112..cf51443089 100644
--- a/crates/client/cache-wasm/Cargo.toml
+++ b/crates/client/cache-wasm/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2024"
name = "cache-wasm"
publish = false
-version = "0.1.0"
+version = "0.2.0"
[lib]
crate-type = ["cdylib", "rlib"]
diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rs
index 22f53422d1..08f4398023 100644
--- a/crates/client/cache-wasm/src/shell.rs
+++ b/crates/client/cache-wasm/src/shell.rs
@@ -1,10 +1,12 @@
use async_lock::Mutex;
use cache_core::deps::OpId;
-use cache_core::engine::{Engine, ReadResult};
+use cache_core::engine::{BeginOptimisticWrite, Engine, ReadResult};
+use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};
+use cache_core::query_inspection::QueryInspection;
use cache_core::queue::{ClaimedMutation, MutationClaimRequest, MutationClaimToken};
use cache_core::value::EntityKey;
use cache_idb::IdbStorage;
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
@@ -57,6 +59,12 @@ struct JsWriteResult {
changed: Vec<String>,
affected_ops: Vec<String>,
reset: bool,
+ revalidations: Vec<QueryRevalidation>,
+}
+
+#[derive(Deserialize)]
+struct JsInspectionPathSegment {
+ field: String,
}
#[derive(Serialize)]
@@ -66,6 +74,7 @@ struct JsOptimisticWriteResult {
changed: Vec<String>,
affected_ops: Vec<String>,
reset: bool,
+ revalidations: Vec<QueryRevalidation>,
}
#[derive(Serialize)]
@@ -180,6 +189,13 @@ fn parse_variables(
serde_wasm_bindgen::from_value(variables).map_err(err_js)
}
+fn parse_vec<T: serde::de::DeserializeOwned>(value: JsValue) -> Result<Vec<T>, JsValue> {
+ if value.is_undefined() || value.is_null() {
+ return Ok(Vec::new());
+ }
+ serde_wasm_bindgen::from_value(value).map_err(err_js)
+}
+
#[wasm_bindgen]
impl CacheEngine {
/// Attempts a cache read. Resolves to `{kind:"hit",data}` or
@@ -248,6 +264,7 @@ impl CacheEngine {
changed: result.changed.into_iter().map(|k| k.0).collect(),
affected_ops: ops.borrow().names(result.affected_ops),
reset: result.reset,
+ revalidations: result.revalidations,
})
})
}
@@ -263,6 +280,8 @@ impl CacheEngine {
operation_name: Option<String>,
variables: JsValue,
data: JsValue,
+ link_patches: JsValue,
+ revalidations: JsValue,
created_at_ms: f64,
) -> js_sys::Promise {
let engine = self.engine.clone();
@@ -270,17 +289,23 @@ impl CacheEngine {
future_to_promise(async move {
let vars = parse_variables(variables)?;
let data: serde_json::Value = serde_wasm_bindgen::from_value(data).map_err(err_js)?;
+ let link_patches: Vec<OptimisticLinkPatch> = parse_vec(link_patches)?;
+ let revalidations: Vec<QueryRevalidation> = parse_vec(revalidations)?;
let created_at_ms = parse_timestamp(created_at_ms, "enqueue timestamp")?;
let origin = origin_op_id.map(|name| ops.borrow_mut().intern(&name));
let mut engine = engine.lock().await;
let (transaction, result) = engine
.begin_optimistic_write(
origin,
- &query,
- operation_name.as_deref(),
- &vars,
- &data,
- created_at_ms,
+ BeginOptimisticWrite {
+ query: &query,
+ operation_name: operation_name.as_deref(),
+ variables: &vars,
+ data: &data,
+ link_patches: &link_patches,
+ revalidations: &revalidations,
+ created_at_ms,
+ },
)
.await
.map_err(err_js)?;
@@ -289,10 +314,38 @@ impl CacheEngine {
changed: result.changed.into_iter().map(|k| k.0).collect(),
affected_ops: ops.borrow().names(result.affected_ops),
reset: result.reset,
+ revalidations: result.revalidations,
})
})
}
+ /// Enumerates cached variants of one generated query field.
+ #[wasm_bindgen(js_name = inspectQuery)]
+ pub fn inspect_query(
+ &self,
+ query: String,
+ operation_name: Option<String>,
+ path: 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 inspection = QueryInspection {
+ query,
+ operation_name,
+ path: path.into_iter().map(|segment| segment.field).collect(),
+ };
+ let instances = engine
+ .lock()
+ .await
+ .inspect_query(&inspection)
+ .await
+ .map_err(err_js)?;
+ to_js(&instances)
+ })
+ }
+
/// Claims the oldest runnable queued mutation.
#[wasm_bindgen(js_name = claimNextMutation)]
pub fn claim_next_mutation(
@@ -392,6 +445,7 @@ impl CacheEngine {
changed: result.changed.into_iter().map(|k| k.0).collect(),
affected_ops: ops.borrow().names(result.affected_ops),
reset: result.reset,
+ revalidations: result.revalidations,
})
})
}
@@ -422,6 +476,7 @@ impl CacheEngine {
changed: result.changed.into_iter().map(|k| k.0).collect(),
affected_ops: ops.borrow().names(result.affected_ops),
reset: result.reset,
+ revalidations: result.revalidations,
})
})
}
@@ -458,6 +513,7 @@ impl CacheEngine {
changed: result.changed.into_iter().map(|key| key.0).collect(),
affected_ops: ops.borrow().names(result.affected_ops),
reset: result.reset,
+ revalidations: result.revalidations,
})
})
}
diff --git a/crates/client/cache-wasm/tests/web.rs b/crates/client/cache-wasm/tests/web.rs
index 3109be200e..ef4bca4b7d 100644
--- a/crates/client/cache-wasm/tests/web.rs
+++ b/crates/client/cache-wasm/tests/web.rs
@@ -72,6 +72,19 @@ async fn write_then_read_through_js_boundary() {
assert_eq!(read["kind"], "hit");
assert_eq!(read["data"], data);
+ // Generated-query inspection crosses the wasm boundary with one wire
+ // shape and recovers the operation variables from the normalized field.
+ let inspected = JsFuture::from(engine.inspect_query(
+ QUERY.into(),
+ Some("Soup".into()),
+ js(serde_json::json!([{"field": "user"}, {"field": "soup"}])),
+ ))
+ .await
+ .unwrap();
+ let inspected: serde_json::Value = serde_wasm_bindgen::from_value(inspected).unwrap();
+ assert_eq!(inspected[0]["variables"], vars);
+ assert_eq!(inspected[0]["value"], data["user"]["soup"]);
+
// Cross-instance invalidation path: evict + report local dependents.
let affected =
JsFuture::from(engine.invalidate_keys(vec!["GraphqlSoupItem:doc-1".to_string()]))
@@ -151,6 +164,8 @@ async fn optimistic_write_round_trip() {
Some("SetEntityProperty".into()),
js(mutation_vars.clone()),
js(serde_json::json!({ "setEntityProperty": { "id": "prop-1", "displayName": "Stage" } })),
+ JsValue::UNDEFINED,
+ JsValue::UNDEFINED,
123.0,
))
.await