Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
add schema-typed GraphQL cache entity resolvers (#5527)
Sean Aye4d8ef446106e
diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.mdindex 0cba096a9d..e018ea7c60 100644--- a/apps/web/docs/graphql-normalized-cache-plan.md+++ b/apps/web/docs/graphql-normalized-cache-plan.md@@ -347,6 +347,16 @@ apps/web/src/lib/graphql-cache/ # JS glueas hashed assets (explicit `module_or_path` URL — vite copies thewasm-pack JS as an opaque asset, so its internal relative wasm URL had tobe resolved at the caller).+- Exchange-level `entityResolvers` can synthesize one singular normalized+ entity relation from a field argument without persisting a link. The+ supported subset is intentionally data-only: `entityFromArgument` accepts+ a schema-generated concrete target typename and a non-list path ending in+ GraphQL `ID`. Arbitrary callbacks, scalar transforms, lists/pagination,+ partial results, and resolver writes are not supported. For extracted+ configuration, preserve field-specific checks with+ `satisfies EntityResolverConfig`; TypeScript `any`/assertions can bypass+ static checks, but malformed values are rejected during exchange+ construction and validated again by the Rust engine.- **Manual smoke test pending**: dev-server run with the override enabled(localStorage `ENABLE_GRAPHQL_SOUP=true`), verify hit/miss + offlinebehavior in the browser.diff --git a/apps/web/package.json b/apps/web/package.jsonindex 18d76f69b8..12a78f0346 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -13,10 +13,12 @@"local:e2e:ui": "LOCAL_E2E=true bunx playwright test --ui","gen-api": "bun scripts/generate-api-schema.ts","gen-emoji-tags": "bun scripts/generate-emoji-tags.ts",- "gen-graphql": "graphql-codegen --config codegen.ts",+ "gen-graphql": "graphql-codegen --config codegen.ts && bun run gen-graphql-cache-schema",+ "gen-graphql-cache-schema": "bun scripts/generate-graphql-cache-entity-resolver-schema.ts",+ "check-graphql-cache-schema": "bun scripts/generate-graphql-cache-entity-resolver-schema.ts --check","gen-tools": "bun scripts/generate-dcs-tools.ts","type-check": "tsc --noEmit --skipLibCheck --project tsconfig.json",- "check": "bun type-check && bun biome check",+ "check": "bun check-graphql-cache-schema && bun type-check && bun biome check","preview": "vite preview -c vite.config.ts --outDir dist --base /app","preview:dev": "vite preview -c vite.config.ts --outDir dist --base /app","preview:prod": "vite preview -c vite.config.ts --outDir dist --base /app",diff --git a/apps/web/scripts/generate-graphql-cache-entity-resolver-schema.test.ts b/apps/web/scripts/generate-graphql-cache-entity-resolver-schema.test.tsnew file mode 100644index 0000000000..1590124027--- /dev/null+++ b/apps/web/scripts/generate-graphql-cache-entity-resolver-schema.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from 'vitest';+import {+ deriveEntityResolverSchema,+ renderEntityResolverSchema,+} from './generate-graphql-cache-entity-resolver-schema';++const FIXTURE = `+ schema { query: Root }+ type Root {+ concrete(input: NestedInput!): Entity+ interfaceResult(input: NestedInput!): Node+ unionResult(id: ID!): SearchResult+ embedded(input: NestedInput!): Embedded+ list(input: NestedInput!): [Entity!]!+ listInput(ids: [ID!]!): Entity+ scalar(id: ID!): String+ }+ input NestedInput { nested: IdInput!, ignored: String }+ input IdInput { entityId: ID!, labels: [ID!]! }+ interface Node { id: ID! }+ type Entity implements Node { id: ID!, name: String }+ type OtherEntity implements Node { id: ID! }+ type Embedded { name: String }+ union SearchResult = OtherEntity | Embedded | Entity+`;++describe('GraphQL cache entity resolver schema generator', () => {+ it('derives concrete, interface, union, and nested ID metadata', () => {+ expect(deriveEntityResolverSchema(FIXTURE)).toEqual({+ Root: {+ concrete: {+ targets: ['Entity'],+ argumentPaths: [['input', 'nested', 'entityId']],+ },+ interfaceResult: {+ targets: ['Entity', 'OtherEntity'],+ argumentPaths: [['input', 'nested', 'entityId']],+ },+ unionResult: {+ targets: ['Entity', 'OtherEntity'],+ argumentPaths: [['id']],+ },+ },+ });+ });++ it('excludes embedded/list returns, list inputs, and scalar returns', () => {+ const fields = deriveEntityResolverSchema(FIXTURE).Root;+ expect(fields).not.toHaveProperty('embedded');+ expect(fields).not.toHaveProperty('list');+ expect(fields).not.toHaveProperty('listInput');+ expect(fields).not.toHaveProperty('scalar');+ });++ it('fails clearly for recursive input types', () => {+ expect(() =>+ deriveEntityResolverSchema(`+ schema { query: Root }+ type Root { entity(input: RecursiveInput!): Entity }+ input RecursiveInput { id: ID, next: RecursiveInput }+ type Entity { id: ID! }+ `)+ ).toThrow('recursive input type RecursiveInput');+ });++ it('fails instead of truncating paths beyond the documented depth', () => {+ const inputTypes = Array.from({ length: 18 }, (_, index) =>+ index === 17+ ? `input Input${index} { id: ID }`+ : `input Input${index} { next: Input${index + 1}! }`+ ).join('\n');+ expect(() =>+ deriveEntityResolverSchema(`+ schema { query: Root }+ type Root { entity(input: Input0!): Entity }+ ${inputTypes}+ type Entity { id: ID! }+ `)+ ).toThrow('exceeds maximum depth');+ });++ it('renders deterministic valid empty unions when no fields are eligible', () => {+ const output = renderEntityResolverSchema(+ deriveEntityResolverSchema(`+ schema { query: Root }+ type Root { value: String }+ `)+ );+ expect(output).toContain('export const entityResolverSchema = {\n} as const;');+ expect(output).toContain(+ 'export type GeneratedEntityResolverTarget = never;'+ );+ expect(output).toContain(+ 'export type GeneratedEntityResolverArgumentPath = never;'+ );+ });++ it('renders deterministically regardless of SDL declaration order', () => {+ const reordered = `+ type Embedded { name: String }+ union SearchResult = Entity | Embedded | OtherEntity+ type OtherEntity implements Node { id: ID! }+ type Entity implements Node { name: String, id: ID! }+ interface Node { id: ID! }+ input IdInput { labels: [ID!]!, entityId: ID! }+ input NestedInput { ignored: String, nested: IdInput! }+ type Root {+ scalar(id: ID!): String+ listInput(ids: [ID!]!): Entity+ list(input: NestedInput!): [Entity!]!+ embedded(input: NestedInput!): Embedded+ unionResult(id: ID!): SearchResult+ interfaceResult(input: NestedInput!): Node+ concrete(input: NestedInput!): Entity+ }+ schema { query: Root }+ `;+ expect(+ renderEntityResolverSchema(deriveEntityResolverSchema(reordered))+ ).toBe(renderEntityResolverSchema(deriveEntityResolverSchema(FIXTURE)));+ });+});diff --git a/apps/web/scripts/generate-graphql-cache-entity-resolver-schema.ts b/apps/web/scripts/generate-graphql-cache-entity-resolver-schema.tsnew file mode 100644index 0000000000..57b81ef2f5--- /dev/null+++ b/apps/web/scripts/generate-graphql-cache-entity-resolver-schema.ts@@ -0,0 +1,269 @@+import {+ GraphQLID,+ type GraphQLInputType,+ type GraphQLObjectType,+ assertValidSchema,+ buildASTSchema,+ getNamedType,+ isInputObjectType,+ isInterfaceType,+ isListType,+ isNonNullType,+ isObjectType,+ isUnionType,+ parse,+} from 'graphql';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++/**+ * Input recursion is bounded so an SDL cycle or unexpectedly deep input shape+ * fails generation instead of silently producing incomplete argument paths.+ */+export const MAX_ENTITY_RESOLVER_INPUT_DEPTH = 16;++type FieldMetadata = {+ targets: string[];+ argumentPaths: string[][];+};++export type EntityResolverSchemaMetadata = Record<+ string,+ Record<string, FieldMetadata>+>;++/** Locale-independent UTF-16 code-unit ordering, matching ECMAScript strings. */+function compareCodeUnits(left: string, right: string): number {+ return left < right ? -1 : left > right ? 1 : 0;+}++function isKeyableObject(type: GraphQLObjectType): boolean {+ const id = type.getFields().id;+ return id !== undefined && isNonNullType(id.type) && id.type.ofType === GraphQLID;+}++function collectArgumentPaths(+ type: GraphQLInputType,+ path: string[],+ visited: ReadonlySet<string>,+ depth: number,+ ownerField: string,+ output: string[][]+): void {+ if (depth > MAX_ENTITY_RESOLVER_INPUT_DEPTH) {+ throw new Error(+ `entity resolver input path for ${ownerField} exceeds maximum depth ${MAX_ENTITY_RESOLVER_INPUT_DEPTH}`+ );+ }+ const nullableType = isNonNullType(type) ? type.ofType : type;+ if (isListType(nullableType)) return;+ if (nullableType === GraphQLID) {+ output.push(path);+ return;+ }+ if (!isInputObjectType(nullableType)) return;+ if (visited.has(nullableType.name)) {+ throw new Error(+ `recursive input type ${nullableType.name} reached while generating entity resolver paths for ${ownerField}`+ );+ }++ const nextVisited = new Set(visited);+ nextVisited.add(nullableType.name);+ const fields = Object.values(nullableType.getFields()).sort((a, b) =>+ compareCodeUnits(a.name, b.name)+ );+ for (const field of fields) {+ collectArgumentPaths(+ field.type,+ [...path, field.name],+ nextVisited,+ depth + 1,+ ownerField,+ output+ );+ }+}++/** Derives resolver metadata from a validated GraphQL SDL document. */+export function deriveEntityResolverSchema(+ schemaSource: string+): EntityResolverSchemaMetadata {+ const schema = buildASTSchema(parse(schemaSource));+ assertValidSchema(schema);+ const metadata: EntityResolverSchemaMetadata = {};++ const owners = Object.values(schema.getTypeMap())+ .filter(+ (type): type is GraphQLObjectType =>+ isObjectType(type) && !type.name.startsWith('__')+ )+ .sort((a, b) => compareCodeUnits(a.name, b.name));++ for (const owner of owners) {+ const fields: Record<string, FieldMetadata> = {};+ for (const field of Object.values(owner.getFields()).sort((a, b) =>+ compareCodeUnits(a.name, b.name)+ )) {+ const nullableReturn = isNonNullType(field.type)+ ? field.type.ofType+ : field.type;+ if (isListType(nullableReturn)) continue;+ const returnType = getNamedType(nullableReturn);+ if (+ !isObjectType(returnType) &&+ !isInterfaceType(returnType) &&+ !isUnionType(returnType)+ ) {+ continue;+ }++ let targets: string[];+ if (isObjectType(returnType)) {+ targets = isKeyableObject(returnType) ? [returnType.name] : [];+ } else {+ targets = schema+ .getPossibleTypes(returnType)+ .filter(isKeyableObject)+ .map((type) => type.name)+ .sort(compareCodeUnits);+ }+ if (targets.length === 0) continue;++ const argumentPaths: string[][] = [];+ for (const argument of [...field.args].sort((a, b) =>+ compareCodeUnits(a.name, b.name)+ )) {+ collectArgumentPaths(+ argument.type,+ [argument.name],+ new Set(),+ 0,+ `${owner.name}.${field.name}`,+ argumentPaths+ );+ }+ argumentPaths.sort((a, b) =>+ compareCodeUnits(JSON.stringify(a), JSON.stringify(b))+ );+ if (argumentPaths.length === 0) continue;+ fields[field.name] = { targets, argumentPaths };+ }+ if (Object.keys(fields).length > 0) metadata[owner.name] = fields;+ }++ return metadata;+}++function quote(value: string): string {+ // GraphQL names cannot contain a single quote.+ return `'${value}'`;+}++function tuple(values: readonly string[]): string {+ return `[${values.map(quote).join(', ')}]`;+}++function quoteTuple(values: readonly string[]): string {+ return `readonly ${tuple(values)}`;+}++/** Renders deterministic committed TypeScript metadata. */+export function renderEntityResolverSchema(+ metadata: EntityResolverSchemaMetadata+): string {+ const targets = new Set<string>();+ const paths = new Map<string, string[]>();+ const lines = [+ '// @generated by scripts/generate-graphql-cache-entity-resolver-schema.ts — do not edit.',+ '',+ 'export const entityResolverSchema = {',+ ];++ for (const parent of Object.keys(metadata).sort(compareCodeUnits)) {+ lines.push(` ${parent}: {`);+ const fields = metadata[parent] ?? {};+ for (const fieldName of Object.keys(fields).sort(compareCodeUnits)) {+ const field = fields[fieldName];+ if (!field) continue;+ for (const target of field.targets) targets.add(target);+ for (const path of field.argumentPaths) {+ paths.set(JSON.stringify(path), path);+ }+ lines.push(` ${fieldName}: {`);+ lines.push(` targets: [${field.targets.map(quote).join(', ')}],`);+ if (field.argumentPaths.length === 1) {+ lines.push(` argumentPaths: [${tuple(field.argumentPaths[0] ?? [])}],`);+ } else {+ lines.push(' argumentPaths: [');+ for (const path of field.argumentPaths) {+ lines.push(` ${tuple(path)},`);+ }+ lines.push(' ],');+ }+ lines.push(' },');+ }+ lines.push(' },');+ }+ lines.push('} as const;', '');+ lines.push(+ 'export type GeneratedEntityResolverSchema = typeof entityResolverSchema;'+ );+ const sortedTargets = [...targets].sort(compareCodeUnits);+ if (sortedTargets.length === 0) {+ lines.push('export type GeneratedEntityResolverTarget = never;');+ } else {+ lines.push('export type GeneratedEntityResolverTarget =');+ for (const [index, target] of sortedTargets.entries()) {+ lines.push(+ ` | ${quote(target)}${+ index === sortedTargets.length - 1 ? ';' : ''+ }`+ );+ }+ }+ const sortedPaths = [...paths.values()].sort((a, b) =>+ compareCodeUnits(JSON.stringify(a), JSON.stringify(b))+ );+ if (sortedPaths.length === 0) {+ lines.push('export type GeneratedEntityResolverArgumentPath = never;');+ } else {+ lines.push('export type GeneratedEntityResolverArgumentPath =');+ for (const [index, path] of sortedPaths.entries()) {+ lines.push(+ ` | ${quoteTuple(path)}${+ index === sortedPaths.length - 1 ? ';' : ''+ }`+ );+ }+ }+ return `${lines.join('\n')}\n`;+}++async function main(): Promise<void> {+ const scriptDirectory = dirname(fileURLToPath(import.meta.url));+ const webDirectory = resolve(scriptDirectory, '..');+ const schemaPath = resolve(webDirectory, '../../static_assets/schema.graphql');+ const outputPath = resolve(+ webDirectory,+ 'src/lib/graphql-cache/generated/entity-resolver-schema.ts'+ );+ const output = renderEntityResolverSchema(+ deriveEntityResolverSchema(await Bun.file(schemaPath).text())+ );++ if (process.argv.includes('--check')) {+ const current = await Bun.file(outputPath).text().catch(() => undefined);+ if (current !== output) {+ throw new Error(+ 'GraphQL cache entity resolver schema is stale; run `bun run gen-graphql-cache-schema`'+ );+ }+ return;+ }+ await Bun.write(outputPath, output);+}++if (import.meta.main) {+ await main();+}diff --git a/apps/web/src/lib/graphql-cache/exchange/entity-resolvers.test.ts b/apps/web/src/lib/graphql-cache/exchange/entity-resolvers.test.tsnew file mode 100644index 0000000000..36b415a661--- /dev/null+++ b/apps/web/src/lib/graphql-cache/exchange/entity-resolvers.test.ts@@ -0,0 +1,146 @@+import { describe, expect, it } from 'vitest';+import {+ compileEntityResolvers,+ type EntityResolverConfig,+ entityFromArgument,+} from './entity-resolvers';++describe('entity resolvers', () => {+ it('retains literals while copying and freezing the argument path', () => {+ const sourcePath: ['input', 'threadId'] = ['input', 'threadId'];+ const descriptor = entityFromArgument('GraphqlSoupEmailThread', sourcePath);++ expect(descriptor).toEqual({+ kind: 'entity-from-argument',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'threadId'],+ });+ expect(descriptor.argumentPath).not.toBe(sourcePath);+ expect(Object.isFrozen(descriptor)).toBe(true);+ expect(Object.isFrozen(descriptor.argumentPath)).toBe(true);+ sourcePath[1] = 'changed' as 'threadId';+ expect(descriptor.argumentPath).toEqual(['input', 'threadId']);+ });++ it('flattens deterministically and freezes copied wire descriptors', () => {+ const config = {+ GraphqlUser: {+ emailThread: entityFromArgument('GraphqlSoupEmailThread', [+ 'input',+ 'threadId',+ ]),+ },+ CompleteMutationRoot: {+ updateEmailThreadLabel: entityFromArgument('GraphqlSoupEmailThread', [+ 'input',+ 'labelId',+ ]),+ markEmailThreadSeen: entityFromArgument('GraphqlSoupEmailThread', [+ 'input',+ 'threadId',+ ]),+ },+ } satisfies EntityResolverConfig;++ const wire = compileEntityResolvers(config);+ expect(wire).toEqual([+ {+ parentType: 'CompleteMutationRoot',+ fieldName: 'markEmailThreadSeen',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'threadId'],+ },+ {+ parentType: 'CompleteMutationRoot',+ fieldName: 'updateEmailThreadLabel',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'labelId'],+ },+ {+ parentType: 'GraphqlUser',+ fieldName: 'emailThread',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'threadId'],+ },+ ]);+ expect(Object.isFrozen(wire)).toBe(true);+ expect(Object.isFrozen(wire[0])).toBe(true);+ expect(Object.isFrozen(wire[0]?.argumentPath)).toBe(true);+ expect(compileEntityResolvers()).toBe(compileEntityResolvers());+ });++ it.each([+ [null, 'configuration must be an object'],+ [{ Nope: {} }, 'unknown parent type'],+ [{ constructor: {} }, 'unknown parent type'],+ [{ GraphqlUser: null }, 'must map fields to descriptors'],+ [{ GraphqlUser: { nope: {} } }, 'unknown or ineligible field'],+ [{ GraphqlUser: { constructor: {} } }, 'unknown or ineligible field'],+ [{ GraphqlUser: { emailThread: null } }, 'must be a descriptor'],+ [+ {+ GraphqlUser: {+ emailThread: {+ kind: 'other',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'threadId'],+ },+ },+ },+ 'unsupported resolver kind',+ ],+ [+ {+ GraphqlUser: {+ emailThread: {+ kind: 'entity-from-argument',+ targetType: 'GraphqlProperty',+ argumentPath: ['input', 'threadId'],+ },+ },+ },+ 'cannot target',+ ],+ [+ {+ GraphqlUser: {+ emailThread: {+ kind: 'entity-from-argument',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'channelId'],+ },+ },+ },+ 'does not have ID argument path',+ ],+ [+ {+ GraphqlUser: {+ emailThread: {+ kind: 'entity-from-argument',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: [],+ },+ },+ },+ 'non-empty string array',+ ],+ [+ {+ GraphqlUser: {+ emailThread: {+ kind: 'entity-from-argument',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'threadId'],+ extra: true,+ },+ },+ },+ 'must contain only',+ ],+ ])('rejects malformed runtime configuration %#', (value, message) => {+ expect(() =>+ compileEntityResolvers(value as unknown as EntityResolverConfig)+ ).toThrow(message as string);+ });+});diff --git a/apps/web/src/lib/graphql-cache/exchange/entity-resolvers.ts b/apps/web/src/lib/graphql-cache/exchange/entity-resolvers.tsnew file mode 100644index 0000000000..99235350db--- /dev/null+++ b/apps/web/src/lib/graphql-cache/exchange/entity-resolvers.ts@@ -0,0 +1,212 @@+import {+ entityResolverSchema,+ type GeneratedEntityResolverArgumentPath,+ type GeneratedEntityResolverSchema,+ type GeneratedEntityResolverTarget,+} from '../generated/entity-resolver-schema';++/** Serializable declaration for a singular entity relation derived from an argument. */+export type EntityFromArgumentDescriptor<+ TargetType extends string,+ ArgumentPath extends readonly string[],+> = {+ readonly kind: 'entity-from-argument';+ readonly targetType: TargetType;+ readonly argumentPath: ArgumentPath;+};++/**+ * Declares that a field resolves to a normalized entity whose id is found at+ * `argumentPath`. The descriptor and a copied path are frozen so exchange+ * options remain immutable after construction.+ */+export function entityFromArgument<+ const TargetType extends GeneratedEntityResolverTarget,+ const ArgumentPath extends GeneratedEntityResolverArgumentPath,+>(+ targetType: TargetType,+ argumentPath: ArgumentPath+): EntityFromArgumentDescriptor<TargetType, ArgumentPath> {+ const copiedPath = Object.freeze([+ ...argumentPath,+ ]) as unknown as ArgumentPath;+ return Object.freeze({+ kind: 'entity-from-argument',+ targetType,+ argumentPath: copiedPath,+ });+}++type TargetFor<+ Parent extends keyof GeneratedEntityResolverSchema,+ Field extends keyof GeneratedEntityResolverSchema[Parent],+> = GeneratedEntityResolverSchema[Parent][Field] extends {+ readonly targets: readonly (infer Target extends string)[];+}+ ? Target+ : never;++type ArgumentPathFor<+ Parent extends keyof GeneratedEntityResolverSchema,+ Field extends keyof GeneratedEntityResolverSchema[Parent],+> = GeneratedEntityResolverSchema[Parent][Field] extends {+ readonly argumentPaths: readonly (infer Path extends readonly string[])[];+}+ ? Path+ : never;++/**+ * Schema-exact entity resolver configuration. TypeScript's `any` and unsafe+ * assertions can bypass these checks; exchange construction also validates+ * every descriptor at runtime.+ */+export type EntityResolverConfig = {+ [Parent in keyof GeneratedEntityResolverSchema]?: {+ [Field in keyof GeneratedEntityResolverSchema[Parent]]?: EntityFromArgumentDescriptor<+ TargetFor<Parent, Field>,+ ArgumentPathFor<Parent, Field>+ >;+ };+};++/** Transport descriptor consumed by browser/WASM and Tauri cache reads. */+export type EntityResolverWire = {+ parentType: string;+ fieldName: string;+ targetType: string;+ argumentPath: string[];+};++const EMPTY_ENTITY_RESOLVERS: readonly EntityResolverWire[] = Object.freeze([]);++function configError(detail: string): Error {+ return new Error(+ `invalid normalized cache entity resolver config: ${detail}`+ );+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value);+}++function pathMatches(+ candidate: readonly string[],+ expected: readonly (readonly string[])[]+): boolean {+ return expected.some(+ (path) =>+ path.length === candidate.length &&+ path.every((part, index) => part === candidate[index])+ );+}++/**+ * Validates and compiles user configuration once into a stable read wire.+ * Exported for focused runtime tests; callers normally use the exchange.+ */+export function compileEntityResolvers(+ config?: EntityResolverConfig+): readonly EntityResolverWire[] {+ if (config === undefined) return EMPTY_ENTITY_RESOLVERS;+ if (!isRecord(config)) throw configError('configuration must be an object');++ const runtimeSchema = entityResolverSchema as Record<+ string,+ Record<+ string,+ {+ readonly targets: readonly string[];+ readonly argumentPaths: readonly (readonly string[])[];+ }+ >+ >;+ const configRecord = config as Record<string, unknown>;+ const compiled: EntityResolverWire[] = [];+ for (const parentType of Object.keys(configRecord).sort()) {+ if (!Object.hasOwn(runtimeSchema, parentType)) {+ throw configError(`unknown parent type ${JSON.stringify(parentType)}`);+ }+ const parentSchema = runtimeSchema[parentType];+ if (!parentSchema) throw configError(`missing schema for ${parentType}`);+ const parentConfig = configRecord[parentType];+ if (!isRecord(parentConfig)) {+ throw configError(`${parentType} must map fields to descriptors`);+ }++ for (const fieldName of Object.keys(parentConfig).sort()) {+ if (!Object.hasOwn(parentSchema, fieldName)) {+ throw configError(+ `unknown or ineligible field ${JSON.stringify(`${parentType}.${fieldName}`)}`+ );+ }+ const fieldSchema = parentSchema[fieldName];+ if (!fieldSchema) {+ throw configError(+ `unknown or ineligible field ${JSON.stringify(`${parentType}.${fieldName}`)}`+ );+ }+ const descriptor = parentConfig[fieldName];+ if (!isRecord(descriptor)) {+ throw configError(`${parentType}.${fieldName} must be a descriptor`);+ }+ const descriptorKeys = Object.keys(descriptor).sort();+ if (+ descriptorKeys.length !== 3 ||+ descriptorKeys[0] !== 'argumentPath' ||+ descriptorKeys[1] !== 'kind' ||+ descriptorKeys[2] !== 'targetType'+ ) {+ throw configError(+ `${parentType}.${fieldName} must contain only kind, targetType, and argumentPath`+ );+ }+ if (descriptor.kind !== 'entity-from-argument') {+ throw configError(+ `${parentType}.${fieldName} has unsupported resolver kind`+ );+ }+ if (typeof descriptor.targetType !== 'string') {+ throw configError(+ `${parentType}.${fieldName} targetType must be a string`+ );+ }+ if (+ !Array.isArray(descriptor.argumentPath) ||+ descriptor.argumentPath.length === 0 ||+ !descriptor.argumentPath.every(+ (part: unknown): part is string => typeof part === 'string'+ )+ ) {+ throw configError(+ `${parentType}.${fieldName} argumentPath must be a non-empty string array`+ );+ }++ if (!fieldSchema.targets.includes(descriptor.targetType)) {+ throw configError(+ `${parentType}.${fieldName} cannot target ${JSON.stringify(descriptor.targetType)}`+ );+ }+ if (!pathMatches(descriptor.argumentPath, fieldSchema.argumentPaths)) {+ throw configError(+ `${parentType}.${fieldName} does not have ID argument path ${JSON.stringify(+ descriptor.argumentPath+ )}`+ );+ }++ const argumentPath = Object.freeze([+ ...descriptor.argumentPath,+ ]) as unknown as string[];+ compiled.push(+ Object.freeze({+ parentType,+ fieldName,+ targetType: descriptor.targetType,+ argumentPath,+ })+ );+ }+ }+ return Object.freeze(compiled);+}diff --git a/apps/web/src/lib/graphql-cache/exchange/entity-resolvers.typecheck.ts b/apps/web/src/lib/graphql-cache/exchange/entity-resolvers.typecheck.tsnew file mode 100644index 0000000000..d58b205e55--- /dev/null+++ b/apps/web/src/lib/graphql-cache/exchange/entity-resolvers.typecheck.ts@@ -0,0 +1,104 @@+import {+ type EntityResolverConfig,+ entityFromArgument,+} from './entity-resolvers';++// The public inline API retains its literals without explicit generics or+// `as const`.+const inlineConfig: EntityResolverConfig = {+ GraphqlUser: {+ emailThread: entityFromArgument('GraphqlSoupEmailThread', [+ 'input',+ 'threadId',+ ]),+ },+};++const extractedConfig = {+ GraphqlUser: {+ emailThread: entityFromArgument('GraphqlSoupEmailThread', [+ 'input',+ 'threadId',+ ]),+ },+} satisfies EntityResolverConfig;++const invalidParent: EntityResolverConfig = {+ // @ts-expect-error Unknown parent type.+ GraphqlTypo: {},+};++const invalidField: EntityResolverConfig = {+ GraphqlUser: {+ // @ts-expect-error Unknown field on a valid parent.+ emailTypo: entityFromArgument('GraphqlSoupEmailThread', [+ 'input',+ 'threadId',+ ]),+ },+};++const scalarField: EntityResolverConfig = {+ GraphqlUser: {+ // @ts-expect-error Scalar fields are not eligible entity relations.+ id: entityFromArgument('GraphqlSoupEmailThread', ['input', 'threadId']),+ },+};++const listField: EntityResolverConfig = {+ GraphqlUser: {+ // @ts-expect-error List-returning fields are not eligible.+ propertyDefinitions: entityFromArgument('GraphqlProperty', [+ 'input',+ 'propertyDefinitionId',+ ]),+ },+};++const embeddedField: EntityResolverConfig = {+ GraphqlUser: {+ // @ts-expect-error Embedded/non-entity fields are not eligible.+ soup: entityFromArgument('GraphqlSoupEmailThread', ['input', 'threadId']),+ },+};++// @ts-expect-error Unknown target typename.+entityFromArgument('GraphqlSoupEmailTread', ['input', 'threadId']);++const incompatibleTarget: EntityResolverConfig = {+ GraphqlUser: {+ // @ts-expect-error Valid entity typename, incompatible with emailThread.+ emailThread: entityFromArgument('GraphqlProperty', ['input', 'threadId']),+ },+};++// @ts-expect-error Typo in the first argument-path segment.+entityFromArgument('GraphqlSoupEmailThread', ['inpt', 'threadId']);++// @ts-expect-error Typo in the ID argument-path leaf.+entityFromArgument('GraphqlSoupEmailThread', ['input', 'threadID']);++const pathForAnotherField: EntityResolverConfig = {+ GraphqlUser: {+ // @ts-expect-error Globally valid ID path, but not for emailThread.+ emailThread: entityFromArgument('GraphqlSoupEmailThread', [+ 'input',+ 'channelId',+ ]),+ },+};++// @ts-expect-error The path leaf is not a GraphQL ID anywhere eligible.+entityFromArgument('GraphqlSoupEmailThread', ['input', 'limit']);++void [+ inlineConfig,+ extractedConfig,+ invalidParent,+ invalidField,+ scalarField,+ listField,+ embeddedField,+ incompatibleTarget,+ pathForAnotherField,+];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.tsindex cc552ddb1b..163067b531 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@@ -25,6 +25,7 @@ import type {ReadResult,WriteResult,} from '../protocol';+import { entityFromArgument } from './entity-resolvers';import {type NormalizedCacheExchangeOptions,normalizedCacheExchange,@@ -39,6 +40,26 @@ const QUERY = gql`}`;+const ENTITY_RESOLVER_OPTIONS: NormalizedCacheExchangeOptions = {+ entityResolvers: {+ GraphqlUser: {+ emailThread: entityFromArgument('GraphqlSoupEmailThread', [+ 'input',+ 'threadId',+ ]),+ },+ },+};++const EXPECTED_ENTITY_RESOLVERS = [+ {+ parentType: 'GraphqlUser',+ fieldName: 'emailThread',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'threadId'],+ },+];+const SUBSCRIPTION = gql`subscription SoupUpdates {soupUpdates {@@ -129,6 +150,7 @@ type FakeHost = CacheHost & {query: string;variables?: object;priority?: 'user-visible';+ entityResolvers?: readonly unknown[];}>;writes: Array<{ opKey?: number; data: unknown; identity?: string }>;begins: Array<{@@ -216,6 +238,7 @@ function makeFakeHost(): FakeHost {query: args.query,variables: args.variables,priority: args.priority,+ entityResolvers: args.entityResolvers,});return readResult;},@@ -694,6 +717,59 @@ describe('normalizedCacheExchange', () => {expect(host.writes[0]?.data).toEqual({ from: 'network' });});+ it('compiles entity resolvers once and forwards them to initial and post-write reads', async () => {+ const options = {+ entityResolvers: ENTITY_RESOLVER_OPTIONS.entityResolvers,+ } satisfies NormalizedCacheExchangeOptions;+ const { ops, forwarded } = harness(host, undefined, options);+ // Mutating the outer options after exchange construction cannot change+ // the already-compiled read policy.+ (options as NormalizedCacheExchangeOptions).entityResolvers = undefined;+ ops.next(makeOp(1));+ await tick();++ expect(host.reads).toHaveLength(2);+ expect(forwarded.map((operation) => operation.key)).toEqual([1]);+ expect(host.reads.every((read) => read.entityResolvers !== undefined)).toBe(+ true+ );+ expect(host.reads.map((read) => read.entityResolvers)).toEqual([+ EXPECTED_ENTITY_RESOLVERS,+ EXPECTED_ENTITY_RESOLVERS,+ ]);+ });++ it('cache-first resolver hit emits without reaching the network', async () => {+ host.scriptRead({ kind: 'hit', data: { from: 'cache' } });+ const { ops, results, forwarded } = harness(+ host,+ undefined,+ ENTITY_RESOLVER_OPTIONS+ );+ ops.next(makeOp(1));+ await tick();++ expect(host.reads[0]?.entityResolvers).toEqual(EXPECTED_ENTITY_RESOLVERS);+ expect(results[0]?.data).toEqual({ from: 'cache' });+ expect(forwarded).toHaveLength(0);+ });++ it('rejects malformed resolver options during exchange construction', () => {+ expect(() =>+ normalizedCacheExchange(host, {+ entityResolvers: {+ GraphqlUser: {+ emailThread: {+ kind: 'entity-from-argument',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'bad'],+ },+ },+ } as never,+ })+ ).toThrow('does not have ID argument path');+ });+it('cache-first hit emits without network', async () => {host.scriptRead({ kind: 'hit', data: { from: 'cache' } });const { ops, results, forwarded } = harness(host);@@ -723,24 +799,30 @@ describe('normalizedCacheExchange', () => {});it('network-only skips the initial read and refreshes dependencies after writing', async () => {- const { ops, results } = harness(host);+ const { ops, results } = harness(host, undefined, ENTITY_RESOLVER_OPTIONS);ops.next(makeOp(1, 'network-only'));await tick();expect(host.reads).toHaveLength(1);expect(host.reads[0]?.opKey).toBe(1);+ expect(host.reads[0]?.entityResolvers).toEqual(EXPECTED_ENTITY_RESOLVERS);expect(results[0]?.data).toEqual({ from: 'network' });expect(host.writes).toHaveLength(1);});it('cache-only miss emits empty data and never touches the network', async () => {- const { ops, results, forwarded } = harness(host);+ const { ops, results, forwarded } = harness(+ host,+ undefined,+ ENTITY_RESOLVER_OPTIONS+ );ops.next(makeOp(1, 'cache-only'));await tick();expect(results).toHaveLength(1);expect(results[0]?.data).toBeUndefined();expect(forwarded).toHaveLength(0);+ expect(host.reads[0]?.entityResolvers).toEqual(EXPECTED_ENTITY_RESOLVERS);});it('cache read errors degrade to the network', async () => {@@ -850,7 +932,7 @@ describe('normalizedCacheExchange', () => {it('re-executes each affected active operation once as a prioritized cache read', async () => {host.scriptRead({ kind: 'hit', data: { from: 'cache' } });- const { ops, client } = harness(host);+ const { ops, client } = harness(host, undefined, ENTITY_RESOLVER_OPTIONS);const op = makeOp(7, 'cache-and-network');ops.next(op);await tick();@@ -869,6 +951,10 @@ describe('normalizedCacheExchange', () => {expect(host.reads).toHaveLength(2);expect(host.reads[0]?.priority).toBeUndefined();expect(host.reads[1]?.priority).toBe('user-visible');+ expect(host.reads.map((read) => read.entityResolvers)).toEqual([+ EXPECTED_ENTITY_RESOLVERS,+ EXPECTED_ENTITY_RESOLVERS,+ ]);});it('teardown unregisters the op with the host and stops re-execution', async () => {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.tsindex ed3a8711c6..a18dab2440 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@@ -63,6 +63,10 @@ import type {EnqueueOptimisticMutationResult,QueryRevalidationWire,} from '../protocol';+import {+ compileEntityResolvers,+ type EntityResolverConfig,+} from './entity-resolvers';import {normalizedEntityKey,optimisticContextOf,@@ -283,6 +287,8 @@ function queuedMutationResult(}export interface NormalizedCacheExchangeOptions {+ /** Schema-typed singular entity relations derived from field arguments. */+ entityResolvers?: EntityResolverConfig;/** Called when a cache read/write fails (diagnostics; flow already degraded to network). */onCacheError?: (error: unknown, op: Operation) => void;/**@@ -306,6 +312,7 @@ export function normalizedCacheExchange(host: CacheHost,options: NormalizedCacheExchangeOptions = {}): Exchange {+ const entityResolvers = compileEntityResolvers(options.entityResolvers);return ({ forward, client }) => {/** Operations registered with the host, for push-driven re-execution. */const activeOps = new Map<number, Operation>();@@ -513,6 +520,7 @@ export function normalizedCacheExchange(query: queryText(op),operationName: operationName(op),variables: op.variables as Record<string, unknown> | undefined,+ entityResolvers,priority:op.context[AFFECTED_READ_CONTEXT_KEY] === true? 'user-visible'@@ -691,6 +699,7 @@ export function normalizedCacheExchange(query: queryText(op),operationName: operationName(op),variables: op.variables as Record<string, unknown> | undefined,+ entityResolvers,};await host.writeQuery({...args,diff --git a/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts b/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.tsnew file mode 100644index 0000000000..357b68ed23--- /dev/null+++ b/apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts@@ -0,0 +1,48 @@+// @generated by scripts/generate-graphql-cache-entity-resolver-schema.ts — do not edit.++export const entityResolverSchema = {+ CompleteMutationRoot: {+ markEmailThreadSeen: {+ targets: ['GraphqlSoupEmailThread'],+ argumentPaths: [['input', 'threadId']],+ },+ recordChannelActivity: {+ targets: ['GraphqlChannelActivity'],+ argumentPaths: [['input', 'channelId']],+ },+ setEntityProperty: {+ targets: ['GraphqlProperty'],+ argumentPaths: [+ ['input', 'propertyDefinitionId'],+ ['input', 'value', 'entityReference', 'specificMessageId'],+ ['input', 'value', 'selectOption'],+ ],+ },+ updateEmailThreadLabel: {+ targets: ['GraphqlSoupEmailThread'],+ argumentPaths: [+ ['input', 'labelId'],+ ['input', 'threadId'],+ ],+ },+ },+ GraphqlUser: {+ emailThread: {+ targets: ['GraphqlSoupEmailThread'],+ argumentPaths: [['input', 'threadId']],+ },+ },+} as const;++export type GeneratedEntityResolverSchema = typeof entityResolverSchema;+export type GeneratedEntityResolverTarget =+ | 'GraphqlChannelActivity'+ | 'GraphqlProperty'+ | 'GraphqlSoupEmailThread';+export type GeneratedEntityResolverArgumentPath =+ | readonly ['input', 'channelId']+ | readonly ['input', 'labelId']+ | readonly ['input', 'propertyDefinitionId']+ | readonly ['input', 'threadId']+ | readonly ['input', 'value', 'entityReference', 'specificMessageId']+ | readonly ['input', 'value', 'selectOption'];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.tsindex 424c5a1f9b..068f1efdb7 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@@ -31,8 +31,20 @@ describe('createTauriCacheHost', () => {));const host = createTauriCacheHost({ scope: 'scope-1', hotCapacity: 42 });+ const entityResolvers = [+ {+ parentType: 'GraphqlUser',+ fieldName: 'emailThread',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'threadId'],+ },+ ];- const result = await host.readQuery({ opKey: 7, query: '{ x }' });+ const result = await host.readQuery({+ opKey: 7,+ query: '{ x }',+ entityResolvers,+ });expect(result).toEqual({ kind: 'miss' });expect(invokeMock).toHaveBeenCalledWith('graphql_cache_init', {@@ -44,6 +56,7 @@ describe('createTauriCacheHost', () => {query: '{ x }',operationName: undefined,variables: undefined,+ entityResolvers,});});diff --git a/apps/web/src/lib/graphql-cache/host/tauri-host.ts b/apps/web/src/lib/graphql-cache/host/tauri-host.tsindex 2a1704a1fc..f3c7b6359a 100644--- a/apps/web/src/lib/graphql-cache/host/tauri-host.ts+++ b/apps/web/src/lib/graphql-cache/host/tauri-host.ts@@ -156,6 +156,7 @@ export function createTauriCacheHost(options: TauriHostOptions): CacheHost {query: args.query,operationName: args.operationName,variables: args.variables,+ entityResolvers: args.entityResolvers,});},diff --git a/apps/web/src/lib/graphql-cache/host/types.ts b/apps/web/src/lib/graphql-cache/host/types.tsindex 9b105fba2e..8e2f2ac8b4 100644--- a/apps/web/src/lib/graphql-cache/host/types.ts+++ b/apps/web/src/lib/graphql-cache/host/types.ts@@ -5,6 +5,7 @@* - tauri-host.ts (Phase 3b): Tauri IPC to the native engine*/+import type { EntityResolverWire } from '../exchange/entity-resolvers';import type {CachedQueryInstanceWire,CachedQueryVariantWire,@@ -30,6 +31,8 @@ export interface CacheReadArgs {variables?: Record<string, unknown>;/** Prioritizes a pushed, user-visible refresh over incidental reads. */priority?: CacheReadPriority;+ /** Read-only synthetic entity relations compiled by the exchange. */+ entityResolvers?: readonly EntityResolverWire[];}export interface InspectQueryArgs {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.tsindex 214769a25d..7f23711400 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@@ -137,16 +137,29 @@ describe('createWorkerCacheHost', () => {}vi.stubGlobal('SharedWorker', FakeSharedWorker);const host = createWorkerCacheHost({ scope: 'scope-1' });+ const entityResolvers = [+ {+ parentType: 'GraphqlUser',+ fieldName: 'emailThread',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'threadId'],+ },+ ];await expect(host.readQuery({opKey: 7,query: 'query GroupSoup { groupSoup }',priority: 'user-visible',+ entityResolvers,})).resolves.toEqual({ kind: 'hit', data: { soup: true } });expect(requests).toContainEqual(- expect.objectContaining({ kind: 'read', priority: 'user-visible' })+ expect.objectContaining({+ kind: 'read',+ priority: 'user-visible',+ entityResolvers,+ }));host.dispose();});diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.ts b/apps/web/src/lib/graphql-cache/host/worker-host.tsindex 5df05f832c..70c23bead6 100644--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts@@ -186,6 +186,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {operationName: args.operationName,variables: args.variables,priority: args.priority,+ entityResolvers: args.entityResolvers,})) as ReadResult;},diff --git a/apps/web/src/lib/graphql-cache/index.ts b/apps/web/src/lib/graphql-cache/index.tsindex 7a73ed6c17..e25927a81b 100644--- a/apps/web/src/lib/graphql-cache/index.ts+++ b/apps/web/src/lib/graphql-cache/index.ts@@ -3,6 +3,13 @@* Design doc: apps/web/docs/graphql-normalized-cache-plan.md*/+export {+ compileEntityResolvers,+ type EntityFromArgumentDescriptor,+ type EntityResolverConfig,+ type EntityResolverWire,+ entityFromArgument,+} from './exchange/entity-resolvers';export {type CachedSelection,type CachedVariant,diff --git a/apps/web/src/lib/graphql-cache/protocol.ts b/apps/web/src/lib/graphql-cache/protocol.tsindex dd76ca518a..dd0ada45ec 100644--- a/apps/web/src/lib/graphql-cache/protocol.ts+++ b/apps/web/src/lib/graphql-cache/protocol.ts@@ -1,3 +1,5 @@+import type { EntityResolverWire } from './exchange/entity-resolvers';+/*** Wire protocol between page contexts and the cache worker (the `CacheHost`* RPC from the design doc, apps/web/docs/graphql-normalized-cache-plan.md §4).@@ -184,6 +186,8 @@ export type CacheRequest = { id: number } & (variables?: Record<string, unknown>;/** May overtake unrelated observational reads, never ordering barriers. */priority?: CacheReadPriority;+ /** Per-read synthetic entity relations. */+ entityResolvers?: readonly EntityResolverWire[];}| {kind: 'write';diff --git a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts b/apps/web/src/lib/graphql-cache/worker/wasm-module.tsindex 9d5fe6c30e..8c92128444 100644--- a/apps/web/src/lib/graphql-cache/worker/wasm-module.ts+++ b/apps/web/src/lib/graphql-cache/worker/wasm-module.ts@@ -8,6 +8,7 @@* src/lib/graphql-cache/wasm/ (gitignored).*/+import type { EntityResolverWire } from '../exchange/entity-resolvers';import type {CachedQueryInstanceWire,CachedQueryVariantWire,@@ -27,7 +28,8 @@ export interface CacheEngine {opId: string | undefined,query: string,operationName: string | undefined,- variables: Record<string, unknown> | undefined+ variables: Record<string, unknown> | undefined,+ entityResolvers: readonly EntityResolverWire[] | undefined): Promise<ReadResult>;readRecords(document: string,diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.test.tsindex dc0e67c73e..3a2b429151 100644--- a/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.test.ts@@ -338,6 +338,91 @@ describe('CacheWorkerCore', () => {});});+ it('does not coalesce reads with different entity resolver semantics', async () => {+ let releaseBlocker!: () => void;+ let markBlockerStarted!: () => void;+ const blocker = new Promise<void>((resolve) => {+ releaseBlocker = resolve;+ });+ const blockerStarted = new Promise<void>((resolve) => {+ markBlockerStarted = resolve;+ });+ const readQuery = vi.fn(+ async (+ opId: string | undefined,+ _query?: string,+ _operationName?: string,+ _variables?: Record<string, unknown>,+ _entityResolvers?: readonly unknown[]+ ) => {+ if (opId === 'client:blocker') {+ markBlockerStarted();+ await blocker;+ }+ return { kind: 'miss' as const };+ }+ );+ loadCacheWasmMock.mockResolvedValue({+ openCache: vi.fn().mockResolvedValue({ readQuery }),+ });+ const port = { postMessage: vi.fn() };+ const core = new CacheWorkerCore();+ await core.handleRequest(port, {+ id: 1,+ kind: 'init',+ scope: 'scope-1',+ });++ const running = core.handleRequest(port, {+ id: 2,+ kind: 'read',+ opId: 'client:blocker',+ query: 'query Blocker { blocker }',+ });+ await blockerStarted;+ const firstResolvers = [+ {+ parentType: 'GraphqlUser',+ fieldName: 'emailThread',+ targetType: 'GraphqlSoupEmailThread',+ argumentPath: ['input', 'threadId'],+ },+ ];+ const secondResolvers = [+ {+ parentType: 'GraphqlUser',+ fieldName: 'emailThread',+ targetType: 'GraphqlSoupDocument',+ argumentPath: ['input', 'threadId'],+ },+ ];+ const first = core.handleRequest(port, {+ id: 3,+ kind: 'read',+ opId: 'client:entity',+ query: 'query Entity { entity }',+ entityResolvers: firstResolvers,+ });+ const second = core.handleRequest(port, {+ id: 4,+ kind: 'read',+ opId: 'client:entity',+ query: 'query Entity { entity }',+ entityResolvers: secondResolvers,+ });++ releaseBlocker();+ await Promise.all([running, first, second]);+ const entityCalls = readQuery.mock.calls.filter(+ ([opId]) => opId === 'client:entity'+ );+ expect(entityCalls).toHaveLength(2);+ expect(entityCalls.map((call) => call[4])).toEqual([+ firstResolvers,+ secondResolvers,+ ]);+ });+it('does not reorder or coalesce reads across operation teardown', async () => {const order: string[] = [];let releaseBlocker!: () => void;diff --git a/apps/web/src/lib/graphql-cache/worker/worker-core.ts b/apps/web/src/lib/graphql-cache/worker/worker-core.tsindex 382b16e2a3..5b0160b5ee 100644--- a/apps/web/src/lib/graphql-cache/worker/worker-core.ts+++ b/apps/web/src/lib/graphql-cache/worker/worker-core.ts@@ -72,6 +72,7 @@ function readSignature(request: CacheRequest): string | undefined {request.query,request.operationName ?? null,request.variables ?? null,+ request.entityResolvers ?? null,]);}@@ -197,7 +198,8 @@ export class CacheWorkerCore {request.opId,request.query,request.operationName,- request.variables+ request.variables,+ request.entityResolvers);return result;})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.tsindex dc67d7b525..a88fce49a2 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@@ -11,6 +11,7 @@ import type { CacheHost } from '@graphql-cache/host/types';import {createTauriCacheHost,createWorkerCacheHost,+ entityFromArgument,} from '@graphql-cache/index';import { registerCacheHost } from '@graphql-cache/lifecycle';import { getOrCreateCacheScope } from '@graphql-cache/scope';@@ -167,6 +168,14 @@ export function getGraphqlSoupClient(): Client {url: `${dssHost}/items/soup/graphql`,exchanges: [normalizedCacheExchange(host, {+ entityResolvers: {+ GraphqlUser: {+ emailThread: entityFromArgument('GraphqlSoupEmailThread', [+ 'input',+ 'threadId',+ ]),+ },+ },// Session identity witness: the viewer id present on every soup// response. A response for a different user silently wipes and// rebinds the cache (see @graphql-cache/scope).diff --git a/apps/web/tauri/graphql_cache_plugin/src/commands.rs b/apps/web/tauri/graphql_cache_plugin/src/commands.rsindex 8962ae2e46..232707e76d 100644--- a/apps/web/tauri/graphql_cache_plugin/src/commands.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/commands.rs@@ -16,6 +16,7 @@ use crate::engine::{use crate::{CacheState, InitializedCache, emit_cache_changed, emit_mutation_settled, emit_ops_affected,};+use cache_core::entity_resolver::EntityResolver;use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};use cache_core::query_inspection::{CachedQueryInstance, CachedQueryVariant};use cache_core::record_selection::{RecordCursor, SelectedRecordPage};@@ -89,9 +90,16 @@ pub async fn graphql_cache_read(query: String,operation_name: Option<String>,variables: Option<Variables>,+ entity_resolvers: Option<Vec<EntityResolver>>,) -> Result<ReadResultWire, String> {engine_handle(&state)?- .read(op_id, query, operation_name, variables.unwrap_or_default())+ .read(+ op_id,+ query,+ operation_name,+ variables.unwrap_or_default(),+ entity_resolvers.unwrap_or_default(),+ ).await}diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine.rs b/apps/web/tauri/graphql_cache_plugin/src/engine.rsindex 2da2000171..cf445640b6 100644--- a/apps/web/tauri/graphql_cache_plugin/src/engine.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/engine.rs@@ -15,6 +15,7 @@ use cache_core::deps::OpId;use cache_core::engine::{BeginOptimisticWrite, Engine, InitialClaimOutcome, ReadResult, WriteResult,};+use cache_core::entity_resolver::EntityResolver;use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};use cache_core::query_inspection::{CachedQueryInstance, CachedQueryVariant, QueryInspection};use cache_core::queue::{ClaimedMutation, MutationClaimRequest, MutationClaimToken};@@ -219,12 +220,19 @@ impl EngineHandle {query: String,operation_name: Option<String>,variables: Variables,+ entity_resolvers: Vec<EntityResolver>,) -> Result<ReadResultWire, String> {let mut state = self.inner.lock().await;let EngineState { engine, ops } = &mut *state;let op = op_id.map(|name| ops.intern(&name));engine- .read_query(op, &query, operation_name.as_deref(), &variables)+ .read_query_with_entity_resolvers(+ op,+ &query,+ operation_name.as_deref(),+ &variables,+ &entity_resolvers,+ ).await.map(|result| match result {ReadResult::Hit { data } => ReadResultWire::Hit { data },diff --git a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rsindex f9674dd0b2..f17e14a19a 100644--- a/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs+++ b/apps/web/tauri/graphql_cache_plugin/src/engine/test.rs@@ -52,6 +52,7 @@ fn read(handle: &EngineHandle, op_id: Option<&str>) -> ReadResultWire {QUERY.to_string(),Some("Soup".to_string()),variables(),+ Vec::new(),)).unwrap()}@@ -71,6 +72,53 @@ fn write_then_read_round_trips() {assert_eq!(data, soup_data(false));}+#[test]+fn entity_resolvers_cross_the_native_engine_boundary() {+ let handle = spawn_handle();+ write(+ &handle,+ None,+ serde_json::json!({+ "user": {+ "id": "user-1",+ "soup": {+ "nextCursor": null,+ "items": [{+ "__typename": "GraphqlSoupEmailThread",+ "id": "thread-1"+ }]+ }+ }+ }),+ None,+ );+ let query = r#"query Email($input: EmailThreadInput!) {+ user { id emailThread(input: $input) { __typename id } }+ }"#;+ let serde_json::Value::Object(variables) =+ serde_json::json!({"input": {"threadId": "thread-1"}})+ else {+ unreachable!()+ };+ let result = block_on(handle.read(+ Some("webview:1".to_string()),+ query.to_string(),+ Some("Email".to_string()),+ variables,+ vec![EntityResolver {+ parent_type: "GraphqlUser".to_string(),+ field_name: "emailThread".to_string(),+ target_type: "GraphqlSoupEmailThread".to_string(),+ argument_path: vec!["input".to_string(), "threadId".to_string()],+ }],+ ))+ .unwrap();+ let ReadResultWire::Hit { data } = result else {+ panic!("expected resolver hit")+ };+ assert_eq!(data["user"]["emailThread"]["id"], "thread-1");+}+#[test]fn record_selection_returns_native_cache_entities() {let handle = spawn_handle();diff --git a/crates/client/cache-core/src/denormalize.rs b/crates/client/cache-core/src/denormalize.rsindex 5aefa5b596..47cecc5247 100644--- a/crates/client/cache-core/src/denormalize.rs+++ b/crates/client/cache-core/src/denormalize.rs@@ -7,7 +7,10 @@//! field is a cache miss (Phase 1: no partial results — nullability-based//! partials are a later phase; the metadata is already generated).-use crate::document::{FieldNode, MissingVariable, Operation, Selection, resolve_args_key};+use crate::document::{+ FieldNode, MissingVariable, Operation, Selection, resolve_args, resolved_args_key,+};+use crate::entity_resolver::EntityResolverLookup;use crate::meta;use crate::value::{CacheValue, EntityKey, Record, field_key};use serde_json::Value as Json;@@ -64,13 +67,31 @@ pub fn denormalize(source: &impl RecordSource,deps: &mut BTreeSet<EntityKey<'static>>,) -> Result<ReadOutcome, DenormalizeError> {- denormalize_record(+ denormalize_with_entity_resolvers(+ op,+ variables,+ source,+ deps,+ &EntityResolverLookup::default(),+ )+}++/// Attempts to answer `op` while applying validated read-only entity links.+pub fn denormalize_with_entity_resolvers(+ op: &Operation,+ variables: &serde_json::Map<String, Json>,+ source: &impl RecordSource,+ deps: &mut BTreeSet<EntityKey<'static>>,+ entity_resolvers: &EntityResolverLookup,+) -> Result<ReadOutcome, DenormalizeError> {+ denormalize_record_with_entity_resolvers(&EntityKey::root(),meta::QUERY_ROOT_TYPE,&op.selection_set,variables,source,deps,+ entity_resolvers,)}@@ -82,11 +103,32 @@ pub fn denormalize_record(variables: &serde_json::Map<String, Json>,source: &impl RecordSource,deps: &mut BTreeSet<EntityKey<'static>>,+) -> Result<ReadOutcome, DenormalizeError> {+ denormalize_record_with_entity_resolvers(+ key,+ type_name,+ selections,+ variables,+ source,+ deps,+ &EntityResolverLookup::default(),+ )+}++fn denormalize_record_with_entity_resolvers(+ key: &EntityKey<'static>,+ type_name: &str,+ selections: &[Selection],+ variables: &serde_json::Map<String, Json>,+ source: &impl RecordSource,+ deps: &mut BTreeSet<EntityKey<'static>>,+ entity_resolvers: &EntityResolverLookup,) -> Result<ReadOutcome, DenormalizeError> {let mut walk = Walk {variables,source,deps,+ entity_resolvers,missing_records: BTreeSet::new(),miss: None,};@@ -111,6 +153,7 @@ struct Walk<'a, S: RecordSource> {variables: &'a serde_json::Map<String, Json>,source: &'a S,deps: &'a mut BTreeSet<EntityKey<'static>>,+ entity_resolvers: &'a EntityResolverLookup,missing_records: BTreeSet<EntityKey<'static>>,/// First field-level miss encountered.miss: Option<(EntityKey<'static>, String)>,@@ -160,14 +203,34 @@ impl<'a, S: RecordSource> Walk<'a, S> {field: f.name.clone(),}})?;- let args = resolve_args_key(f, self.variables)?;- let storage_key = field_key(&f.name, args.as_deref());+ let entity_resolver = self.entity_resolvers.get(concrete, &f.name);+ let arguments = match resolve_args(f, self.variables) {+ Ok(arguments) => arguments,+ Err(_) if entity_resolver.is_some() => {+ self.mark_miss(owner, f.name.clone());+ continue;+ }+ Err(error) => return Err(error.into()),+ };+ let args_key = resolved_args_key(f, &arguments);+ let storage_key = field_key(&f.name, args_key.as_deref());- let Some(value) = fields.get(&storage_key) else {- if self.miss.is_none() {- self.miss = Some((owner.clone(), storage_key));+ if let Some(entity_resolver) = entity_resolver {+ let Some(target_key) = entity_resolver.entity_key(&arguments) else {+ self.mark_miss(owner, storage_key);+ continue;+ };+ let json =+ self.read_record(&target_key, &entity_resolver.target_type, &f.selection_set)?;+ if let Some(json) = json {+ out.insert(f.response_key.clone(), json);}continue;+ }++ let Some(value) = fields.get(&storage_key) else {+ self.mark_miss(owner, storage_key);+ continue;};let json = self.read_value(owner, f, fmeta.ty.name, value)?;match json {@@ -180,6 +243,12 @@ impl<'a, S: RecordSource> Walk<'a, S> {Ok(Some(Json::Object(out)))}+ fn mark_miss(&mut self, owner: &EntityKey<'static>, field: String) {+ if self.miss.is_none() {+ self.miss = Some((owner.clone(), field));+ }+ }+fn read_value(&mut self,owner: &EntityKey<'static>,diff --git a/crates/client/cache-core/src/document.rs b/crates/client/cache-core/src/document.rsindex 10e087295a..36ba6ffa4c 100644--- a/crates/client/cache-core/src/document.rs+++ b/crates/client/cache-core/src/document.rs@@ -399,20 +399,35 @@ pub fn resolve_arg(})}-/// Resolves a field's arguments to a canonical string (`None` when the field-/// has no arguments), for use in field storage keys.-pub fn resolve_args_key(+/// Resolves all of a field's arguments against operation variables.+pub fn resolve_args(field: &FieldNode,variables: &serde_json::Map<String, Json>,-) -> Result<Option<String>, MissingVariable> {- if field.arguments.is_empty() {- return Ok(None);- }+) -> Result<serde_json::Map<String, Json>, MissingVariable> {let mut map = serde_json::Map::new();for (name, value) in &field.arguments {map.insert(name.clone(), resolve_arg(value, variables)?);}- Ok(Some(canonical_json(&Json::Object(map))))+ Ok(map)+}++/// Converts already-resolved field arguments to their canonical storage-key+/// suffix (`None` when the field declares no arguments).+pub fn resolved_args_key(+ field: &FieldNode,+ arguments: &serde_json::Map<String, Json>,+) -> Option<String> {+ (!field.arguments.is_empty()).then(|| canonical_json(&Json::Object(arguments.clone())))+}++/// Resolves a field's arguments to a canonical string (`None` when the field+/// has no arguments), for use in field storage keys.+pub fn resolve_args_key(+ field: &FieldNode,+ variables: &serde_json::Map<String, Json>,+) -> Result<Option<String>, MissingVariable> {+ let arguments = resolve_args(field, variables)?;+ Ok(resolved_args_key(field, &arguments))}#[cfg(test)]diff --git a/crates/client/cache-core/src/engine.rs b/crates/client/cache-core/src/engine.rsindex 168e226a58..6bed2745d4 100644--- a/crates/client/cache-core/src/engine.rs+++ b/crates/client/cache-core/src/engine.rs@@ -3,10 +3,12 @@//! Tauri) expose over RPC.use crate::denormalize::{- DenormalizeError, ReadOutcome, RecordSource, denormalize, denormalize_record,+ DenormalizeError, ReadOutcome, RecordSource, denormalize_record,+ denormalize_with_entity_resolvers,};use crate::deps::{DepIndex, OpId};use crate::document::{Document, DocumentError, OperationKind};+use crate::entity_resolver::{EntityResolver, EntityResolverError, EntityResolverLookup};use crate::link_patch::{LinkPatchError, OptimisticLinkPatch, QueryRevalidation, apply_link_patches,deduplicate_patches, missing_patch_record,@@ -42,6 +44,8 @@ pub enum EngineError<S: std::error::Error + 'static> {#[error(transparent)]Denormalize(#[from] DenormalizeError),#[error(transparent)]+ EntityResolver(#[from] EntityResolverError),+ #[error(transparent)]LinkPatch(#[from] LinkPatchError),#[error(transparent)]QueryInspection(#[from] QueryInspectionError),@@ -362,6 +366,21 @@ impl<S: Storage> Engine<S> {operation_name: Option<&str>,variables: &serde_json::Map<String, Json>,) -> Result<ReadResult, EngineError<S::Error>> {+ self.read_query_with_entity_resolvers(op_id, query, operation_name, variables, &[])+ .await+ }++ /// Attempts to answer a query while applying validated read-only entity+ /// relations. Resolver descriptors are request policy and never persisted.+ pub async fn read_query_with_entity_resolvers(+ &mut self,+ op_id: Option<OpId>,+ query: &str,+ operation_name: Option<&str>,+ variables: &serde_json::Map<String, Json>,+ entity_resolvers: &[EntityResolver],+ ) -> Result<ReadResult, EngineError<S::Error>> {+ let entity_resolvers = EntityResolverLookup::compile(entity_resolvers)?;self.hydrate_optimistic().await?;let doc = Self::document(&mut self.docs, query)?;let op = doc.operation(operation_name)?;@@ -401,7 +420,13 @@ impl<S: Storage> Engine<S> {fetched: &fetched_base,composed: &composed,};- match denormalize(op, variables, &source, &mut deps)? {+ match denormalize_with_entity_resolvers(+ op,+ variables,+ &source,+ &mut deps,+ &entity_resolvers,+ )? {ReadOutcome::Complete(data) => break ReadResult::Hit { data },ReadOutcome::Miss { .. } => break ReadResult::Miss,ReadOutcome::NeedRecords(missing) => {diff --git a/crates/client/cache-core/src/entity_resolver.rs b/crates/client/cache-core/src/entity_resolver.rsnew file mode 100644index 0000000000..528b9a39fd--- /dev/null+++ b/crates/client/cache-core/src/entity_resolver.rs@@ -0,0 +1,177 @@+//! Schema-validated, read-only entity resolver descriptors.+//!+//! Transport adapters deserialize [`EntityResolver`] values and the engine+//! compiles them into a field lookup for one read. Output relation metadata is+//! validated against the generated schema. Input argument metadata is not+//! currently generated in Rust; a nonexistent or non-scalar runtime path is+//! therefore handled safely as a cache miss by denormalization.++use crate::meta::{self, FieldKind, TypeKind};+use serde::{Deserialize, Serialize};+use std::collections::BTreeMap;+use thiserror::Error;++/// A singular entity relation derived from one resolved field-argument path.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct EntityResolver {+ /// Concrete object type that owns the configured field.+ pub parent_type: String,+ /// Schema field replaced by this resolver during reads.+ pub field_name: String,+ /// Concrete, `id: ID!` entity type addressed by the argument value.+ pub target_type: String,+ /// Path beginning with a GraphQL argument name.+ pub argument_path: Vec<String>,+}++/// Invalid untrusted entity resolver configuration.+#[derive(Debug, Error, PartialEq, Eq)]+pub enum EntityResolverError {+ /// The configured parent is absent from generated schema metadata.+ #[error("unknown entity resolver parent type `{0}`")]+ UnknownParent(String),+ /// Resolver parents must be concrete output objects.+ #[error("entity resolver parent `{0}` is not a concrete object")]+ ParentNotObject(String),+ /// The configured field is absent from its parent object.+ #[error("unknown entity resolver field `{parent}.{field}`")]+ UnknownField { parent: String, field: String },+ /// Entity resolvers only replace singular composite relations.+ #[error("entity resolver field `{parent}.{field}` is not a singular composite relation")]+ NotSingularComposite { parent: String, field: String },+ /// The configured target is absent from generated schema metadata.+ #[error("unknown entity resolver target type `{0}`")]+ UnknownTarget(String),+ /// Resolver targets must be concrete output objects.+ #[error("entity resolver target `{0}` is not a concrete object")]+ TargetNotObject(String),+ /// Resolver targets use the cache's single `id: ID!` key convention.+ #[error("entity resolver target `{0}` is not keyed by `id: ID!`")]+ TargetNotKeyable(String),+ /// The concrete target cannot satisfy the field's declared return type.+ #[error(+ "entity resolver target `{target}` is incompatible with `{parent}.{field}` return type `{declared}`"+ )]+ IncompatibleTarget {+ parent: String,+ field: String,+ target: String,+ declared: String,+ },+ /// A resolver path must contain at least one non-empty segment.+ #[error("entity resolver argument path for `{parent}.{field}` must be non-empty")]+ EmptyArgumentPath { parent: String, field: String },+ /// At most one resolver can replace a parent field.+ #[error("duplicate entity resolver for `{parent}.{field}`")]+ Duplicate { parent: String, field: String },+}++/// Validated lookup used by the synchronous denormalization walk.+#[derive(Debug, Default)]+pub struct EntityResolverLookup {+ by_parent: BTreeMap<String, BTreeMap<String, EntityResolver>>,+}++impl EntityResolverLookup {+ /// Validates descriptors against generated output schema metadata.+ pub fn compile(resolvers: &[EntityResolver]) -> Result<Self, EntityResolverError> {+ let mut by_parent = BTreeMap::<String, BTreeMap<String, EntityResolver>>::new();+ for resolver in resolvers {+ let parent = meta::type_meta(&resolver.parent_type)+ .ok_or_else(|| EntityResolverError::UnknownParent(resolver.parent_type.clone()))?;+ if parent.kind != TypeKind::Object {+ return Err(EntityResolverError::ParentNotObject(+ resolver.parent_type.clone(),+ ));+ }+ let field =+ meta::field_meta(&resolver.parent_type, &resolver.field_name).ok_or_else(|| {+ EntityResolverError::UnknownField {+ parent: resolver.parent_type.clone(),+ field: resolver.field_name.clone(),+ }+ })?;+ if field.ty.kind != FieldKind::Composite || field.ty.list {+ return Err(EntityResolverError::NotSingularComposite {+ parent: resolver.parent_type.clone(),+ field: resolver.field_name.clone(),+ });+ }++ let target = meta::type_meta(&resolver.target_type)+ .ok_or_else(|| EntityResolverError::UnknownTarget(resolver.target_type.clone()))?;+ if target.kind != TypeKind::Object {+ return Err(EntityResolverError::TargetNotObject(+ resolver.target_type.clone(),+ ));+ }+ if target.key_fields != Some(&["id"][..]) {+ return Err(EntityResolverError::TargetNotKeyable(+ resolver.target_type.clone(),+ ));+ }++ let declared = meta::type_meta(field.ty.name)+ .expect("generated composite field type has generated metadata");+ let compatible = match declared.kind {+ TypeKind::Object => declared.name == target.name,+ TypeKind::Interface | TypeKind::Union => {+ declared.possible_types.contains(&target.name)+ }+ };+ if !compatible {+ return Err(EntityResolverError::IncompatibleTarget {+ parent: resolver.parent_type.clone(),+ field: resolver.field_name.clone(),+ target: resolver.target_type.clone(),+ declared: declared.name.to_string(),+ });+ }+ if resolver.argument_path.is_empty()+ || resolver.argument_path.iter().any(String::is_empty)+ {+ return Err(EntityResolverError::EmptyArgumentPath {+ parent: resolver.parent_type.clone(),+ field: resolver.field_name.clone(),+ });+ }++ let fields = by_parent.entry(resolver.parent_type.clone()).or_default();+ if fields+ .insert(resolver.field_name.clone(), resolver.clone())+ .is_some()+ {+ return Err(EntityResolverError::Duplicate {+ parent: resolver.parent_type.clone(),+ field: resolver.field_name.clone(),+ });+ }+ }+ Ok(Self { by_parent })+ }++ /// Returns the resolver replacing `parent_type.field_name`, if configured.+ pub(crate) fn get(&self, parent_type: &str, field_name: &str) -> Option<&EntityResolver> {+ self.by_parent.get(parent_type)?.get(field_name)+ }+}++impl EntityResolver {+ /// Resolves a string/number id from an already-resolved argument object.+ pub(crate) fn entity_key(+ &self,+ arguments: &serde_json::Map<String, serde_json::Value>,+ ) -> Option<crate::value::EntityKey<'static>> {+ let mut value = arguments.get(self.argument_path.first()?)?;+ for segment in &self.argument_path[1..] {+ value = value.as_object()?.get(segment)?;+ }+ let id = match value {+ serde_json::Value::String(value) => value.clone(),+ serde_json::Value::Number(value) => value.to_string(),+ _ => return None,+ };+ Some(crate::value::EntityKey::entity(&self.target_type, &[&id]))+ }+}diff --git a/crates/client/cache-core/src/lib.rs b/crates/client/cache-core/src/lib.rsindex 0735c73ffe..086023df18 100644--- a/crates/client/cache-core/src/lib.rs+++ b/crates/client/cache-core/src/lib.rs@@ -7,6 +7,7 @@ pub mod denormalize;pub mod deps;pub mod document;pub mod engine;+pub mod entity_resolver;pub mod link_patch;pub mod meta;pub mod normalize;diff --git a/crates/client/cache-core/tests/entity_resolver.rs b/crates/client/cache-core/tests/entity_resolver.rsnew file mode 100644index 0000000000..fc2f5b96a1--- /dev/null+++ b/crates/client/cache-core/tests/entity_resolver.rs@@ -0,0 +1,565 @@+//! Entity-from-argument resolver behavior against the real Soup schema.++use cache_core::engine::{Engine, ReadResult};+use cache_core::entity_resolver::EntityResolver;+use cache_core::store::InMemoryStorage;+use cache_core::value::EntityKey;+use pollster::block_on;+use serde_json::{Value as Json, json};++const SOUP_EMAIL_QUERY: &str = r#"+query SoupEmail($input: SoupInput!) {+ user {+ id+ soup(input: $input) {+ items {+ __typename+ id+ ... on GraphqlSoupEmailThread {+ emailName: name+ ownerId+ }+ }+ nextCursor+ }+ }+}+"#;++const SOUP_EMAIL_WITHOUT_NAME_QUERY: &str = r#"+query SoupEmailWithoutName($input: SoupInput!) {+ user {+ id+ soup(input: $input) {+ items {+ __typename+ id+ ... on GraphqlSoupEmailThread { ownerId }+ }+ nextCursor+ }+ }+}+"#;++const DIRECT_EMAIL_QUERY: &str = r#"+query EmailThread($input: EmailThreadInput!) {+ viewer: user {+ id+ thread: emailThread(input: $input) {+ __typename+ id+ emailName: name+ ownerId+ }+ }+}+"#;++const INLINE_EMAIL_QUERY: &str = r#"+query InlineEmailThread {+ user {+ id+ emailThread(input: { threadId: "thread-1" }) {+ __typename+ id+ name+ ownerId+ }+ }+}+"#;++const NUMERIC_EMAIL_QUERY: &str = r#"+query NumericEmailThread {+ user {+ id+ emailThread(input: { threadId: 42 }) {+ __typename+ id+ name+ ownerId+ }+ }+}+"#;++const UPDATE_EMAIL_MUTATION: &str = r#"+mutation UpdateEmail($input: MarkEmailThreadSeenInput!) {+ markEmailThreadSeen(input: $input) {+ __typename+ id+ name+ ownerId+ }+}+"#;++fn resolver() -> EntityResolver {+ EntityResolver {+ parent_type: "GraphqlUser".to_string(),+ field_name: "emailThread".to_string(),+ target_type: "GraphqlSoupEmailThread".to_string(),+ argument_path: vec!["input".to_string(), "threadId".to_string()],+ }+}++fn object(value: Json) -> serde_json::Map<String, Json> {+ let Json::Object(value) = value else {+ panic!("expected object")+ };+ value+}++fn soup_variables() -> serde_json::Map<String, Json> {+ object(json!({ "input": { "limit": 10 } }))+}++fn direct_variables(id: Json) -> serde_json::Map<String, Json> {+ object(json!({ "input": { "threadId": id } }))+}++fn soup_response(id: Json, name: &str) -> Json {+ json!({+ "user": {+ "id": "user-1",+ "soup": {+ "items": [{+ "__typename": "GraphqlSoupEmailThread",+ "id": id,+ "emailName": name,+ "ownerId": "user-1"+ }],+ "nextCursor": null+ }+ }+ })+}++async fn seed_thread(engine: &mut Engine<InMemoryStorage>, id: Json, name: &str) {+ engine+ .write_query(+ None,+ SOUP_EMAIL_QUERY,+ Some("SoupEmail"),+ &soup_variables(),+ &soup_response(id, name),+ None,+ )+ .await+ .unwrap();+}++#[test]+fn unseen_direct_relation_misses_without_resolver_and_hits_with_it() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ seed_thread(&mut engine, json!("thread-1"), "Roadmap").await;+ let variables = direct_variables(json!("thread-1"));++ assert!(matches!(+ engine+ .read_query(None, DIRECT_EMAIL_QUERY, Some("EmailThread"), &variables)+ .await+ .unwrap(),+ ReadResult::Miss+ ));++ let ReadResult::Hit { data } = engine+ .read_query_with_entity_resolvers(+ None,+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &variables,+ &[resolver()],+ )+ .await+ .unwrap()+ else {+ panic!("expected resolver hit")+ };+ assert_eq!(+ data,+ json!({+ "viewer": {+ "id": "user-1",+ "thread": {+ "__typename": "GraphqlSoupEmailThread",+ "id": "thread-1",+ "emailName": "Roadmap",+ "ownerId": "user-1"+ }+ }+ })+ );++ // The synthetic relation was not persisted by the resolver read.+ assert!(matches!(+ engine+ .read_query(None, DIRECT_EMAIL_QUERY, Some("EmailThread"), &variables)+ .await+ .unwrap(),+ ReadResult::Miss+ ));+ });+}++#[test]+fn supports_inline_arguments_aliases_and_string_or_numeric_ids() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ seed_thread(&mut engine, json!("thread-1"), "String id").await;++ let ReadResult::Hit { data } = engine+ .read_query_with_entity_resolvers(+ None,+ INLINE_EMAIL_QUERY,+ Some("InlineEmailThread"),+ &serde_json::Map::new(),+ &[resolver()],+ )+ .await+ .unwrap()+ else {+ panic!("expected inline hit")+ };+ assert_eq!(data["user"]["emailThread"]["name"], json!("String id"));++ seed_thread(&mut engine, json!(42), "Numeric id").await;+ let ReadResult::Hit { data } = engine+ .read_query_with_entity_resolvers(+ None,+ NUMERIC_EMAIL_QUERY,+ Some("NumericEmailThread"),+ &serde_json::Map::new(),+ &[resolver()],+ )+ .await+ .unwrap()+ else {+ panic!("expected numeric hit")+ };+ assert_eq!(data["user"]["emailThread"]["id"], json!(42));+ assert_eq!(data["user"]["emailThread"]["name"], json!("Numeric id"));+ });+}++#[test]+fn absent_incomplete_and_malformed_runtime_values_are_misses() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ engine+ .write_query(+ None,+ SOUP_EMAIL_WITHOUT_NAME_QUERY,+ Some("SoupEmailWithoutName"),+ &soup_variables(),+ &json!({+ "user": {+ "id": "user-1",+ "soup": {+ "items": [{+ "__typename": "GraphqlSoupEmailThread",+ "id": "thread-1",+ "ownerId": "user-1"+ }],+ "nextCursor": null+ }+ }+ }),+ None,+ )+ .await+ .unwrap();++ for variables in [+ direct_variables(json!("absent")),+ direct_variables(Json::Null),+ direct_variables(json!({ "bad": true })),+ direct_variables(json!(true)),+ serde_json::Map::new(),+ ] {+ assert!(matches!(+ engine+ .read_query_with_entity_resolvers(+ None,+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &variables,+ &[resolver()],+ )+ .await+ .unwrap(),+ ReadResult::Miss+ ));+ }++ // The target exists, but `name` was never selected into its record.+ assert!(matches!(+ engine+ .read_query_with_entity_resolvers(+ None,+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &direct_variables(json!("thread-1")),+ &[resolver()],+ )+ .await+ .unwrap(),+ ReadResult::Miss+ ));++ // Rust does not carry generated input metadata yet; an untrusted path+ // that cannot be followed is still safe and behaves as a miss.+ let mut nonexistent_path = resolver();+ nonexistent_path.argument_path = vec!["input".into(), "missing".into()];+ assert!(matches!(+ engine+ .read_query_with_entity_resolvers(+ None,+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &direct_variables(json!("thread-1")),+ &[nonexistent_path],+ )+ .await+ .unwrap(),+ ReadResult::Miss+ ));+ });+}++#[test]+fn resolver_overrides_stored_links_and_null() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ seed_thread(&mut engine, json!("thread-1"), "Resolved").await;+ let variables = direct_variables(json!("thread-1"));++ engine+ .write_query(+ None,+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &variables,+ &json!({+ "viewer": {+ "id": "user-1",+ "thread": {+ "__typename": "GraphqlSoupEmailThread",+ "id": "thread-2",+ "emailName": "Stored link",+ "ownerId": "user-1"+ }+ }+ }),+ None,+ )+ .await+ .unwrap();+ let ReadResult::Hit { data } = engine+ .read_query_with_entity_resolvers(+ None,+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &variables,+ &[resolver()],+ )+ .await+ .unwrap()+ else {+ panic!("expected resolver hit")+ };+ assert_eq!(data["viewer"]["thread"]["id"], json!("thread-1"));++ engine+ .write_query(+ None,+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &variables,+ &json!({ "viewer": { "id": "user-1", "thread": null } }),+ None,+ )+ .await+ .unwrap();+ let ReadResult::Hit { data } = engine+ .read_query_with_entity_resolvers(+ None,+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &variables,+ &[resolver()],+ )+ .await+ .unwrap()+ else {+ panic!("expected resolver to override null")+ };+ assert_eq!(data["viewer"]["thread"]["id"], json!("thread-1"));+ });+}++#[test]+fn synthetic_target_dependencies_are_registered_on_hits_and_misses() {+ block_on(async {+ let mut engine = Engine::new(InMemoryStorage::new());+ seed_thread(&mut engine, json!("thread-1"), "Before").await;+ let variables = direct_variables(json!("thread-1"));+ assert!(matches!(+ engine+ .read_query_with_entity_resolvers(+ Some(41),+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &variables,+ &[resolver()],+ )+ .await+ .unwrap(),+ ReadResult::Hit { .. }+ ));++ let update_variables = object(json!({ "input": { "threadId": "thread-1" } }));+ let write = engine+ .write_query(+ Some(2),+ UPDATE_EMAIL_MUTATION,+ Some("UpdateEmail"),+ &update_variables,+ &json!({+ "markEmailThreadSeen": {+ "__typename": "GraphqlSoupEmailThread",+ "id": "thread-1",+ "name": "After",+ "ownerId": "user-1"+ }+ }),+ None,+ )+ .await+ .unwrap();+ assert!(write.affected_ops.contains(&41));++ let target_key = EntityKey::entity("GraphqlSoupEmailThread", &["thread-1"]);+ let affected = engine.delete_keys(&[target_key]).await.unwrap();+ assert!(affected.contains(&41));+ assert!(matches!(+ engine+ .read_query_with_entity_resolvers(+ Some(41),+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &variables,+ &[resolver()],+ )+ .await+ .unwrap(),+ ReadResult::Miss+ ));++ assert!(matches!(+ engine+ .read_query_with_entity_resolvers(+ Some(42),+ DIRECT_EMAIL_QUERY,+ Some("EmailThread"),+ &direct_variables(json!("arrives-later")),+ &[resolver()],+ )+ .await+ .unwrap(),+ ReadResult::Miss+ ));+ let arrival_variables = object(json!({ "input": { "threadId": "arrives-later" } }));+ let arrival = engine+ .write_query(+ Some(2),+ UPDATE_EMAIL_MUTATION,+ Some("UpdateEmail"),+ &arrival_variables,+ &json!({+ "markEmailThreadSeen": {+ "__typename": "GraphqlSoupEmailThread",+ "id": "arrives-later",+ "name": "Arrived",+ "ownerId": "user-1"+ }+ }),+ None,+ )+ .await+ .unwrap();+ assert!(arrival.affected_ops.contains(&42));+ });+}++#[test]+fn rejects_invalid_untrusted_descriptors() {+ block_on(async {+ let valid_query = "query Viewer { user { id } }";+ let invalid = [+ EntityResolver {+ parent_type: "NoSuchParent".into(),+ ..resolver()+ },+ EntityResolver {+ parent_type: "GraphqlSoupEntity".into(),+ field_name: "metadata".into(),+ ..resolver()+ },+ EntityResolver {+ field_name: "noSuchField".into(),+ ..resolver()+ },+ EntityResolver {+ field_name: "id".into(),+ ..resolver()+ },+ EntityResolver {+ target_type: "NoSuchTarget".into(),+ ..resolver()+ },+ EntityResolver {+ target_type: "GraphqlSoupEntity".into(),+ ..resolver()+ },+ EntityResolver {+ target_type: "SoupPage".into(),+ ..resolver()+ },+ EntityResolver {+ target_type: "GraphqlSoupDocument".into(),+ ..resolver()+ },+ EntityResolver {+ argument_path: Vec::new(),+ ..resolver()+ },+ ];++ for descriptor in invalid {+ let error = engine_read_error(valid_query, &[descriptor]).await;+ assert!(+ error.contains("entity resolver"),+ "unexpected error: {error}"+ );+ }+ let error = engine_read_error(valid_query, &[resolver(), resolver()]).await;+ assert!(error.contains("duplicate entity resolver"));+ });+}++async fn engine_read_error(query: &str, resolvers: &[EntityResolver]) -> String {+ Engine::new(InMemoryStorage::new())+ .read_query_with_entity_resolvers(+ None,+ query,+ Some("Viewer"),+ &serde_json::Map::new(),+ resolvers,+ )+ .await+ .expect_err("descriptor must be rejected")+ .to_string()+}diff --git a/crates/client/cache-wasm/src/shell.rs b/crates/client/cache-wasm/src/shell.rsindex d60463e810..01083e203b 100644--- a/crates/client/cache-wasm/src/shell.rs+++ b/crates/client/cache-wasm/src/shell.rs@@ -1,6 +1,7 @@use async_lock::Mutex;use cache_core::deps::OpId;use cache_core::engine::{BeginOptimisticWrite, Engine, InitialClaimOutcome, ReadResult};+use cache_core::entity_resolver::EntityResolver;use cache_core::link_patch::{OptimisticLinkPatch, QueryRevalidation};use cache_core::query_inspection::QueryInspection;use cache_core::queue::{ClaimedMutation, MutationClaimRequest, MutationClaimToken};@@ -260,15 +261,23 @@ impl CacheEngine {query: String,operation_name: Option<String>,variables: JsValue,+ entity_resolvers: JsValue,) -> js_sys::Promise {let engine = self.engine.clone();let ops = self.ops.clone();future_to_promise(async move {let vars = parse_variables(variables)?;+ let entity_resolvers: Vec<EntityResolver> = parse_vec(entity_resolvers)?;let op = op_id.map(|name| ops.borrow_mut().intern(&name));let mut engine = engine.lock().await;let result = engine- .read_query(op, &query, operation_name.as_deref(), &vars)+ .read_query_with_entity_resolvers(+ op,+ &query,+ operation_name.as_deref(),+ &vars,+ &entity_resolvers,+ ).await.map_err(err_js)?;to_js(&match result {diff --git a/crates/client/cache-wasm/tests/web.rs b/crates/client/cache-wasm/tests/web.rsindex ad6848a44d..efd6a5f867 100644--- a/crates/client/cache-wasm/tests/web.rs+++ b/crates/client/cache-wasm/tests/web.rs@@ -51,6 +51,7 @@ async fn write_then_read_through_js_boundary() {QUERY.into(),Some("Soup".into()),js(vars.clone()),+ JsValue::UNDEFINED,)).await.unwrap();@@ -84,6 +85,7 @@ async fn write_then_read_through_js_boundary() {QUERY.into(),Some("Soup".into()),js(vars.clone()),+ JsValue::UNDEFINED,)).await.unwrap();@@ -132,6 +134,7 @@ async fn write_then_read_through_js_boundary() {QUERY.into(),Some("Soup".into()),js(vars.clone()),+ JsValue::UNDEFINED,)).await.unwrap();@@ -146,6 +149,7 @@ async fn write_then_read_through_js_boundary() {QUERY.into(),Some("Soup".into()),js(vars),+ JsValue::UNDEFINED,)).await.unwrap();@@ -158,6 +162,64 @@ async fn write_then_read_through_js_boundary() {destroy_cache("wasm-shell-test".into()).await.unwrap();}+#[wasm_bindgen_test]+async fn entity_resolvers_cross_the_js_boundary() {+ destroy_cache("wasm-shell-entity-resolver".into())+ .await+ .unwrap();+ let engine = open_cache("wasm-shell-entity-resolver".into(), None)+ .await+ .unwrap();+ let soup_variables = serde_json::json!({"input": {"limit": 1}});+ JsFuture::from(engine.write_query(+ None,+ QUERY.into(),+ Some("Soup".into()),+ js(soup_variables),+ js(serde_json::json!({+ "user": {+ "id": "user-1",+ "soup": {+ "nextCursor": null,+ "items": [{+ "__typename": "GraphqlSoupEmailThread",+ "id": "thread-1"+ }]+ }+ }+ })),+ None,+ ))+ .await+ .unwrap();++ let direct_query = r#"query Email($input: EmailThreadInput!) {+ user { id emailThread(input: $input) { __typename id } }+ }"#;+ let result = JsFuture::from(engine.read_query(+ Some("tab1:entity".into()),+ direct_query.into(),+ Some("Email".into()),+ js(serde_json::json!({"input": {"threadId": "thread-1"}})),+ js(serde_json::json!([{+ "parentType": "GraphqlUser",+ "fieldName": "emailThread",+ "targetType": "GraphqlSoupEmailThread",+ "argumentPath": ["input", "threadId"]+ }])),+ ))+ .await+ .unwrap();+ let result: serde_json::Value = serde_wasm_bindgen::from_value(result).unwrap();+ assert_eq!(result["kind"], "hit");+ assert_eq!(result["data"]["user"]["emailThread"]["id"], "thread-1");++ JsFuture::from(engine.close()).await.unwrap();+ destroy_cache("wasm-shell-entity-resolver".into())+ .await+ .unwrap();+}+const PROPERTY_QUERY: &str = r#"query Soup($input: SoupInput!) {user { id soup(input: $input) { nextCursor items {__typename@@ -201,6 +263,7 @@ async fn optimistic_write_round_trip() {PROPERTY_QUERY.into(),Some("Soup".into()),js(vars.clone()),+ JsValue::UNDEFINED,)).await.unwrap();@@ -246,6 +309,7 @@ async fn optimistic_write_round_trip() {PROPERTY_QUERY.into(),Some("Soup".into()),js(vars.clone()),+ JsValue::UNDEFINED,)).await.unwrap();