From 5a8bfdf10588bb1c39ebdce91067a7ba876f7469 Mon Sep 17 00:00:00 2001 From: Andreas Marek Date: Sun, 15 Nov 2026 09:24:30 +1000 Subject: [PATCH 1/2] Add opt-in NormalizedDocument built during validation --- docs/normalized-document.md | 197 + .../DFSelectionSetPerformance.java | 119 +- src/jmh/java/performance/ENF1Performance.java | 70 - src/jmh/java/performance/ENF2Performance.java | 59 - .../ENFDeepIntrospectionPerformance.java | 128 - .../performance/ENFExtraLargePerformance.java | 68 - src/main/java/graphql/GraphQL.java | 27 +- src/main/java/graphql/ParseAndValidate.java | 8 +- .../java/graphql/ParseAndValidateResult.java | 16 +- .../java/graphql/execution/Execution.java | 9 +- .../graphql/execution/ExecutionContext.java | 22 +- .../execution/ExecutionContextBuilder.java | 8 + .../graphql/execution/ExecutionStrategy.java | 13 +- .../java/graphql/execution/ResolveType.java | 7 +- .../conditional/ConditionalNodes.java | 60 +- .../execution/directives/QueryDirectives.java | 5 +- .../incremental/DeferredExecution.java | 4 - .../preparsed/PreparsedDocumentEntry.java | 20 +- .../graphql/normalized/ArgumentMaker.java | 110 - .../java/graphql/normalized/ENFMerger.java | 197 - .../normalized/ExecutableNormalizedField.java | 704 ---- .../ExecutableNormalizedOperation.java | 202 - .../ExecutableNormalizedOperationFactory.java | 985 ----- ...tableNormalizedOperationToAstCompiler.java | 473 --- .../normalized/NormalizedDocument.java | 111 + .../graphql/normalized/NormalizedField.java | 84 + .../normalized/NormalizedFieldCollector.java | 103 + .../normalized/NormalizedOperation.java | 69 + .../normalized/NormalizedSelection.java | 18 + .../normalized/NormalizedSelectionScope.java | 100 + .../normalized/NormalizedSelectionSet.java | 55 + .../ValueToVariableValueCompiler.java | 138 - .../normalized/VariableAccumulator.java | 70 - .../graphql/normalized/VariablePredicate.java | 44 - .../VariableValueWithDefinition.java | 30 - .../NormalizedDeferredExecution.java | 131 - .../normalized/nf/NormalizedDocument.java | 49 - .../nf/NormalizedDocumentFactory.java | 686 ---- .../normalized/nf/NormalizedField.java | 682 ---- .../normalized/nf/NormalizedFieldsMerger.java | 195 - .../normalized/nf/NormalizedOperation.java | 183 - .../nf/NormalizedOperationToAstCompiler.java | 249 -- .../schema/DataFetchingFieldSelectionSet.java | 39 +- .../DataFetchingFieldSelectionSetImpl.java | 479 +-- .../java/graphql/schema/SelectedField.java | 16 +- .../graphql/schema/SelectedFieldImpl.java | 134 + .../schema/UnavailableFieldSelectionSet.java | 58 + .../validation/DocumentValidationResult.java | 16 + .../validation/NormalizedDocumentBuilder.java | 99 + .../validation/OperationValidator.java | 24 +- .../java/graphql/validation/Validator.java | 13 +- .../graphql/TypeResolverExecutionTest.groovy | 4 +- .../execution/NormalizedValuesTest.groovy | 115 + .../OperationDirectivesResolverTest.groovy | 7 - .../QueryDirectivesIntegrationTest.groovy | 22 +- .../GoodFaithIntrospectionTest.groovy | 15 - .../GoodFaithMergedFieldsTest.groovy | 26 +- .../language/AstReconstructionTest.groovy | 44 + .../ExecutableNormalizedFieldTest.groovy | 143 - ...NormalizedOperationFactoryDeferTest.groovy | 1329 ------- ...tableNormalizedOperationFactoryTest.groovy | 3306 ----------------- ...izedOperationToAstCompilerDeferTest.groovy | 652 ---- ...perationToAstCompilerDirectivesTest.groovy | 194 - ...ormalizedOperationToAstCompilerTest.groovy | 2288 ------------ .../normalized/NormalizedDocumentTest.groovy | 437 +++ .../ValueToVariableValueCompilerTest.groovy | 134 - .../normalized/VariableAccumulatorTest.groovy | 46 - .../nf/NormalizedDocumentFactoryTest.groovy | 251 -- ...ormalizedOperationToAstCompilerTest.groovy | 257 -- ...taFetchingFieldSelectionSetImplTest.groovy | 83 +- .../LargeSchemaQueryComplexityTest.groovy | 83 +- .../groovy/readme/FieldSelectionExamples.java | 8 + .../nullability/NullableNormalizedUsage.java | 20 +- test-baseline.json | 212 +- 74 files changed, 2138 insertions(+), 14924 deletions(-) create mode 100644 docs/normalized-document.md delete mode 100644 src/jmh/java/performance/ENF1Performance.java delete mode 100644 src/jmh/java/performance/ENF2Performance.java delete mode 100644 src/jmh/java/performance/ENFDeepIntrospectionPerformance.java delete mode 100644 src/jmh/java/performance/ENFExtraLargePerformance.java delete mode 100644 src/main/java/graphql/normalized/ArgumentMaker.java delete mode 100644 src/main/java/graphql/normalized/ENFMerger.java delete mode 100644 src/main/java/graphql/normalized/ExecutableNormalizedField.java delete mode 100644 src/main/java/graphql/normalized/ExecutableNormalizedOperation.java delete mode 100644 src/main/java/graphql/normalized/ExecutableNormalizedOperationFactory.java delete mode 100644 src/main/java/graphql/normalized/ExecutableNormalizedOperationToAstCompiler.java create mode 100644 src/main/java/graphql/normalized/NormalizedDocument.java create mode 100644 src/main/java/graphql/normalized/NormalizedField.java create mode 100644 src/main/java/graphql/normalized/NormalizedFieldCollector.java create mode 100644 src/main/java/graphql/normalized/NormalizedOperation.java create mode 100644 src/main/java/graphql/normalized/NormalizedSelection.java create mode 100644 src/main/java/graphql/normalized/NormalizedSelectionScope.java create mode 100644 src/main/java/graphql/normalized/NormalizedSelectionSet.java delete mode 100644 src/main/java/graphql/normalized/ValueToVariableValueCompiler.java delete mode 100644 src/main/java/graphql/normalized/VariableAccumulator.java delete mode 100644 src/main/java/graphql/normalized/VariablePredicate.java delete mode 100644 src/main/java/graphql/normalized/VariableValueWithDefinition.java delete mode 100644 src/main/java/graphql/normalized/incremental/NormalizedDeferredExecution.java delete mode 100644 src/main/java/graphql/normalized/nf/NormalizedDocument.java delete mode 100644 src/main/java/graphql/normalized/nf/NormalizedDocumentFactory.java delete mode 100644 src/main/java/graphql/normalized/nf/NormalizedField.java delete mode 100644 src/main/java/graphql/normalized/nf/NormalizedFieldsMerger.java delete mode 100644 src/main/java/graphql/normalized/nf/NormalizedOperation.java delete mode 100644 src/main/java/graphql/normalized/nf/NormalizedOperationToAstCompiler.java create mode 100644 src/main/java/graphql/schema/SelectedFieldImpl.java create mode 100644 src/main/java/graphql/schema/UnavailableFieldSelectionSet.java create mode 100644 src/main/java/graphql/validation/DocumentValidationResult.java create mode 100644 src/main/java/graphql/validation/NormalizedDocumentBuilder.java create mode 100644 src/test/groovy/graphql/execution/NormalizedValuesTest.groovy create mode 100644 src/test/groovy/graphql/language/AstReconstructionTest.groovy delete mode 100644 src/test/groovy/graphql/normalized/ExecutableNormalizedFieldTest.groovy delete mode 100644 src/test/groovy/graphql/normalized/ExecutableNormalizedOperationFactoryDeferTest.groovy delete mode 100644 src/test/groovy/graphql/normalized/ExecutableNormalizedOperationFactoryTest.groovy delete mode 100644 src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerDeferTest.groovy delete mode 100644 src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerDirectivesTest.groovy delete mode 100644 src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerTest.groovy create mode 100644 src/test/groovy/graphql/normalized/NormalizedDocumentTest.groovy delete mode 100644 src/test/groovy/graphql/normalized/ValueToVariableValueCompilerTest.groovy delete mode 100644 src/test/groovy/graphql/normalized/VariableAccumulatorTest.groovy delete mode 100644 src/test/groovy/graphql/normalized/nf/NormalizedDocumentFactoryTest.groovy delete mode 100644 src/test/groovy/graphql/normalized/nf/NormalizedOperationToAstCompilerTest.groovy diff --git a/docs/normalized-document.md b/docs/normalized-document.md new file mode 100644 index 0000000000..96a7a2d1ce --- /dev/null +++ b/docs/normalized-document.md @@ -0,0 +1,197 @@ +# NormalizedDocument and lookahead + +`NormalizedDocument` is an immutable selection graph built during document +validation. It describes every operation and retains shared fragment bodies, +source locations, aliases, argument AST values, directives and type conditions. +It contains no execution variables, resolved arguments or mutable parent pointers. + +## Enabling creation + +Creation is **off by default**. Enable it before validation for requests whose +data fetchers or type resolvers use lookahead: + +```java +ExecutionInput input = ExecutionInput.newExecutionInput(query) + .graphQLContext(Map.of(NormalizedDocument.ENABLED, true)) + .build(); +ExecutionResult result = graphQL.execute(input); +``` + +The same option works with `ParseAndValidate.parseAndValidate(schema, input)`. +`ParseAndValidateResult.getNormalizedDocument()` returns the graph after +successful validation, or null when creation is disabled or validation fails. +`ExecutionContext.getNormalizedDocument()` exposes it during execution. + +Calling a lookahead inspection method (`getFields`, `getImmediateFields`, +`contains`, or their variants) without this option and artifact throws +`IllegalStateException`. This also applies to scalar fields and empty patterns. +Merely obtaining `DataFetchingEnvironment.getSelectionSet()` does not throw. +There is no lazy construction or revalidation fallback. As with other data +fetcher exceptions, the normal execution exception handler can turn this into a +field error; type resolver exceptions follow the existing execution error path. + +## Stored graph + +`getOperations()` contains operations in source order. Each operation has a root +selection set ID. IDs index `getSelectionSets()`. Each selection set contains +ordered `NormalizedField` and `NormalizedSelectionScope` entries: + +- A field retains its original AST node and declared parent type. Its child ID + is `-1` for a leaf. +- A scope retains an inline fragment or fragment spread, its type condition and + its target selection set ID. Named scopes also retain the fragment definition. +- A named fragment body is stored once. Conditions belong to each reference, + and remain symbolic AST expressions. No combinations of variable values are + enumerated. + +For example: + +```graphql +query($a: Boolean!, $b: Boolean!) { + box { ...Details @include(if: $a) ...Details @include(if: $b) } +} +fragment Details on Box { name } +``` + +The `box` selection set has **two scopes referencing one shared body**. That +body stores **one field**. Expanding both spreads would produce two logical +occurrences, but does not allocate two stored fields. During lookahead the two +active contributions collect into one `name` entry. If both conditions are +false, there is no entry. Nested scope conditions all have to hold. + +Validation records fields using its existing resolved parent types. It does not +coerce arguments or construct execution trees. A final pass freezes the recorded +selection sets and their direct references. Validation's merge checks and query +complexity limits continue to use their existing semantics. + +## Collection and behavior changes + +Lookahead evaluates `@skip`, `@include` and custom `ConditionalNodeDecision` +callbacks for the current execution. It collects immediate fields by **concrete +parent object type and response key** (alias, or field name). Children are +collected when requested. `getFields()` traverses those child views in preorder. + +### Separate concrete types + +Given a `Pet` interface implemented by `Cat` and `Dog`: + +```graphql +{ pet { name } } +``` + +Previously identical selections could become one entry with object types +`[Cat, Dog]`. Now `getImmediateFields()` returns two entries, `Cat.name` and +`Dog.name`. Each has one object type and one field definition. Their result key +is `name`; `getFieldsGroupedByResultKey().get("name")` contains both. Do not use +that group's size as the number of fields in one concrete response object. + +### Aliases on mutually exclusive types + +```graphql +{ + pet { + ... on Cat { label: name } + ... on Dog { label: nickname } + } +} +``` + +There are two entries: `Cat.name` and `Dog.nickname`, both with result key +`label`. They may have different arguments and field definitions. Result-key +grouping alone does not imply identical arguments across concrete types. + +### Combining children one level at a time + +```graphql +{ + pet { + ... on Cat { child { name } child { lives } } + ... on Dog { child { nickname } } + } +} +``` + +Immediate lookahead returns `Cat.child` and `Dog.child`. The two active Cat +occurrences contribute to one Cat child view; inspecting it returns `name` and +`lives`. The Dog view contains `nickname`. Identical trees on different parent +types are no longer recursively merged together. + +### Ordering, paths and conditions + +Concrete types are visited in type-name order. Within each type, fields retain +first-active-occurrence order. Thus a source ordering of Dog then Cat still +returns the Cat group first. Aliases distinguish entries but field paths keep +using schema field names: `child/name` and `Cat.child/Cat.name`. + +Immediate fields have no parent within the data fetcher's lookahead view. +Descendants point to their parent in that view. A selected field's own +`getSelectionSet()` uses relative paths again. Levels remain absolute field +levels in the operation, excluding list indices. + +`isConditional()` means this entry belongs to one of several possible parent +object types at its level. In `{ pet { name } }`, both entries are conditional, +even though every Pet type provides `name`. Variable conditions have already +been evaluated; an included field on a concrete object is not marked conditional +just because it had `@include`. + +Arguments are resolved only when `SelectedField.getArguments()` is called, +using the concrete field definition, execution variables, context and locale. +Defaults can therefore differ between concrete implementations. They are never +stored in the cached document. Source `@defer` directives remain accessible in +the graph; lookahead includes their selected fields but does not expose a +separate normalized deferred-execution model. + +## Preparsed caches + +Cache and return the **whole entry** produced by the supplied parse/validate +function. Custom preparation can also use: + +```java +ParseAndValidateResult prepared = ParseAndValidate.parseAndValidate(schema, input); +// Handle syntax failure separately: its document is null. +PreparsedDocumentEntry entry = new PreparsedDocumentEntry( + prepared.getDocument(), prepared.getErrors(), prepared.getNormalizedDocument()); +``` + +The graph and AST must be the same objects produced by validation. The entry +checks this association and requires an error-free document when a graph is +supplied. The graph is serializable with the entry, under the entry's existing +same-version serialization contract. + +Cache keys must distinguish the schema/version and any validation options that +change the cached result, including `NormalizedDocument.ENABLED`. A cached +AST-only entry will not gain a graph when reused by an enabled request. +Invalidate or repopulate existing caches when enabling creation. A graph +can be shared across requests with different variables; collected fields and +resolved arguments belong to each execution. AST-transforming instrumentation +must retain or regenerate the corresponding validation result. + +## Removed APIs and migration + +This removes `ExecutableNormalizedField`, `ExecutableNormalizedOperation`, +`ExecutableNormalizedOperationFactory`, `ExecutionContext.getNormalizedQueryTree()`, +`ExecutionStrategy.getNormalizedField()`, +the old `graphql.normalized.nf` package, and +`graphql.normalized.incremental.NormalizedDeferredExecution`. It also removes `ExecutableNormalizedOperationToAstCompiler`, the +old normalized-operation compiler and `VariablePredicate` **without replacement**. + +Use the opt-in validated graph for static inspection and the selection-set API +for execution lookahead. Custom execution strategies must remove overrides or +calls to the removed normalized-field hook. Update assumptions about type grouping, result counts, +ordering, conditional flags and parents as illustrated above. Consumers that +need to compile normalized operations back to AST must supply that capability +outside this API. `NormalizedInputValue`, variable normalization and execution +query-directive APIs remain available independently of document creation. + +For resource protection, continue to use parser limits and +`QueryComplexityLimits` during validation. `NormalizedDocument.getFields().size()` +counts stored AST fields, not expanded occurrences or merged execution fields. + +## Open draft question: flat lookahead paths + +The stored graph stays shared, but full `getFields()` enumeration can expand +many concrete-type paths through nested interfaces. With two implementations +at every level, the number of such paths can grow exponentially with depth. +The current draft has not added an enumeration budget. The remaining choice is +whether to bound these compatibility methods with the configured occurrence +limit or replace them with an API that exposes shared graph views. diff --git a/src/jmh/java/performance/DFSelectionSetPerformance.java b/src/jmh/java/performance/DFSelectionSetPerformance.java index bbc34b03f0..d67a5beb38 100644 --- a/src/jmh/java/performance/DFSelectionSetPerformance.java +++ b/src/jmh/java/performance/DFSelectionSetPerformance.java @@ -1,11 +1,13 @@ package performance; -import graphql.execution.CoercedVariables; -import graphql.language.Document; -import graphql.normalized.ExecutableNormalizedField; -import graphql.normalized.ExecutableNormalizedOperation; -import graphql.normalized.ExecutableNormalizedOperationFactory; -import graphql.parser.Parser; +import graphql.ExecutionInput; +import graphql.ParseAndValidate; +import graphql.ParseAndValidateResult; +import graphql.execution.ExecutionContext; +import graphql.execution.ExecutionContextBuilder; +import graphql.execution.MergedField; +import graphql.language.Field; +import graphql.normalized.NormalizedDocument; import graphql.schema.DataFetchingFieldSelectionSet; import graphql.schema.DataFetchingFieldSelectionSetImpl; import graphql.schema.GraphQLOutputType; @@ -22,97 +24,52 @@ import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; -import org.openjdk.jmh.infra.Blackhole; import java.util.List; +import java.util.Map; import java.util.concurrent.TimeUnit; +import static graphql.Assert.assertNotNull; +import static graphql.Assert.assertTrue; + @State(Scope.Benchmark) @Warmup(iterations = 2, time = 5) @Measurement(iterations = 3) @Fork(2) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MILLISECONDS) public class DFSelectionSetPerformance { - - @State(Scope.Benchmark) - public static class MyState { - - public ExecutableNormalizedField normalisedField; - public GraphQLOutputType outputFieldType; - GraphQLSchema schema; - Document document; - - @Setup - public void setup() { - try { - String schemaString = PerformanceTestingUtils.loadResource("large-schema-2.graphqls"); - schema = SchemaGenerator.createdMockedSchema(schemaString); - - String query = PerformanceTestingUtils.loadResource("large-schema-2-query.graphql"); - document = Parser.parse(query); - - ExecutableNormalizedOperation executableNormalizedOperation = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation(schema, document, null, CoercedVariables.emptyVariables()); - - normalisedField = executableNormalizedOperation.getTopLevelFields().get(0); - - outputFieldType = schema.getObjectType("Object42"); - - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - } - - @Benchmark - @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void benchMarkAvgTime(MyState myState, Blackhole blackhole) { - List fields = getSelectedFields(myState); - blackhole.consume(fields); - } - - @Benchmark - @BenchmarkMode(Mode.Throughput) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void benchMarkThroughput(MyState myState, Blackhole blackhole) { - List fields = getSelectedFields(myState); - blackhole.consume(fields); + private ExecutionContext context; + private MergedField field; + private GraphQLOutputType fieldType; + + @Setup + public void setup() throws Exception { + GraphQLSchema schema = SchemaGenerator.createdMockedSchema(PerformanceTestingUtils.loadResource("large-schema-2.graphqls")); + ExecutionInput input = ExecutionInput.newExecutionInput(PerformanceTestingUtils.loadResource("large-schema-2-query.graphql")) + .graphQLContext(Map.of(NormalizedDocument.ENABLED, true)).build(); + ParseAndValidateResult result = ParseAndValidate.parseAndValidate(schema, input); + assertTrue(!result.isFailure(), () -> result.getErrors().toString()); + NormalizedDocument document = assertNotNull(result.getNormalizedDocument()); + Field root = (Field) document.getOperations().get(0).getSource().getSelectionSet().getSelections().get(0); + field = MergedField.newMergedField(root).build(); + fieldType = assertNotNull(schema.getQueryType().getFieldDefinition(root.getName())).getType(); + context = ExecutionContextBuilder.newExecutionContextBuilder().executionId(graphql.execution.ExecutionId.generate()).graphQLSchema(schema) + .graphQLContext(input.getGraphQLContext()).locale(input.getLocale()) + .document(result.getDocument()).normalizedDocument(document).build(); } @Benchmark - @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void benchMarkAvgTime_getImmediateFields(MyState myState, Blackhole blackhole) { - List fields = getImmediateFields(myState); - blackhole.consume(fields); + public List benchMarkAvgTime() { + return collector().getFields("wontBeFound"); } @Benchmark - @BenchmarkMode(Mode.Throughput) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void benchMarkThroughput_getImmediateFields(MyState myState, Blackhole blackhole) { - List fields = getImmediateFields(myState); - blackhole.consume(fields); + public List benchMarkAvgTime_getImmediateFields() { + return collector().getImmediateFields(); } - private List getSelectedFields(MyState myState) { - DataFetchingFieldSelectionSet dataFetchingFieldSelectionSet = DataFetchingFieldSelectionSetImpl.newCollector(myState.schema, myState.outputFieldType, () -> myState.normalisedField); - return dataFetchingFieldSelectionSet.getFields("wontBeFound"); + private DataFetchingFieldSelectionSet collector() { + return DataFetchingFieldSelectionSetImpl.newCollector(context, field, fieldType, 1); } - - private List getImmediateFields(MyState myState) { - DataFetchingFieldSelectionSet dataFetchingFieldSelectionSet = DataFetchingFieldSelectionSetImpl.newCollector(myState.schema, myState.outputFieldType, () -> myState.normalisedField); - return dataFetchingFieldSelectionSet.getImmediateFields(); - } - - public static void mainX(String[] args) throws InterruptedException { - MyState myState = new MyState(); - myState.setup(); - - while (true) { - List selectedFields = new DFSelectionSetPerformance().getSelectedFields(myState); - Thread.sleep(500); - } - } - } diff --git a/src/jmh/java/performance/ENF1Performance.java b/src/jmh/java/performance/ENF1Performance.java deleted file mode 100644 index 06cc1a234d..0000000000 --- a/src/jmh/java/performance/ENF1Performance.java +++ /dev/null @@ -1,70 +0,0 @@ -package performance; - -import graphql.execution.CoercedVariables; -import graphql.language.Document; -import graphql.normalized.ExecutableNormalizedOperation; -import graphql.normalized.ExecutableNormalizedOperationFactory; -import graphql.parser.Parser; -import graphql.schema.GraphQLSchema; -import graphql.schema.idl.SchemaGenerator; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.Warmup; -import org.openjdk.jmh.infra.Blackhole; - -import java.util.concurrent.TimeUnit; - -@State(Scope.Benchmark) -@Warmup(iterations = 2, time = 5) -@Measurement(iterations = 3) -@Fork(2) -public class ENF1Performance { - - @State(Scope.Benchmark) - public static class MyState { - - GraphQLSchema schema; - Document document; - - @Setup - public void setup() { - try { - String schemaString = PerformanceTestingUtils.loadResource("large-schema-1.graphqls"); - schema = SchemaGenerator.createdMockedSchema(schemaString); - - String query = PerformanceTestingUtils.loadResource("large-schema-1-query.graphql"); - document = Parser.parse(query); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - @Benchmark - @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void benchMarkAvgTime(MyState myState, Blackhole blackhole) { - runImpl(myState, blackhole); - } - - @Benchmark - @BenchmarkMode(Mode.Throughput) - @OutputTimeUnit(TimeUnit.SECONDS) - public void benchMarkThroughput(MyState myState, Blackhole blackhole) { - runImpl(myState, blackhole); - } - - private void runImpl(MyState myState, Blackhole blackhole) { - ExecutableNormalizedOperation executableNormalizedOperation = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation(myState.schema, myState.document, null, CoercedVariables.emptyVariables()); - blackhole.consume(executableNormalizedOperation); - } - - -} diff --git a/src/jmh/java/performance/ENF2Performance.java b/src/jmh/java/performance/ENF2Performance.java deleted file mode 100644 index f6240d625c..0000000000 --- a/src/jmh/java/performance/ENF2Performance.java +++ /dev/null @@ -1,59 +0,0 @@ -package performance; - -import graphql.execution.CoercedVariables; -import graphql.language.Document; -import graphql.normalized.ExecutableNormalizedOperation; -import graphql.normalized.ExecutableNormalizedOperationFactory; -import graphql.parser.Parser; -import graphql.schema.GraphQLSchema; -import graphql.schema.idl.SchemaGenerator; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.Warmup; - -import java.util.concurrent.TimeUnit; - -@State(Scope.Benchmark) -@Warmup(iterations = 2, time = 5) -@Measurement(iterations = 3) -@Fork(2) -public class ENF2Performance { - - @State(Scope.Benchmark) - public static class MyState { - - GraphQLSchema schema; - Document document; - - @Setup - public void setup() { - try { - String schemaString = PerformanceTestingUtils.loadResource("large-schema-2.graphqls"); - schema = SchemaGenerator.createdMockedSchema(schemaString); - - String query = PerformanceTestingUtils.loadResource("large-schema-2-query.graphql"); - document = Parser.parse(query); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - } - - @Benchmark - @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public ExecutableNormalizedOperation benchMarkAvgTime(MyState myState) { - ExecutableNormalizedOperation executableNormalizedOperation = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation(myState.schema, myState.document, null, CoercedVariables.emptyVariables()); -// System.out.println("fields size:" + normalizedQuery.getFieldToNormalizedField().size()); - return executableNormalizedOperation; - } - -} diff --git a/src/jmh/java/performance/ENFDeepIntrospectionPerformance.java b/src/jmh/java/performance/ENFDeepIntrospectionPerformance.java deleted file mode 100644 index 02d3626d0c..0000000000 --- a/src/jmh/java/performance/ENFDeepIntrospectionPerformance.java +++ /dev/null @@ -1,128 +0,0 @@ -package performance; - -import benchmark.BenchmarkUtils; -import graphql.execution.CoercedVariables; -import graphql.language.Document; -import graphql.normalized.ExecutableNormalizedOperation; -import graphql.normalized.ExecutableNormalizedOperationFactory; -import graphql.parser.Parser; -import graphql.schema.GraphQLSchema; -import graphql.schema.idl.SchemaGenerator; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Level; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Param; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.Warmup; -import org.openjdk.jmh.runner.Runner; -import org.openjdk.jmh.runner.RunnerException; -import org.openjdk.jmh.runner.options.Options; -import org.openjdk.jmh.runner.options.OptionsBuilder; - -import java.util.concurrent.TimeUnit; - -import static graphql.normalized.ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation; - -@State(Scope.Benchmark) -@Warmup(iterations = 2, time = 5) -@Measurement(iterations = 3, time = 5) -@Fork(2) -public class ENFDeepIntrospectionPerformance { - - @Param({"2", "10"}) - int howDeep = 2; - - String query = ""; - - GraphQLSchema schema; - Document document; - - @Setup(Level.Trial) - public void setUp() { - String schemaString = PerformanceTestingUtils.loadResource("large-schema-2.graphqls"); - schema = SchemaGenerator.createdMockedSchema(schemaString); - - query = createDeepQuery(howDeep); - document = Parser.parse(query); - } - - @Benchmark - @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public ExecutableNormalizedOperation benchMarkAvgTime() { - ExecutableNormalizedOperationFactory.Options options = ExecutableNormalizedOperationFactory.Options.defaultOptions(); - ExecutableNormalizedOperation executableNormalizedOperation = createExecutableNormalizedOperation(schema, - document, - null, - CoercedVariables.emptyVariables(), - options); - return executableNormalizedOperation; - } - - public static void main(String[] args) throws RunnerException { - runAtStartup(); - - Options opt = new OptionsBuilder() - .include("performance.ENFDeepIntrospectionPerformance") - .build(); - - new Runner(opt).run(); - } - - private static void runAtStartup() { - - ENFDeepIntrospectionPerformance benchmarkIntrospection = new ENFDeepIntrospectionPerformance(); - benchmarkIntrospection.howDeep = 2; - - BenchmarkUtils.runInToolingForSomeTimeThenExit( - benchmarkIntrospection::setUp, - () -> { - while (true) { - benchmarkIntrospection.benchMarkAvgTime(); - } - }, - () -> { - } - ); - } - - - private static String createDeepQuery(int depth) { - String result = "query test {\n" + - " __schema {\n" + - " types {\n" + - " ...F1\n" + - " }\n" + - " }\n" + - "}\n"; - - for (int i = 1; i < depth; i++) { - result += " fragment F" + i + " on __Type {\n" + - " fields {\n" + - " type {\n" + - " ...F" + (i + 1) + "\n" + - " }\n" + - " }\n" + - "\n" + - " ofType {\n" + - " ...F" + (i + 1) + "\n" + - " }\n" + - " }\n"; - } - result += " fragment F" + depth + " on __Type {\n" + - " fields {\n" + - " type {\n" + - "name\n" + - " }\n" + - " }\n" + - "}\n"; - return result; - } - -} diff --git a/src/jmh/java/performance/ENFExtraLargePerformance.java b/src/jmh/java/performance/ENFExtraLargePerformance.java deleted file mode 100644 index ce8d3d6da4..0000000000 --- a/src/jmh/java/performance/ENFExtraLargePerformance.java +++ /dev/null @@ -1,68 +0,0 @@ -package performance; - -import graphql.execution.CoercedVariables; -import graphql.language.Document; -import graphql.normalized.ExecutableNormalizedOperation; -import graphql.normalized.ExecutableNormalizedOperationFactory; -import graphql.parser.Parser; -import graphql.schema.GraphQLSchema; -import graphql.schema.idl.SchemaGenerator; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.Warmup; -import org.openjdk.jmh.infra.Blackhole; - -import java.util.concurrent.TimeUnit; - -@State(Scope.Benchmark) -@Warmup(iterations = 2, time = 5) -@Measurement(iterations = 3) -@Fork(2) -public class ENFExtraLargePerformance { - - @State(Scope.Benchmark) - public static class MyState { - - GraphQLSchema schema; - Document document; - - @Setup - public void setup() { - try { - String schemaString = PerformanceTestingUtils.loadResource("extra-large-schema-1.graphqls"); - schema = SchemaGenerator.createdMockedSchema(schemaString); - - String query = PerformanceTestingUtils.loadResource("extra-large-schema-1-query.graphql"); - document = Parser.parse(query); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - @Benchmark - @BenchmarkMode(Mode.AverageTime) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void benchMarkAvgTime(MyState myState, Blackhole blackhole) { - runImpl(myState, blackhole); - } - - @Benchmark - @BenchmarkMode(Mode.Throughput) - @OutputTimeUnit(TimeUnit.SECONDS) - public void benchMarkThroughput(MyState myState, Blackhole blackhole) { - runImpl(myState, blackhole); - } - - private void runImpl(MyState myState, Blackhole blackhole) { - ExecutableNormalizedOperation executableNormalizedOperation = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation(myState.schema, myState.document, null, CoercedVariables.emptyVariables()); - blackhole.consume(executableNormalizedOperation); - } -} diff --git a/src/main/java/graphql/GraphQL.java b/src/main/java/graphql/GraphQL.java index 9b337ff273..87c80f31d3 100644 --- a/src/main/java/graphql/GraphQL.java +++ b/src/main/java/graphql/GraphQL.java @@ -24,13 +24,17 @@ import graphql.execution.preparsed.PreparsedDocumentEntry; import graphql.execution.preparsed.PreparsedDocumentProvider; import graphql.language.Document; +import graphql.normalized.NormalizedDocument; import graphql.schema.GraphQLSchema; +import graphql.validation.DocumentValidationResult; import graphql.validation.GoodFaithIntrospectionExceeded; import graphql.validation.OperationValidationRule; import graphql.validation.QueryComplexityLimits; import graphql.validation.ValidationError; +import graphql.validation.Validator; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.NullUnmarked; +import org.jspecify.annotations.Nullable; import java.util.List; import java.util.Locale; @@ -549,7 +553,7 @@ private CompletableFuture parseValidateAndExecute(ExecutionInpu return CompletableFuture.completedFuture(new ExecutionResultImpl(preparsedDocumentEntry.getErrors())); } try { - return execute(Assert.assertNotNull(executionInputRef.get()), assertNotNull(preparsedDocumentEntry.getDocument(), "document must not be null"), graphQLSchema, instrumentationState, engineRunningState, profiler); + return execute(Assert.assertNotNull(executionInputRef.get()), assertNotNull(preparsedDocumentEntry.getDocument(), "document must not be null"), preparsedDocumentEntry.getNormalizedDocument(), graphQLSchema, instrumentationState, engineRunningState, profiler); } catch (AbortExecutionException e) { return CompletableFuture.completedFuture(e.toExecutionResult()); } @@ -569,17 +573,13 @@ private PreparsedDocumentEntry parseAndValidate(AtomicReference executionInput = executionInput.transform(builder -> builder.variables(parseResult.getVariables())); executionInputRef.set(executionInput); - final List errors; + final DocumentValidationResult validation; try { - errors = validate(executionInput, document, graphQLSchema, instrumentationState); + validation = validate(executionInput, document, graphQLSchema, instrumentationState); } catch (GoodFaithIntrospectionExceeded e) { return new PreparsedDocumentEntry(document, List.of(e.toBadFaithError())); } - if (!errors.isEmpty()) { - return new PreparsedDocumentEntry(document, errors); - } - - return new PreparsedDocumentEntry(document); + return new PreparsedDocumentEntry(document, validation.errors(), validation.normalizedDocument()); } } @@ -602,7 +602,7 @@ private ParseAndValidateResult parse(ExecutionInput executionInput, GraphQLSchem } } - private List validate(ExecutionInput executionInput, Document document, GraphQLSchema graphQLSchema, InstrumentationState instrumentationState) { + private DocumentValidationResult validate(ExecutionInput executionInput, Document document, GraphQLSchema graphQLSchema, InstrumentationState instrumentationState) { InstrumentationContext> validationCtx = nonNullCtx(instrumentation.beginValidation(new InstrumentationValidationParameters(executionInput, document, graphQLSchema), instrumentationState)); validationCtx.onDispatched(); @@ -610,14 +610,15 @@ private List validate(ExecutionInput executionInput, Document d Locale locale = executionInput.getLocale(); QueryComplexityLimits limits = executionInput.getGraphQLContext().get(QueryComplexityLimits.KEY); - List validationErrors = ParseAndValidate.validate(graphQLSchema, document, validationRulePredicate, locale, limits); + DocumentValidationResult validation = new Validator().validateDocumentWithResult(graphQLSchema, document, validationRulePredicate, locale, limits, executionInput.getGraphQLContext()); - validationCtx.onCompleted(validationErrors, null); - return validationErrors; + validationCtx.onCompleted(validation.errors(), null); + return validation; } private CompletableFuture execute(ExecutionInput executionInput, Document document, + @Nullable NormalizedDocument normalizedDocument, GraphQLSchema graphQLSchema, InstrumentationState instrumentationState, EngineRunningState engineRunningState, @@ -627,7 +628,7 @@ private CompletableFuture execute(ExecutionInput executionInput Execution execution = new Execution(queryStrategy, mutationStrategy, subscriptionStrategy, instrumentation, valueUnboxer, doNotAutomaticallyDispatchDataLoader); ExecutionId executionId = executionInput.getExecutionId(); - return execution.execute(document, graphQLSchema, executionId, executionInput, instrumentationState, engineRunningState, profiler); + return execution.execute(document, graphQLSchema, executionId, executionInput, instrumentationState, engineRunningState, profiler, normalizedDocument); } } diff --git a/src/main/java/graphql/ParseAndValidate.java b/src/main/java/graphql/ParseAndValidate.java index 0f69253f73..786340875e 100644 --- a/src/main/java/graphql/ParseAndValidate.java +++ b/src/main/java/graphql/ParseAndValidate.java @@ -6,6 +6,7 @@ import graphql.parser.ParserEnvironment; import graphql.parser.ParserOptions; import graphql.schema.GraphQLSchema; +import graphql.validation.DocumentValidationResult; import graphql.validation.OperationValidationRule; import graphql.validation.QueryComplexityLimits; import graphql.validation.ValidationError; @@ -52,9 +53,10 @@ public static ParseAndValidateResult parseAndValidate(@NonNull GraphQLSchema gra ParseAndValidateResult result = parse(executionInput); if (!result.isFailure()) { QueryComplexityLimits limits = executionInput.getGraphQLContext().get(QueryComplexityLimits.KEY); - List errors = validate(graphQLSchema, assertNotNull(result.getDocument(), "Parse result document cannot be null when parse succeeded"), - rule -> true, executionInput.getLocale(), limits); - return result.transform(builder -> builder.validationErrors(errors)); + DocumentValidationResult validation = new Validator().validateDocumentWithResult(graphQLSchema, + assertNotNull(result.getDocument(), "Parse result document cannot be null when parse succeeded"), + rule -> true, executionInput.getLocale(), limits, executionInput.getGraphQLContext()); + return result.transform(builder -> builder.validationErrors(validation.errors()).normalizedDocument(validation.normalizedDocument())); } return result; } diff --git a/src/main/java/graphql/ParseAndValidateResult.java b/src/main/java/graphql/ParseAndValidateResult.java index fe7a70487e..a747545144 100644 --- a/src/main/java/graphql/ParseAndValidateResult.java +++ b/src/main/java/graphql/ParseAndValidateResult.java @@ -3,6 +3,7 @@ import graphql.collect.ImmutableKit; import graphql.execution.instrumentation.DocumentAndVariables; import graphql.language.Document; +import graphql.normalized.NormalizedDocument; import graphql.parser.InvalidSyntaxException; import graphql.validation.ValidationError; import org.jspecify.annotations.NullMarked; @@ -23,12 +24,14 @@ public class ParseAndValidateResult { private final @Nullable Document document; + private final @Nullable NormalizedDocument normalizedDocument; private final Map variables; private final @Nullable InvalidSyntaxException syntaxException; private final List validationErrors; private ParseAndValidateResult(Builder builder) { this.document = builder.document; + this.normalizedDocument = builder.normalizedDocument; this.variables = builder.variables == null ? ImmutableKit.emptyMap() : builder.variables; this.syntaxException = builder.syntaxException; this.validationErrors = builder.validationErrors == null ? ImmutableKit.emptyList() : builder.validationErrors; @@ -93,9 +96,14 @@ public List getErrors() { return errors; } + /** @return the validated selection graph, or null when disabled or validation failed */ + public @Nullable NormalizedDocument getNormalizedDocument() { + return normalizedDocument; + } + public ParseAndValidateResult transform(Consumer builderConsumer) { Builder builder = new Builder() - .document(document).variables(variables).syntaxException(syntaxException).validationErrors(validationErrors); + .document(document).normalizedDocument(normalizedDocument).variables(variables).syntaxException(syntaxException).validationErrors(validationErrors); builderConsumer.accept(builder); return builder.build(); } @@ -107,6 +115,7 @@ public static Builder newResult() { @NullUnmarked public static class Builder { private Document document; + private NormalizedDocument normalizedDocument; private Map variables = ImmutableKit.emptyMap(); private InvalidSyntaxException syntaxException; private List validationErrors = ImmutableKit.emptyList(); @@ -116,6 +125,11 @@ public Builder document(Document document) { return this; } + public Builder normalizedDocument(@Nullable NormalizedDocument normalizedDocument) { + this.normalizedDocument = normalizedDocument; + return this; + } + public Builder variables(Map variables) { this.variables = variables; return this; diff --git a/src/main/java/graphql/execution/Execution.java b/src/main/java/graphql/execution/Execution.java index df7a0f6aeb..480649f5ae 100644 --- a/src/main/java/graphql/execution/Execution.java +++ b/src/main/java/graphql/execution/Execution.java @@ -10,8 +10,8 @@ import graphql.GraphQL; import graphql.GraphQLContext; import graphql.GraphQLError; -import graphql.GraphQLUnusualConfiguration; import graphql.GraphQLException; +import graphql.GraphQLUnusualConfiguration; import graphql.Internal; import graphql.Profiler; import graphql.execution.directives.OperationDirectivesResolver; @@ -35,11 +35,13 @@ import graphql.language.NodeUtil; import graphql.language.OperationDefinition; import graphql.language.VariableDefinition; +import graphql.normalized.NormalizedDocument; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import graphql.schema.impl.SchemaUtil; import graphql.util.FpKit; import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; import org.reactivestreams.Publisher; import java.util.Collections; @@ -84,6 +86,10 @@ public Execution(ExecutionStrategy queryStrategy, } public CompletableFuture execute(Document document, GraphQLSchema graphQLSchema, ExecutionId executionId, ExecutionInput executionInput, InstrumentationState instrumentationState, EngineRunningState engineRunningState, Profiler profiler) { + return execute(document, graphQLSchema, executionId, executionInput, instrumentationState, engineRunningState, profiler, null); + } + + public CompletableFuture execute(Document document, GraphQLSchema graphQLSchema, ExecutionId executionId, ExecutionInput executionInput, InstrumentationState instrumentationState, EngineRunningState engineRunningState, Profiler profiler, @Nullable NormalizedDocument normalizedDocument) { NodeUtil.GetOperationResult getOperationResult; CoercedVariables coercedVariables; Supplier normalizedVariableValues; @@ -131,6 +137,7 @@ public CompletableFuture execute(Document document, GraphQLSche .coercedVariables(coercedVariables) .normalizedVariableValues(normalizedVariableValues) .document(document) + .normalizedDocument(normalizedDocument) .operationDefinition(getOperationResult.operationDefinition) .operationDirectives(operationDirectives) .dataLoaderRegistry(executionInput.getDataLoaderRegistry()) diff --git a/src/main/java/graphql/execution/ExecutionContext.java b/src/main/java/graphql/execution/ExecutionContext.java index 51982f7d96..ecfdb0b7ae 100644 --- a/src/main/java/graphql/execution/ExecutionContext.java +++ b/src/main/java/graphql/execution/ExecutionContext.java @@ -18,7 +18,7 @@ import graphql.language.Document; import graphql.language.FragmentDefinition; import graphql.language.OperationDefinition; -import graphql.normalized.ExecutableNormalizedOperation; +import graphql.normalized.NormalizedDocument; import graphql.schema.GraphQLSchema; import graphql.util.FpKit; import graphql.util.LockKit; @@ -35,8 +35,7 @@ import java.util.function.Consumer; import java.util.function.Supplier; -import static graphql.normalized.ExecutableNormalizedOperationFactory.Options; -import static graphql.normalized.ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation; + @SuppressWarnings("TypeParameterUnusedInFormals") @PublicApi @@ -70,7 +69,7 @@ public class ExecutionContext { private final ResponseMapFactory responseMapFactory; private final ExecutionInput executionInput; - private final Supplier queryTree; + private final @Nullable NormalizedDocument normalizedDocument; private final boolean propagateErrorsOnNonNullContractFailure; // this is modified after creation so it needs to be volatile to ensure visibility across Threads @@ -110,19 +109,11 @@ public class ExecutionContext { this.propagateErrorsOnNonNullContractFailure = builder.propagateErrorsOnNonNullContractFailure; this.engineRunningState = builder.engineRunningState; this.profiler = builder.profiler; - // lazy loading for performance - this.queryTree = mkExecutableNormalizedOperation(); + this.normalizedDocument = builder.normalizedDocument; this.allOperationsDirectives = builder.allOperationsDirectives; this.operationDirectives = mkOpDirectives(builder.allOperationsDirectives); } - private Supplier mkExecutableNormalizedOperation() { - return FpKit.interThreadMemoize(() -> { - Options options = Options.defaultOptions().graphQLContext(graphQLContext).locale(locale); - return createExecutableNormalizedOperation(graphQLSchema, operationDefinition, fragmentsByName, coercedVariables, options); - }); - } - private Supplier>> mkOpDirectives(Supplier>> allOperationsDirectives) { return FpKit.interThreadMemoize(() -> { List list = allOperationsDirectives.get().getOrDefault(operationDefinition, ImmutableList.of()); @@ -375,8 +366,9 @@ public ExecutionStrategy getStrategy(OperationDefinition.Operation operation) { } } - public Supplier getNormalizedQueryTree() { - return queryTree; + /** @return the graph prepared during validation, or null when creation was disabled */ + public @Nullable NormalizedDocument getNormalizedDocument() { + return normalizedDocument; } @Internal diff --git a/src/main/java/graphql/execution/ExecutionContextBuilder.java b/src/main/java/graphql/execution/ExecutionContextBuilder.java index 4077b8def3..2442c4b4ab 100644 --- a/src/main/java/graphql/execution/ExecutionContextBuilder.java +++ b/src/main/java/graphql/execution/ExecutionContextBuilder.java @@ -16,6 +16,7 @@ import graphql.language.Document; import graphql.language.FragmentDefinition; import graphql.language.OperationDefinition; +import graphql.normalized.NormalizedDocument; import graphql.schema.GraphQLSchema; import org.dataloader.DataLoaderRegistry; import org.jspecify.annotations.Nullable; @@ -42,6 +43,7 @@ public class ExecutionContextBuilder { GraphQLContext graphQLContext; Object root; Document document; + @Nullable NormalizedDocument normalizedDocument; OperationDefinition operationDefinition; CoercedVariables coercedVariables = CoercedVariables.emptyVariables(); Supplier normalizedVariables = NormalizedVariables::emptyVariables; @@ -95,6 +97,7 @@ public ExecutionContextBuilder() { localContext = other.getLocalContext(); root = other.getRoot(); document = other.getDocument(); + normalizedDocument = other.getNormalizedDocument(); operationDefinition = other.getOperationDefinition(); coercedVariables = other.getCoercedVariables(); fragmentsByName = ImmutableMap.copyOf(other.getFragmentsByName()); @@ -110,6 +113,11 @@ public ExecutionContextBuilder() { profiler = other.getProfiler(); } + public ExecutionContextBuilder normalizedDocument(@Nullable NormalizedDocument normalizedDocument) { + this.normalizedDocument = normalizedDocument; + return this; + } + public ExecutionContextBuilder instrumentation(Instrumentation instrumentation) { this.instrumentation = instrumentation; return this; diff --git a/src/main/java/graphql/execution/ExecutionStrategy.java b/src/main/java/graphql/execution/ExecutionStrategy.java index 3511073033..d2b8b6cf54 100644 --- a/src/main/java/graphql/execution/ExecutionStrategy.java +++ b/src/main/java/graphql/execution/ExecutionStrategy.java @@ -29,8 +29,6 @@ import graphql.extensions.ExtensionsBuilder; import graphql.introspection.Introspection; import graphql.language.Field; -import graphql.normalized.ExecutableNormalizedField; -import graphql.normalized.ExecutableNormalizedOperation; import graphql.schema.CoercingSerializeException; import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; @@ -525,10 +523,8 @@ protected Object resolveFieldWithInfo(ExecutionContext executionContext, Executi Supplier> argumentValues = () -> executionStepInfo.get().getArguments(); - Supplier normalizedFieldSupplier = getNormalizedField(executionContext, parameters, executionStepInfo); - - // DataFetchingFieldSelectionSet and QueryDirectives is a supplier of sorts - eg a lazy pattern - DataFetchingFieldSelectionSet fieldCollector = DataFetchingFieldSelectionSetImpl.newCollector(executionContext.getGraphQLSchema(), fieldDef.getType(), normalizedFieldSupplier); + DataFetchingFieldSelectionSet fieldCollector = DataFetchingFieldSelectionSetImpl.newCollector( + executionContext, field, fieldDef.getType(), parameters.getPath().getLevel()); QueryDirectives queryDirectives = new QueryDirectivesImpl(field, executionContext.getGraphQLSchema(), executionContext.getCoercedVariables(), @@ -629,11 +625,6 @@ protected Object resolveFieldWithInfo(ExecutionContext executionContext, Executi return fetchedValue; } - protected Supplier getNormalizedField(ExecutionContext executionContext, ExecutionStrategyParameters parameters, Supplier executionStepInfo) { - Supplier normalizedQuery = executionContext.getNormalizedQueryTree(); - return () -> normalizedQuery.get().getNormalizedField(assertNotNull(parameters.getField(), "Field execution requires a merged field"), assertNotNull(executionStepInfo.get().getObjectType(), "Normalized field lookup requires its object type"), executionStepInfo.get().getPath()); - } - /** * If the data fetching returned a {@link DataFetcherResult} then it can contain errors and new local context * and hence it gets turned into a {@link FetchedValue} but otherwise this method returns the unboxed diff --git a/src/main/java/graphql/execution/ResolveType.java b/src/main/java/graphql/execution/ResolveType.java index 3ef9c556fb..53e3199128 100644 --- a/src/main/java/graphql/execution/ResolveType.java +++ b/src/main/java/graphql/execution/ResolveType.java @@ -3,8 +3,6 @@ import graphql.Assert; import graphql.Internal; import graphql.TypeResolutionEnvironment; -import graphql.normalized.ExecutableNormalizedField; -import graphql.normalized.ExecutableNormalizedOperation; import graphql.schema.DataFetchingFieldSelectionSet; import graphql.schema.DataFetchingFieldSelectionSetImpl; import graphql.schema.GraphQLInterfaceType; @@ -15,7 +13,6 @@ import graphql.schema.GraphQLUnionType; import graphql.schema.TypeResolver; -import java.util.function.Supplier; @Internal public class ResolveType { @@ -43,9 +40,7 @@ public GraphQLObjectType resolveType(ExecutionContext executionContext, MergedFi } private DataFetchingFieldSelectionSet buildSelectionSet(ExecutionContext executionContext, MergedField field, GraphQLOutputType fieldType, ExecutionStepInfo executionStepInfo) { - Supplier normalizedQuery = executionContext.getNormalizedQueryTree(); - Supplier normalizedFieldSupplier = () -> normalizedQuery.get().getNormalizedField(field, executionStepInfo.getObjectType(), executionStepInfo.getPath()); - return DataFetchingFieldSelectionSetImpl.newCollector(executionContext.getGraphQLSchema(), fieldType, normalizedFieldSupplier); + return DataFetchingFieldSelectionSetImpl.newCollector(executionContext, field, fieldType, executionStepInfo.getPath().getLevel()); } public GraphQLObjectType resolveTypeForInterface(TypeResolutionEnvironment env, GraphQLInterfaceType abstractType) { diff --git a/src/main/java/graphql/execution/conditional/ConditionalNodes.java b/src/main/java/graphql/execution/conditional/ConditionalNodes.java index e922eeb427..12e1231069 100644 --- a/src/main/java/graphql/execution/conditional/ConditionalNodes.java +++ b/src/main/java/graphql/execution/conditional/ConditionalNodes.java @@ -22,13 +22,6 @@ @Internal public class ConditionalNodes { - /** - * return null if skip/include argument contains a variable and therefore could not be resolved - */ - public Boolean shouldIncludeWithoutVariables(DirectivesContainer element) { - return shouldInclude(null, element.getDirectives()); - } - public boolean shouldInclude(DirectivesContainer element, Map variables, GraphQLSchema graphQLSchema, @@ -83,54 +76,15 @@ public GraphQLContext getGraphQLContext() { } - private @Nullable Boolean shouldInclude(Map variables, List directives) { - // shortcut on no directives + private boolean shouldInclude(Map variables, List directives) { if (directives.isEmpty()) { return true; } - Boolean skip = getDirectiveResult(variables, directives, SkipDirective.getName(), false); - if (skip == null) { - return null; - } - if (skip) { - return false; - } - - return getDirectiveResult(variables, directives, IncludeDirective.getName(), true); - } - - public boolean containsSkipOrIncludeDirective(DirectivesContainer directivesContainer) { - return NodeUtil.findNodeByName(directivesContainer.getDirectives(), SkipDirective.getName()) != null || - NodeUtil.findNodeByName(directivesContainer.getDirectives(), IncludeDirective.getName()) != null; - } - - - public String getSkipVariableName(DirectivesContainer directivesContainer) { - Directive skipDirective = NodeUtil.findNodeByName(directivesContainer.getDirectives(), SkipDirective.getName()); - if (skipDirective == null) { - return null; - } - Argument argument = skipDirective.getArgument("if"); - if (argument.getValue() instanceof VariableReference) { - return ((VariableReference) argument.getValue()).getName(); - } - return null; + return !getDirectiveResult(variables, directives, SkipDirective.getName(), false) + && getDirectiveResult(variables, directives, IncludeDirective.getName(), true); } - public String getIncludeVariableName(DirectivesContainer directivesContainer) { - Directive skipDirective = NodeUtil.findNodeByName(directivesContainer.getDirectives(), IncludeDirective.getName()); - if (skipDirective == null) { - return null; - } - Argument argument = skipDirective.getArgument("if"); - if (argument.getValue() instanceof VariableReference) { - return ((VariableReference) argument.getValue()).getName(); - } - return null; - } - - - private @Nullable Boolean getDirectiveResult(Map variables, List directives, String directiveName, boolean defaultValue) { + private boolean getDirectiveResult(Map variables, List directives, String directiveName, boolean defaultValue) { Directive foundDirective = NodeUtil.findNodeByName(directives, directiveName); if (foundDirective != null) { return getIfValue(foundDirective.getArguments(), variables); @@ -138,17 +92,17 @@ public String getIncludeVariableName(DirectivesContainer directivesContainer) return defaultValue; } - private @Nullable Boolean getIfValue(List arguments, @Nullable Map variables) { + private boolean getIfValue(List arguments, Map variables) { for (Argument argument : arguments) { if (argument.getName().equals("if")) { Object value = argument.getValue(); if (value instanceof BooleanValue) { return ((BooleanValue) value).isValue(); } - if (value instanceof VariableReference && variables != null) { + if (value instanceof VariableReference) { return (boolean) variables.get(((VariableReference) value).getName()); } - return null; + return Assert.assertShouldNeverHappen("The 'if' argument must be a Boolean or variable reference"); } } return Assert.assertShouldNeverHappen("The 'if' argument must be present"); diff --git a/src/main/java/graphql/execution/directives/QueryDirectives.java b/src/main/java/graphql/execution/directives/QueryDirectives.java index ff7baf6869..8b5d2bd311 100644 --- a/src/main/java/graphql/execution/directives/QueryDirectives.java +++ b/src/main/java/graphql/execution/directives/QueryDirectives.java @@ -2,7 +2,6 @@ import graphql.GraphQLContext; import graphql.PublicApi; -import org.jspecify.annotations.NullMarked; import graphql.execution.CoercedVariables; import graphql.execution.MergedField; import graphql.execution.NormalizedVariables; @@ -10,6 +9,7 @@ import graphql.normalized.NormalizedInputValue; import graphql.schema.GraphQLDirective; import graphql.schema.GraphQLSchema; +import org.jspecify.annotations.NullMarked; import java.util.List; import java.util.Locale; @@ -73,9 +73,6 @@ public interface QueryDirectives { /** * This will return a map of {@link QueryAppliedDirective} to a map of their argument values in {@link NormalizedInputValue} form - *

- * NOTE : This will only be available when {@link graphql.normalized.ExecutableNormalizedOperationFactory} is used - * to create the {@link QueryAppliedDirective} information * * @return a map of applied directive to named argument values */ diff --git a/src/main/java/graphql/execution/incremental/DeferredExecution.java b/src/main/java/graphql/execution/incremental/DeferredExecution.java index b24ddc92b0..7075a4c6f1 100644 --- a/src/main/java/graphql/execution/incremental/DeferredExecution.java +++ b/src/main/java/graphql/execution/incremental/DeferredExecution.java @@ -1,15 +1,11 @@ package graphql.execution.incremental; import graphql.ExperimentalApi; -import graphql.normalized.incremental.NormalizedDeferredExecution; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; /** * Represents details about the defer execution that can be associated with a {@link graphql.execution.MergedField}. - *

- * This representation is used during graphql execution. Check {@link NormalizedDeferredExecution} - * for the normalized representation of @defer. */ @ExperimentalApi @NullMarked diff --git a/src/main/java/graphql/execution/preparsed/PreparsedDocumentEntry.java b/src/main/java/graphql/execution/preparsed/PreparsedDocumentEntry.java index cd878497c0..aa37ed9aee 100644 --- a/src/main/java/graphql/execution/preparsed/PreparsedDocumentEntry.java +++ b/src/main/java/graphql/execution/preparsed/PreparsedDocumentEntry.java @@ -3,6 +3,7 @@ import graphql.GraphQLError; import graphql.PublicApi; import graphql.language.Document; +import graphql.normalized.NormalizedDocument; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; @@ -27,25 +28,33 @@ @PublicApi public class PreparsedDocumentEntry implements Serializable { private final @Nullable Document document; + private final @Nullable NormalizedDocument normalizedDocument; private final List errors; public PreparsedDocumentEntry(Document document, List errors) { + this(document, errors, null); + } + + /** Retains the optional validation artifact alongside the exact AST used to build it. */ + public PreparsedDocumentEntry(Document document, List errors, @Nullable NormalizedDocument normalizedDocument) { assertNotNull(document); assertNotNull(errors); + graphql.Assert.assertTrue(normalizedDocument == null || (normalizedDocument.getDocument() == document && errors.isEmpty()), + () -> "NormalizedDocument requires its validated document and no errors"); + this.normalizedDocument = normalizedDocument; this.document = document; this.errors = errors; } public PreparsedDocumentEntry(Document document) { - assertNotNull(document); - this.document = document; - this.errors = Collections.emptyList(); + this(document, Collections.emptyList(), null); } public PreparsedDocumentEntry(List errors) { assertNotNull(errors); this.document = null; + this.normalizedDocument = null; this.errors = errors; } @@ -63,6 +72,11 @@ public List getErrors() { return errors; } + /** @return the optional validated selection graph, or null when not supplied */ + public @Nullable NormalizedDocument getNormalizedDocument() { + return normalizedDocument; + } + public boolean hasErrors() { return !errors.isEmpty(); } diff --git a/src/main/java/graphql/normalized/ArgumentMaker.java b/src/main/java/graphql/normalized/ArgumentMaker.java deleted file mode 100644 index c6ad4868ba..0000000000 --- a/src/main/java/graphql/normalized/ArgumentMaker.java +++ /dev/null @@ -1,110 +0,0 @@ -package graphql.normalized; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import graphql.Internal; -import graphql.execution.directives.QueryAppliedDirective; -import graphql.execution.directives.QueryAppliedDirectiveArgument; -import graphql.execution.directives.QueryDirectives; -import graphql.language.Argument; -import graphql.language.ArrayValue; -import graphql.language.NullValue; -import graphql.language.ObjectField; -import graphql.language.ObjectValue; -import graphql.language.Value; -import org.jspecify.annotations.NonNull; -import org.jspecify.annotations.Nullable; - -import java.util.List; -import java.util.Map; - -import static graphql.collect.ImmutableKit.emptyMap; -import static graphql.collect.ImmutableKit.map; -import static graphql.language.Argument.newArgument; - -/** - * This class is a peer class and broken out of {@link ExecutableNormalizedOperationToAstCompiler} to deal with - * argument value making. - */ -@Internal -class ArgumentMaker { - - static List createArguments(ExecutableNormalizedField executableNormalizedField, - VariableAccumulator variableAccumulator) { - ImmutableList.Builder result = ImmutableList.builder(); - ImmutableMap normalizedArguments = executableNormalizedField.getNormalizedArguments(); - for (String argName : normalizedArguments.keySet()) { - NormalizedInputValue normalizedInputValue = normalizedArguments.get(argName); - Value value = argValue(executableNormalizedField, null, argName, normalizedInputValue, variableAccumulator); - Argument argument = newArgument() - .name(argName) - .value(value) - .build(); - result.add(argument); - } - return result.build(); - } - - static List createDirectiveArguments(ExecutableNormalizedField executableNormalizedField, - QueryDirectives queryDirectives, - QueryAppliedDirective queryAppliedDirective, - VariableAccumulator variableAccumulator) { - - Map argValueMap = queryDirectives.getNormalizedInputValueByImmediateAppliedDirectives().getOrDefault(queryAppliedDirective, emptyMap()); - - ImmutableList.Builder result = ImmutableList.builder(); - for (QueryAppliedDirectiveArgument directiveArgument : queryAppliedDirective.getArguments()) { - String argName = directiveArgument.getName(); - if (argValueMap != null && argValueMap.containsKey(argName)) { - NormalizedInputValue normalizedInputValue = argValueMap.get(argName); - Value value = argValue(executableNormalizedField, queryAppliedDirective, argName, normalizedInputValue, variableAccumulator); - Argument argument = newArgument() - .name(argName) - .value(value) - .build(); - result.add(argument); - } - } - return result.build(); - } - - @SuppressWarnings("unchecked") - private static Value argValue(ExecutableNormalizedField executableNormalizedField, - QueryAppliedDirective queryAppliedDirective, - String argName, - @Nullable Object value, - VariableAccumulator variableAccumulator) { - if (value instanceof List) { - ArrayValue.Builder arrayValue = ArrayValue.newArrayValue(); - arrayValue.values(map((List) value, val -> argValue(executableNormalizedField, queryAppliedDirective, argName, val, variableAccumulator))); - return arrayValue.build(); - } - if (value instanceof Map) { - ObjectValue.Builder objectValue = ObjectValue.newObjectValue(); - Map map = (Map) value; - for (String fieldName : map.keySet()) { - Value fieldValue = argValue(executableNormalizedField, queryAppliedDirective, argName, (NormalizedInputValue) map.get(fieldName), variableAccumulator); - objectValue.objectField(ObjectField.newObjectField().name(fieldName).value(fieldValue).build()); - } - return objectValue.build(); - } - if (value == null) { - return NullValue.newNullValue().build(); - } - return (Value) value; - } - - @NonNull - private static Value argValue(ExecutableNormalizedField executableNormalizedField, - QueryAppliedDirective queryAppliedDirective, - String argName, - NormalizedInputValue normalizedInputValue, - VariableAccumulator variableAccumulator) { - if (variableAccumulator.shouldMakeVariable(executableNormalizedField, queryAppliedDirective, argName, normalizedInputValue)) { - VariableValueWithDefinition variableWithDefinition = variableAccumulator.accumulateVariable(normalizedInputValue); - return variableWithDefinition.getVariableReference(); - } else { - return argValue(executableNormalizedField, queryAppliedDirective, argName, normalizedInputValue.getValue(), variableAccumulator); - } - } -} diff --git a/src/main/java/graphql/normalized/ENFMerger.java b/src/main/java/graphql/normalized/ENFMerger.java deleted file mode 100644 index 4c6aad6d27..0000000000 --- a/src/main/java/graphql/normalized/ENFMerger.java +++ /dev/null @@ -1,197 +0,0 @@ -package graphql.normalized; - -import graphql.Internal; -import graphql.introspection.Introspection; -import graphql.language.Argument; -import graphql.language.AstComparator; -import graphql.schema.GraphQLInterfaceType; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLSchema; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -@Internal -public class ENFMerger { - - public static void merge( - ExecutableNormalizedField parent, - List childrenWithSameResultKey, - GraphQLSchema schema, - boolean deferSupport - ) { - // they have all the same result key - // we can only merge the fields if they have the same field name + arguments + all children are the same - List> possibleGroupsToMerge = new ArrayList<>(); - for (ExecutableNormalizedField field : childrenWithSameResultKey) { - boolean addToGroup = false; - overPossibleGroups: - for (Set group : possibleGroupsToMerge) { - for (ExecutableNormalizedField fieldInGroup : group) { - if (field.getFieldName().equals(Introspection.TypeNameMetaFieldDef.getName())) { - addToGroup = true; - group.add(field); - continue overPossibleGroups; - } - if (field.getFieldName().equals(fieldInGroup.getFieldName()) && - sameArguments(field.getAstArguments(), fieldInGroup.getAstArguments()) - && isFieldInSharedInterface(field, fieldInGroup, schema) - ) { - addToGroup = true; - group.add(field); - continue overPossibleGroups; - } - } - } - if (!addToGroup) { - LinkedHashSet group = new LinkedHashSet<>(); - group.add(field); - possibleGroupsToMerge.add(group); - } - } - for (Set groupOfFields : possibleGroupsToMerge) { - // for each group we check if it could be merged - List> listOfChildrenForGroup = new ArrayList<>(); - for (ExecutableNormalizedField fieldInGroup : groupOfFields) { - Set childrenSets = new LinkedHashSet<>(fieldInGroup.getChildren()); - listOfChildrenForGroup.add(childrenSets); - } - boolean mergeable = areFieldSetsTheSame(listOfChildrenForGroup); - if (mergeable) { - Set mergedObjects = new LinkedHashSet<>(); - groupOfFields.forEach(f -> mergedObjects.addAll(f.getObjectTypeNames())); - // patching the first one to contain more objects, remove all others - Iterator iterator = groupOfFields.iterator(); - ExecutableNormalizedField first = iterator.next(); - - while (iterator.hasNext()) { - ExecutableNormalizedField next = iterator.next(); - parent.getChildren().remove(next); - - if (deferSupport) { - // Move defer executions from removed field into the merged field's entry - first.addDeferredExecutions(next.getDeferredExecutions()); - } - } - first.setObjectTypeNames(mergedObjects); - } - } - } - - private static boolean isFieldInSharedInterface(ExecutableNormalizedField fieldOne, ExecutableNormalizedField fieldTwo, GraphQLSchema schema) { - - /* - * we can get away with only checking one of the object names, because all object names in one ENF are guaranteed to be the same field. - * This comes from how the ENFs are created in the factory before. - */ - String firstObject = fieldOne.getSingleObjectTypeName(); - String secondObject = fieldTwo.getSingleObjectTypeName(); - // we know that the field names are the same, therefore we can just take the first one - String fieldName = fieldOne.getFieldName(); - - GraphQLObjectType objectTypeOne = schema.getObjectType(firstObject); - GraphQLObjectType objectTypeTwo = schema.getObjectType(secondObject); - List interfacesOne = (List) objectTypeOne.getInterfaces(); - List interfacesTwo = (List) objectTypeTwo.getInterfaces(); - - Optional firstInterfaceFound = interfacesOne.stream().filter(singleInterface -> singleInterface.getFieldDefinition(fieldName) != null).findFirst(); - Optional secondInterfaceFound = interfacesTwo.stream().filter(singleInterface -> singleInterface.getFieldDefinition(fieldName) != null).findFirst(); - if (!firstInterfaceFound.isPresent() || !secondInterfaceFound.isPresent()) { - return false; - } - return firstInterfaceFound.get().getName().equals(secondInterfaceFound.get().getName()); - } - - - private static boolean areFieldSetsTheSame(List> listOfSets) { - if (listOfSets.size() == 0 || listOfSets.size() == 1) { - return true; - } - Set first = listOfSets.get(0); - Iterator> iterator = listOfSets.iterator(); - iterator.next(); - while (iterator.hasNext()) { - Set set = iterator.next(); - if (!compareTwoFieldSets(first, set)) { - return false; - } - } - List> nextLevel = new ArrayList<>(); - for (Set set : listOfSets) { - for (ExecutableNormalizedField fieldInSet : set) { - nextLevel.add(new LinkedHashSet<>(fieldInSet.getChildren())); - } - } - return areFieldSetsTheSame(nextLevel); - } - - private static boolean compareTwoFieldSets(Set setOne, Set setTwo) { - if (setOne.size() != setTwo.size()) { - return false; - } - for (ExecutableNormalizedField field : setOne) { - if (!isContained(field, setTwo)) { - return false; - } - } - return true; - } - - private static boolean isContained(ExecutableNormalizedField searchFor, Set set) { - for (ExecutableNormalizedField field : set) { - if (compareWithoutChildren(searchFor, field)) { - return true; - } - } - return false; - } - - private static boolean compareWithoutChildren(ExecutableNormalizedField one, ExecutableNormalizedField two) { - - if (!one.getObjectTypeNames().equals(two.getObjectTypeNames())) { - return false; - } - if (!Objects.equals(one.getAlias(), two.getAlias())) { - return false; - } - if (!Objects.equals(one.getFieldName(), two.getFieldName())) { - return false; - } - if (!sameArguments(one.getAstArguments(), two.getAstArguments())) { - return false; - } - return true; - } - - // copied from graphql.validation.OperationValidator - private static boolean sameArguments(List arguments1, List arguments2) { - if (arguments1.size() != arguments2.size()) { - return false; - } - for (Argument argument : arguments1) { - Argument matchedArgument = findArgumentByName(argument.getName(), arguments2); - if (matchedArgument == null) { - return false; - } - if (!AstComparator.sameValue(argument.getValue(), matchedArgument.getValue())) { - return false; - } - } - return true; - } - - private static Argument findArgumentByName(String name, List arguments) { - for (Argument argument : arguments) { - if (argument.getName().equals(name)) { - return argument; - } - } - return null; - } - -} diff --git a/src/main/java/graphql/normalized/ExecutableNormalizedField.java b/src/main/java/graphql/normalized/ExecutableNormalizedField.java deleted file mode 100644 index 108d51ced5..0000000000 --- a/src/main/java/graphql/normalized/ExecutableNormalizedField.java +++ /dev/null @@ -1,704 +0,0 @@ -package graphql.normalized; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import graphql.ExperimentalApi; -import graphql.Internal; -import graphql.Mutable; -import graphql.PublicApi; -import graphql.collect.ImmutableKit; -import graphql.introspection.Introspection; -import graphql.language.Argument; -import graphql.normalized.incremental.NormalizedDeferredExecution; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLInterfaceType; -import graphql.schema.GraphQLNamedOutputType; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLOutputType; -import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLUnionType; -import graphql.util.FpKit; -import graphql.util.MutableRef; -import org.jspecify.annotations.NonNull; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.NullUnmarked; -import org.jspecify.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; - -import static graphql.Assert.assertNotNull; -import static graphql.Assert.assertTrue; -import static graphql.schema.GraphQLTypeUtil.simplePrint; -import static graphql.schema.GraphQLTypeUtil.unwrapAll; -import static java.util.stream.Collectors.joining; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toSet; - -/** - * An {@link ExecutableNormalizedField} represents a field in an executable graphql operation. Its models what - * could be executed during a given operation. - *

- * This class is intentionally mutable for performance reasons since building immutable parent child - * objects is too expensive. - */ -@PublicApi -@Mutable -@NullMarked -public class ExecutableNormalizedField { - private final @Nullable String alias; - private final ImmutableMap normalizedArguments; - private final LinkedHashMap resolvedArguments; - private final ImmutableList astArguments; - - // Mutable List on purpose: it is modified after creation - private final LinkedHashSet objectTypeNames; - private final ArrayList children; - private @Nullable ExecutableNormalizedField parent; - - private final String fieldName; - private final int level; - - // Mutable List on purpose: it is modified after creation - private final LinkedHashSet deferredExecutions; - - private ExecutableNormalizedField(Builder builder) { - this.alias = builder.alias; - this.resolvedArguments = builder.resolvedArguments; - this.normalizedArguments = builder.normalizedArguments; - this.astArguments = builder.astArguments; - this.objectTypeNames = builder.objectTypeNames; - this.fieldName = assertNotNull(builder.fieldName); - this.children = builder.children; - this.level = builder.level; - this.parent = builder.parent; - this.deferredExecutions = builder.deferredExecutions; - } - - /** - * Determines whether this {@link ExecutableNormalizedField} needs a fragment to select the field. However, it considers the parent - * output type when determining whether it needs a fragment. - *

- * Consider the following schema - * - *

-     * interface Animal {
-     *     name: String
-     *     parent: Animal
-     * }
-     * type Cat implements Animal {
-     *     name: String
-     *     parent: Cat
-     * }
-     * type Dog implements Animal {
-     *     name: String
-     *     parent: Dog
-     *     isGoodBoy: Boolean
-     * }
-     * type Query {
-     *     animal: Animal
-     * }
-     * 
- *

- * and the following query - * - *

-     * {
-     *     animal {
-     *         parent {
-     *             name
-     *         }
-     *     }
-     * }
-     * 
- *

- * Then we would get the following {@link ExecutableNormalizedOperation} - * - *

-     * -Query.animal: Animal
-     * --[Cat, Dog].parent: Cat, Dog
-     * ---[Cat, Dog].name: String
-     * 
- *

- * If we simply checked the {@link #parent}'s {@link #getFieldDefinitions(GraphQLSchema)} that would - * point us to {@code Cat.parent} and {@code Dog.parent} whose output types would incorrectly answer - * our question whether this is conditional? - *

- * We MUST consider that the output type of the {@code parent} field is {@code Animal} and - * NOT {@code Cat} or {@code Dog} as their respective implementations would say. - * - * @param schema - the graphql schema in play - * - * @return true if the field is conditional - */ - public boolean isConditional(GraphQLSchema schema) { - if (parent == null) { - return false; - } - - for (GraphQLInterfaceType commonParentOutputInterface : parent.getInterfacesCommonToAllOutputTypes(schema)) { - List implementations = schema.getImplementations(commonParentOutputInterface); - // __typename - if (fieldName.equals(Introspection.TypeNameMetaFieldDef.getName()) && implementations.size() == objectTypeNames.size()) { - return false; - } - if (commonParentOutputInterface.getField(fieldName) == null) { - continue; - } - if (implementations.size() == objectTypeNames.size()) { - return false; - } - } - - // __typename is the only field in a union type that CAN be NOT conditional - GraphQLFieldDefinition parentFieldDef = parent.getOneFieldDefinition(schema); - if (unwrapAll(parentFieldDef.getType()) instanceof GraphQLUnionType) { - GraphQLUnionType parentOutputTypeAsUnion = (GraphQLUnionType) unwrapAll(parentFieldDef.getType()); - if (fieldName.equals(Introspection.TypeNameMetaFieldDef.getName()) && objectTypeNames.size() == parentOutputTypeAsUnion.getTypes().size()) { - return false; // Not conditional - } - } - - // This means there is no Union or Interface which could serve as unconditional parent - if (objectTypeNames.size() > 1) { - return true; // Conditional - } - if (parent.objectTypeNames.size() > 1) { - return true; - } - - GraphQLObjectType oneObjectType = (GraphQLObjectType) schema.getType(objectTypeNames.iterator().next()); - return unwrapAll(parentFieldDef.getType()) != oneObjectType; - } - - public boolean hasChildren() { - return children.size() > 0; - } - - public GraphQLOutputType getType(GraphQLSchema schema) { - List fieldDefinitions = getFieldDefinitions(schema); - Set fieldTypes = fieldDefinitions.stream().map(fd -> simplePrint(fd.getType())).collect(toSet()); - assertTrue(fieldTypes.size() == 1, "More than one type ... use getTypes"); - return fieldDefinitions.get(0).getType(); - } - - public List getTypes(GraphQLSchema schema) { - return ImmutableKit.map(getFieldDefinitions(schema), fd -> fd.getType()); - } - - public void forEachFieldDefinition(GraphQLSchema schema, Consumer consumer) { - var fieldDefinition = resolveIntrospectionField(schema, objectTypeNames, fieldName); - if (fieldDefinition != null) { - consumer.accept(fieldDefinition); - return; - } - - var fieldVisibility = schema.getCodeRegistry().getFieldVisibility(); - for (String objectTypeName : objectTypeNames) { - GraphQLObjectType type = (GraphQLObjectType) assertNotNull(schema.getType(objectTypeName)); - // Use field visibility to allow custom visibility implementations to provide placeholder fields - // for fields that don't exist on the local schema (e.g., in federated subgraphs) - GraphQLFieldDefinition field = fieldVisibility.getFieldDefinition(type, fieldName); - consumer.accept(assertNotNull(field, "No field %s found for type %s", fieldName, objectTypeName)); - } - } - - public List getFieldDefinitions(GraphQLSchema schema) { - ImmutableList.Builder builder = ImmutableList.builder(); - forEachFieldDefinition(schema, builder::add); - return builder.build(); - } - - /** - * This is NOT public as it is not recommended usage. - *

- * Internally there are cases where we know it is safe to use this, so this exists. - */ - private GraphQLFieldDefinition getOneFieldDefinition(GraphQLSchema schema) { - var fieldDefinition = resolveIntrospectionField(schema, objectTypeNames, fieldName); - if (fieldDefinition != null) { - return fieldDefinition; - } - - String objectTypeName = objectTypeNames.iterator().next(); - GraphQLObjectType type = (GraphQLObjectType) assertNotNull(schema.getType(objectTypeName)); - var fieldVisibility = schema.getCodeRegistry().getFieldVisibility(); - return assertNotNull(fieldVisibility.getFieldDefinition(type, fieldName), "No field %s found for type %s", fieldName, objectTypeName); - } - - private static @Nullable GraphQLFieldDefinition resolveIntrospectionField(GraphQLSchema schema, Set objectTypeNames, String fieldName) { - if (fieldName.equals(schema.getIntrospectionTypenameFieldDefinition().getName())) { - return schema.getIntrospectionTypenameFieldDefinition(); - } else if (objectTypeNames.size() == 1 && objectTypeNames.iterator().next().equals(schema.getQueryType().getName())) { - if (fieldName.equals(schema.getIntrospectionSchemaFieldDefinition().getName())) { - return schema.getIntrospectionSchemaFieldDefinition(); - } else if (fieldName.equals(schema.getIntrospectionTypeFieldDefinition().getName())) { - return schema.getIntrospectionTypeFieldDefinition(); - } - } - return null; - } - - @Internal - public void addObjectTypeNames(Collection objectTypeNames) { - this.objectTypeNames.addAll(objectTypeNames); - } - - @Internal - public void setObjectTypeNames(Collection objectTypeNames) { - this.objectTypeNames.clear(); - this.objectTypeNames.addAll(objectTypeNames); - } - - @Internal - public void addChild(ExecutableNormalizedField executableNormalizedField) { - this.children.add(executableNormalizedField); - } - - @Internal - public void clearChildren() { - this.children.clear(); - } - - @Internal - public void setDeferredExecutions(Collection deferredExecutions) { - this.deferredExecutions.clear(); - this.deferredExecutions.addAll(deferredExecutions); - } - - public void addDeferredExecutions(Collection deferredExecutions) { - this.deferredExecutions.addAll(deferredExecutions); - } - - /** - * All merged fields have the same name so this is the name of the {@link ExecutableNormalizedField}. - *

- * WARNING: This is not always the key in the execution result, because of possible field aliases. - * - * @return the name of this {@link ExecutableNormalizedField} - * - * @see #getResultKey() - * @see #getAlias() - */ - public String getName() { - return getFieldName(); - } - - /** - * @return the same value as {@link #getName()} - * - * @see #getResultKey() - * @see #getAlias() - */ - public String getFieldName() { - return fieldName; - } - - /** - * Returns the result key of this {@link ExecutableNormalizedField} within the overall result. - * This is either a field alias or the value of {@link #getName()} - * - * @return the result key for this {@link ExecutableNormalizedField}. - * - * @see #getName() - */ - public String getResultKey() { - if (alias != null) { - return alias; - } - return getName(); - } - - /** - * @return the field alias used or null if there is none - * - * @see #getResultKey() - * @see #getName() - */ - public @Nullable String getAlias() { - return alias; - } - - /** - * @return a list of the {@link Argument}s on the field - */ - public ImmutableList getAstArguments() { - return astArguments; - } - - /** - * Returns an argument value as a {@link NormalizedInputValue} which contains its type name and its current value - * - * @param name the name of the argument - * - * @return an argument value - */ - public @Nullable NormalizedInputValue getNormalizedArgument(String name) { - return normalizedArguments.get(name); - } - - /** - * @return a map of all the arguments in {@link NormalizedInputValue} form - */ - public ImmutableMap getNormalizedArguments() { - return normalizedArguments; - } - - /** - * @return a map of the resolved argument values - */ - public LinkedHashMap getResolvedArguments() { - return resolvedArguments; - } - - - /** - * A {@link ExecutableNormalizedField} can sometimes (for non-concrete types like interfaces and unions) - * have more than one object type it could be when executed. There is no way to know what it will be until - * the field is executed over data and the type is resolved via a {@link graphql.schema.TypeResolver}. - *

- * This method returns all the possible types a field can be which is one or more {@link GraphQLObjectType} - * names. - *

- * Warning: This returns a Mutable Set. No defensive copy is made for performance reasons. - * - * @return a set of the possible type names this field could be. - */ - public Set getObjectTypeNames() { - return objectTypeNames; - } - - - /** - * This returns the first entry in {@link #getObjectTypeNames()}. Sometimes you know a field cant be more than one - * type and this method is a shortcut one to help you. - * - * @return the first entry from - */ - public String getSingleObjectTypeName() { - return objectTypeNames.iterator().next(); - } - - /** - * @return a helper method show field details - */ - public String printDetails() { - StringBuilder result = new StringBuilder(); - if (getAlias() != null) { - result.append(getAlias()).append(": "); - } - return result + objectTypeNamesToString() + "." + fieldName; - } - - /** - * @return a helper method to show the object types names as a string - */ - public String objectTypeNamesToString() { - if (objectTypeNames.size() == 1) { - return objectTypeNames.iterator().next(); - } else { - return objectTypeNames.toString(); - } - } - - /** - * This returns the list of the result keys (see {@link #getResultKey()} that lead from this field upwards to - * its parent field - * - * @return a list of the result keys from this {@link ExecutableNormalizedField} to the top of the operation via parent fields - */ - public List getListOfResultKeys() { - LinkedList list = new LinkedList<>(); - ExecutableNormalizedField current = this; - while (current != null) { - list.addFirst(current.getResultKey()); - current = current.parent; - } - return list; - } - - /** - * @return the children of the {@link ExecutableNormalizedField} - */ - public List getChildren() { - return children; - } - - /** - * Returns the list of child fields that would have the same result key - * - * @param resultKey the result key to check - * - * @return a list of all direct {@link ExecutableNormalizedField} children with the specified result key - */ - public List getChildrenWithSameResultKey(String resultKey) { - return FpKit.filterList(children, child -> child.getResultKey().equals(resultKey)); - } - - public List getChildren(int includingRelativeLevel) { - assertTrue(includingRelativeLevel >= 1, "relative level must be >= 1"); - List result = new ArrayList<>(); - - this.getChildren().forEach(child -> { - traverseImpl(child, result::add, 1, includingRelativeLevel); - }); - return result; - } - - /** - * This returns the child fields that can be used if the object is of the specified object type - * - * @param objectTypeName the object type - * - * @return a list of child fields that would apply to that object type - */ - public List getChildren(String objectTypeName) { - return children.stream() - .filter(cld -> cld.objectTypeNames.contains(objectTypeName)) - .collect(toList()); - } - - /** - * the level of the {@link ExecutableNormalizedField} in the operation hierarchy with top level fields - * starting at 1 - * - * @return the level of the {@link ExecutableNormalizedField} in the operation hierarchy - */ - public int getLevel() { - return level; - } - - /** - * @return the parent of this {@link ExecutableNormalizedField} or null if it's a top level field - */ - public @Nullable ExecutableNormalizedField getParent() { - return parent; - } - - /** - * @return the {@link NormalizedDeferredExecution}s associated with this {@link ExecutableNormalizedField}. - * - * @see NormalizedDeferredExecution - */ - @ExperimentalApi - public LinkedHashSet getDeferredExecutions() { - return deferredExecutions; - } - - @Internal - public void replaceParent(ExecutableNormalizedField newParent) { - this.parent = newParent; - } - - - @Override - public String toString() { - return "NormalizedField{" + - objectTypeNamesToString() + "." + fieldName + - ", alias=" + alias + - ", level=" + level + - ", children=" + children.stream().map(ExecutableNormalizedField::toString).collect(joining("\n")) + - '}'; - } - - - /** - * Traverse from this {@link ExecutableNormalizedField} down into itself and all of its children - * - * @param consumer the callback for each {@link ExecutableNormalizedField} in the hierarchy. - */ - public void traverseSubTree(Consumer consumer) { - this.getChildren().forEach(child -> { - traverseImpl(child, consumer, 1, Integer.MAX_VALUE); - }); - } - - private void traverseImpl(ExecutableNormalizedField root, - Consumer consumer, - int curRelativeLevel, - int abortAfter) { - if (curRelativeLevel > abortAfter) { - return; - } - consumer.accept(root); - root.getChildren().forEach(child -> { - traverseImpl(child, consumer, curRelativeLevel + 1, abortAfter); - }); - } - - /** - * This tries to find interfaces common to all the field output types. - *

- * i.e. goes through {@link #getFieldDefinitions(GraphQLSchema)} and finds interfaces that - * all the field's unwrapped output types are assignable to. - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - private Set getInterfacesCommonToAllOutputTypes(GraphQLSchema schema) { - // Shortcut for performance - if (objectTypeNames.size() == 1) { - var fieldDef = getOneFieldDefinition(schema); - var outputType = unwrapAll(fieldDef.getType()); - - if (outputType instanceof GraphQLObjectType) { - return new LinkedHashSet<>((List) ((GraphQLObjectType) outputType).getInterfaces()); - } else if (outputType instanceof GraphQLInterfaceType) { - var result = new LinkedHashSet<>((List) ((GraphQLInterfaceType) outputType).getInterfaces()); - result.add(outputType); - return result; - } else { - return Collections.emptySet(); - } - } - - MutableRef> commonInterfaces = new MutableRef<>(); - forEachFieldDefinition(schema, (fieldDef) -> { - var outputType = unwrapAll(fieldDef.getType()); - - List outputTypeInterfaces; - if (outputType instanceof GraphQLObjectType) { - outputTypeInterfaces = (List) ((GraphQLObjectType) outputType).getInterfaces(); - } else if (outputType instanceof GraphQLInterfaceType) { - // This interface and superinterfaces - List superInterfaces = ((GraphQLInterfaceType) outputType).getInterfaces(); - - outputTypeInterfaces = new ArrayList<>(superInterfaces.size() + 1); - outputTypeInterfaces.add((GraphQLInterfaceType) outputType); - - if (!superInterfaces.isEmpty()) { - outputTypeInterfaces.addAll((List) superInterfaces); - } - } else { - outputTypeInterfaces = Collections.emptyList(); - } - - if (commonInterfaces.value == null) { - commonInterfaces.value = new LinkedHashSet<>(outputTypeInterfaces); - } else { - commonInterfaces.value.retainAll(outputTypeInterfaces); - } - }); - - return commonInterfaces.value; - } - - /** - * @return a {@link Builder} of {@link ExecutableNormalizedField}s - */ - public static Builder newNormalizedField() { - return new Builder(); - } - - /** - * Allows this {@link ExecutableNormalizedField} to be transformed via a {@link Builder} consumer callback - * - * @param builderConsumer the consumer given a builder - * - * @return a new transformed {@link ExecutableNormalizedField} - */ - public ExecutableNormalizedField transform(Consumer builderConsumer) { - Builder builder = new Builder(this); - builderConsumer.accept(builder); - return builder.build(); - } - - @NullUnmarked - public static class Builder { - private LinkedHashSet objectTypeNames = new LinkedHashSet<>(); - private String fieldName; - private ArrayList children = new ArrayList<>(); - private int level; - private ExecutableNormalizedField parent; - private String alias; - private ImmutableMap normalizedArguments = ImmutableKit.emptyMap(); - private LinkedHashMap resolvedArguments = new LinkedHashMap<>(); - private ImmutableList astArguments = ImmutableKit.emptyList(); - - private LinkedHashSet deferredExecutions = new LinkedHashSet<>(); - - private Builder() { - } - - private Builder(ExecutableNormalizedField existing) { - this.alias = existing.alias; - this.normalizedArguments = existing.normalizedArguments; - this.astArguments = existing.astArguments; - this.resolvedArguments = existing.resolvedArguments; - this.objectTypeNames = new LinkedHashSet<>(existing.getObjectTypeNames()); - this.fieldName = existing.getFieldName(); - this.children = new ArrayList<>(existing.children); - this.level = existing.getLevel(); - this.parent = existing.getParent(); - this.deferredExecutions = existing.getDeferredExecutions(); - } - - public Builder clearObjectTypesNames() { - this.objectTypeNames.clear(); - return this; - } - - public Builder objectTypeNames(List objectTypeNames) { - this.objectTypeNames.addAll(objectTypeNames); - return this; - } - - public Builder alias(String alias) { - this.alias = alias; - return this; - } - - public Builder normalizedArguments(@Nullable Map arguments) { - this.normalizedArguments = arguments == null ? ImmutableKit.emptyMap() : ImmutableMap.copyOf(arguments); - return this; - } - - public Builder resolvedArguments(@Nullable Map arguments) { - this.resolvedArguments = arguments == null ? new LinkedHashMap<>() : new LinkedHashMap<>(arguments); - return this; - } - - public Builder astArguments(@NonNull List astArguments) { - this.astArguments = ImmutableList.copyOf(astArguments); - return this; - } - - - public Builder fieldName(String fieldName) { - this.fieldName = fieldName; - return this; - } - - - public Builder children(List children) { - this.children.clear(); - this.children.addAll(children); - return this; - } - - public Builder level(int level) { - this.level = level; - return this; - } - - public Builder parent(ExecutableNormalizedField parent) { - this.parent = parent; - return this; - } - - public Builder deferredExecutions(LinkedHashSet deferredExecutions) { - this.deferredExecutions = deferredExecutions; - return this; - } - - public ExecutableNormalizedField build() { - return new ExecutableNormalizedField(this); - } - } -} diff --git a/src/main/java/graphql/normalized/ExecutableNormalizedOperation.java b/src/main/java/graphql/normalized/ExecutableNormalizedOperation.java deleted file mode 100644 index 3e3029101e..0000000000 --- a/src/main/java/graphql/normalized/ExecutableNormalizedOperation.java +++ /dev/null @@ -1,202 +0,0 @@ -package graphql.normalized; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableListMultimap; -import graphql.Assert; -import graphql.PublicApi; -import graphql.execution.MergedField; -import graphql.execution.ResultPath; -import graphql.execution.directives.QueryAppliedDirective; -import graphql.execution.directives.QueryDirectives; -import graphql.language.Field; -import graphql.language.OperationDefinition; -import graphql.schema.FieldCoordinates; -import graphql.schema.GraphQLFieldsContainer; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -import java.util.List; -import java.util.Map; - -/** - * A {@link ExecutableNormalizedOperation} represent how the text of a graphql operation (sometimes known colloquially as a query) - * will be executed at runtime according to the graphql specification. It handles complex mechanisms like merging - * duplicate fields into one and also detecting when the types of a given field may actually be for more than one possible object - * type. - *

- * An operation consists of a list of {@link ExecutableNormalizedField}s in a parent child hierarchy - */ -@PublicApi -@NullMarked -public class ExecutableNormalizedOperation { - private final OperationDefinition.Operation operation; - private final Map> operationDirectives; - private final @Nullable String operationName; - private final List topLevelFields; - private final ImmutableListMultimap fieldToNormalizedField; - private final Map normalizedFieldToMergedField; - private final Map normalizedFieldToQueryDirectives; - private final ImmutableListMultimap coordinatesToNormalizedFields; - private final int operationFieldCount; - private final int operationDepth; - - public ExecutableNormalizedOperation( - OperationDefinition.Operation operation, - @Nullable String operationName, - Map> operationDirectives, - List topLevelFields, - ImmutableListMultimap fieldToNormalizedField, - Map normalizedFieldToMergedField, - Map normalizedFieldToQueryDirectives, - ImmutableListMultimap coordinatesToNormalizedFields, - int operationFieldCount, - int operationDepth) { - this.operation = operation; - this.operationName = operationName; - this.operationDirectives = operationDirectives; - this.topLevelFields = topLevelFields; - this.fieldToNormalizedField = fieldToNormalizedField; - this.normalizedFieldToMergedField = normalizedFieldToMergedField; - this.normalizedFieldToQueryDirectives = normalizedFieldToQueryDirectives; - this.coordinatesToNormalizedFields = coordinatesToNormalizedFields; - this.operationFieldCount = operationFieldCount; - this.operationDepth = operationDepth; - } - - /** - * @return operation AST being executed - */ - public OperationDefinition.Operation getOperation() { - return operation; - } - - /** - * @return the operation name, which can be null - */ - public @Nullable String getOperationName() { - return operationName; - } - - /** - * This is the directives that are on the operation itself and not the fields under it for example - *

-     * {@code
-     *   query opName @foo { field }
-     * }
-     * 
- * - * @return the directives that are on this operation itself. - */ - public Map> getOperationDirectives() { - return operationDirectives; - } - - /** - * @return This returns how many {@link ExecutableNormalizedField}s are in the operation. - */ - public int getOperationFieldCount() { - return operationFieldCount; - } - - /** - * @return This returns the depth of the operation - */ - public int getOperationDepth() { - return operationDepth; - } - - /** - * This multimap shows how a given {@link ExecutableNormalizedField} maps to a one or more field coordinate in the schema - * - * @return a multimap of fields to schema field coordinates - */ - public ImmutableListMultimap getCoordinatesToNormalizedFields() { - return coordinatesToNormalizedFields; - } - - /** - * @return a list of the top level {@link ExecutableNormalizedField}s in this operation. - */ - public List getTopLevelFields() { - return topLevelFields; - } - - /** - * This is a multimap and the size of it reflects all the normalized fields in the operation - * - * @return an immutable list multimap of {@link Field} to {@link ExecutableNormalizedField} - */ - public ImmutableListMultimap getFieldToNormalizedField() { - return fieldToNormalizedField; - } - - /** - * Looks up one or more {@link ExecutableNormalizedField}s given a {@link Field} AST element in the operation - * - * @param field the field to look up - * - * @return zero, one or more possible {@link ExecutableNormalizedField}s that represent that field - */ - public List getNormalizedFields(Field field) { - return fieldToNormalizedField.get(field); - } - - /** - * @return a map of {@link ExecutableNormalizedField} to {@link MergedField}s - */ - public Map getNormalizedFieldToMergedField() { - return normalizedFieldToMergedField; - } - - /** - * Looks up the {@link MergedField} given a {@link ExecutableNormalizedField} - * - * @param executableNormalizedField the field to use the key - * - * @return a {@link MergedField} or null if its not present - */ - public @Nullable MergedField getMergedField(ExecutableNormalizedField executableNormalizedField) { - return normalizedFieldToMergedField.get(executableNormalizedField); - } - - /** - * @return a map of {@link ExecutableNormalizedField} to its {@link QueryDirectives} - */ - public Map getNormalizedFieldToQueryDirectives() { - return normalizedFieldToQueryDirectives; - - } - - /** - * This looks up the {@link QueryDirectives} associated with the given {@link ExecutableNormalizedField} - * - * @param executableNormalizedField the executable normalised field in question - * - * @return the fields query directives or null - */ - public @Nullable QueryDirectives getQueryDirectives(ExecutableNormalizedField executableNormalizedField) { - return normalizedFieldToQueryDirectives.get(executableNormalizedField); - } - - /** - * This will find a {@link ExecutableNormalizedField} given a merged field and a result path. If this does not find a field it will assert with an exception - * - * @param mergedField the merged field - * @param fieldsContainer the containing type of that field - * @param resultPath the result path in play - * - * @return the ExecutableNormalizedField - */ - public ExecutableNormalizedField getNormalizedField(MergedField mergedField, GraphQLFieldsContainer fieldsContainer, ResultPath resultPath) { - List executableNormalizedFields = fieldToNormalizedField.get(mergedField.getSingleField()); - List keysOnlyPath = resultPath.getKeysOnly(); - for (ExecutableNormalizedField executableNormalizedField : executableNormalizedFields) { - if (executableNormalizedField.getListOfResultKeys().equals(keysOnlyPath)) { - if (executableNormalizedField.getObjectTypeNames().contains(fieldsContainer.getName())) { - return executableNormalizedField; - } - } - } - return Assert.assertShouldNeverHappen("normalized field not found"); - } -} diff --git a/src/main/java/graphql/normalized/ExecutableNormalizedOperationFactory.java b/src/main/java/graphql/normalized/ExecutableNormalizedOperationFactory.java deleted file mode 100644 index b2adb7ffcb..0000000000 --- a/src/main/java/graphql/normalized/ExecutableNormalizedOperationFactory.java +++ /dev/null @@ -1,985 +0,0 @@ -package graphql.normalized; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableListMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import graphql.Assert; -import graphql.Directives; -import graphql.ExperimentalApi; -import graphql.GraphQLContext; -import graphql.PublicApi; -import graphql.collect.ImmutableKit; -import graphql.execution.AbortExecutionException; -import graphql.execution.CoercedVariables; -import graphql.execution.MergedField; -import graphql.execution.NormalizedVariables; -import graphql.execution.RawVariables; -import graphql.execution.ValuesResolver; -import graphql.execution.conditional.ConditionalNodes; -import graphql.execution.directives.OperationDirectivesResolver; -import graphql.execution.directives.QueryAppliedDirective; -import graphql.execution.directives.QueryDirectives; -import graphql.execution.directives.QueryDirectivesImpl; -import graphql.execution.incremental.IncrementalUtils; -import graphql.introspection.Introspection; -import graphql.language.Directive; -import graphql.language.Document; -import graphql.language.Field; -import graphql.language.FragmentDefinition; -import graphql.language.FragmentSpread; -import graphql.language.InlineFragment; -import graphql.language.NodeUtil; -import graphql.language.OperationDefinition; -import graphql.language.Selection; -import graphql.language.SelectionSet; -import graphql.language.VariableDefinition; -import graphql.normalized.incremental.NormalizedDeferredExecution; -import graphql.schema.FieldCoordinates; -import graphql.schema.GraphQLCompositeType; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLInterfaceType; -import graphql.schema.GraphQLNamedOutputType; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLType; -import graphql.schema.GraphQLUnionType; -import graphql.schema.GraphQLUnmodifiedType; -import graphql.schema.impl.SchemaUtil; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.IdentityHashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -import static graphql.Assert.assertNotNull; -import static graphql.Assert.assertShouldNeverHappen; -import static graphql.collect.ImmutableKit.map; -import static graphql.collect.ImmutableKit.mapToSet; -import static graphql.schema.GraphQLTypeUtil.unwrapAll; -import static graphql.util.FpKit.filterSet; -import static graphql.util.FpKit.groupingBy; -import static graphql.util.FpKit.intersection; -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; -import static java.util.stream.Collectors.toCollection; -import static java.util.stream.Collectors.toSet; - -/** - * This factory can create a {@link ExecutableNormalizedOperation} which represents what would be executed - * during a given graphql operation. - */ -@PublicApi -@NullMarked -public class ExecutableNormalizedOperationFactory { - - public static class Options { - - - private final GraphQLContext graphQLContext; - private final Locale locale; - private final int maxChildrenDepth; - private final int maxFieldsCount; - - private final boolean deferSupport; - - /** - * The default max fields count is 100,000. - * This is big enough for even very large queries, but - * can be changed via {#setDefaultOptions - */ - public static final int DEFAULT_MAX_FIELDS_COUNT = 100_000; - private static Options defaultOptions = new Options(GraphQLContext.getDefault(), - Locale.getDefault(), - Integer.MAX_VALUE, - DEFAULT_MAX_FIELDS_COUNT, - false); - - private Options(GraphQLContext graphQLContext, - Locale locale, - int maxChildrenDepth, - int maxFieldsCount, - boolean deferSupport) { - this.graphQLContext = graphQLContext; - this.locale = locale; - this.maxChildrenDepth = maxChildrenDepth; - this.deferSupport = deferSupport; - this.maxFieldsCount = maxFieldsCount; - } - - /** - * Sets new default Options used when creating instances of {@link ExecutableNormalizedOperation}. - * - * @param options new default options - */ - public static void setDefaultOptions(Options options) { - defaultOptions = Assert.assertNotNull(options); - } - - - /** - * Returns the default options used when creating instances of {@link ExecutableNormalizedOperation}. - * - * @return the default options - */ - public static Options defaultOptions() { - return defaultOptions; - } - - /** - * Locale to use when parsing the query. - *

- * e.g. can be passed to {@link graphql.schema.Coercing} for parsing. - * - * @param locale the locale to use - * - * @return new options object to use - */ - public Options locale(Locale locale) { - return new Options(this.graphQLContext, locale, this.maxChildrenDepth, this.maxFieldsCount, this.deferSupport); - } - - /** - * Context object to use when parsing the operation. - *

- * Can be used to intercept input values e.g. using {@link graphql.execution.values.InputInterceptor}. - * - * @param graphQLContext the context to use - * - * @return new options object to use - */ - public Options graphQLContext(GraphQLContext graphQLContext) { - return new Options(graphQLContext, this.locale, this.maxChildrenDepth, this.maxFieldsCount, this.deferSupport); - } - - /** - * Controls the maximum depth of the operation. Can be used to prevent - * against malicious operations. - * - * @param maxChildrenDepth the max depth - * - * @return new options object to use - */ - public Options maxChildrenDepth(int maxChildrenDepth) { - return new Options(this.graphQLContext, this.locale, maxChildrenDepth, this.maxFieldsCount, this.deferSupport); - } - - /** - * Controls the maximum number of ENFs created. Can be used to prevent - * against malicious operations. - * - * @param maxFieldsCount the max number of ENFs created - * - * @return new options object to use - */ - public Options maxFieldsCount(int maxFieldsCount) { - return new Options(this.graphQLContext, this.locale, this.maxChildrenDepth, maxFieldsCount, this.deferSupport); - } - - /** - * Controls whether defer execution is supported when creating instances of {@link ExecutableNormalizedOperation}. - * - * @param deferSupport true to enable support for defer - * - * @return new options object to use - */ - @ExperimentalApi - public Options deferSupport(boolean deferSupport) { - return new Options(this.graphQLContext, this.locale, this.maxChildrenDepth, this.maxFieldsCount, deferSupport); - } - - /** - * @return context to use during operation parsing - * - * @see #graphQLContext(GraphQLContext) - */ - public GraphQLContext getGraphQLContext() { - return graphQLContext; - } - - /** - * @return locale to use during operation parsing - * - * @see #locale(Locale) - */ - public Locale getLocale() { - return locale; - } - - /** - * @return maximum children depth before aborting parsing - * - * @see #maxChildrenDepth(int) - */ - public int getMaxChildrenDepth() { - return maxChildrenDepth; - } - - public int getMaxFieldsCount() { - return maxFieldsCount; - } - - /** - * @return whether support for defer is enabled - * - * @see #deferSupport(boolean) - */ - @ExperimentalApi - public boolean getDeferSupport() { - return deferSupport; - } - } - - private static final ConditionalNodes conditionalNodes = new ConditionalNodes(); - - private ExecutableNormalizedOperationFactory() { - - } - - /** - * This will create a runtime representation of the graphql operation that would be executed - * in a runtime sense. - * - * @param graphQLSchema the schema to be used - * @param document the {@link Document} holding the operation text - * @param operationName the operation name to use - * @param coercedVariableValues the coerced variables to use - * - * @return a runtime representation of the graphql operation. - */ - public static ExecutableNormalizedOperation createExecutableNormalizedOperation( - GraphQLSchema graphQLSchema, - Document document, - String operationName, - CoercedVariables coercedVariableValues - ) { - return createExecutableNormalizedOperation( - graphQLSchema, - document, - operationName, - coercedVariableValues, - Options.defaultOptions()); - } - - /** - * This will create a runtime representation of the graphql operation that would be executed - * in a runtime sense. - * - * @param graphQLSchema the schema to be used - * @param document the {@link Document} holding the operation text - * @param operationName the operation name to use - * @param coercedVariableValues the coerced variables to use - * @param options the {@link Options} to use for parsing - * - * @return a runtime representation of the graphql operation. - */ - public static ExecutableNormalizedOperation createExecutableNormalizedOperation( - GraphQLSchema graphQLSchema, - Document document, - String operationName, - CoercedVariables coercedVariableValues, - Options options - ) { - NodeUtil.GetOperationResult getOperationResult = NodeUtil.getOperation(document, operationName); - - return new ExecutableNormalizedOperationFactoryImpl( - graphQLSchema, - getOperationResult.operationDefinition, - getOperationResult.fragmentsByName, - coercedVariableValues, - null, - options - ).createNormalizedQueryImpl(); - } - - /** - * This will create a runtime representation of the graphql operation that would be executed - * in a runtime sense. - * - * @param graphQLSchema the schema to be used - * @param operationDefinition the operation to be executed - * @param fragments a set of fragments associated with the operation - * @param coercedVariableValues the coerced variables to use - * - * @return a runtime representation of the graphql operation. - */ - public static ExecutableNormalizedOperation createExecutableNormalizedOperation(GraphQLSchema graphQLSchema, - OperationDefinition operationDefinition, - Map fragments, - CoercedVariables coercedVariableValues) { - return createExecutableNormalizedOperation(graphQLSchema, - operationDefinition, - fragments, - coercedVariableValues, - Options.defaultOptions()); - } - - /** - * This will create a runtime representation of the graphql operation that would be executed - * in a runtime sense. - * - * @param graphQLSchema the schema to be used - * @param operationDefinition the operation to be executed - * @param fragments a set of fragments associated with the operation - * @param coercedVariableValues the coerced variables to use - * @param options the options to use - * - * @return a runtime representation of the graphql operation. - */ - public static ExecutableNormalizedOperation createExecutableNormalizedOperation(GraphQLSchema graphQLSchema, - OperationDefinition operationDefinition, - Map fragments, - CoercedVariables coercedVariableValues, - Options options) { - return new ExecutableNormalizedOperationFactoryImpl( - graphQLSchema, - operationDefinition, - fragments, - coercedVariableValues, - null, - options - ).createNormalizedQueryImpl(); - } - - /** - * This will create a runtime representation of the graphql operation that would be executed - * in a runtime sense. - * - * @param graphQLSchema the schema to be used - * @param document the {@link Document} holding the operation text - * @param operationName the operation name to use - * @param rawVariables the raw variables to be coerced - * - * @return a runtime representation of the graphql operation. - */ - public static ExecutableNormalizedOperation createExecutableNormalizedOperationWithRawVariables(GraphQLSchema graphQLSchema, - Document document, - String operationName, - RawVariables rawVariables) { - return createExecutableNormalizedOperationWithRawVariables(graphQLSchema, - document, - operationName, - rawVariables, - Options.defaultOptions()); - } - - - /** - * This will create a runtime representation of the graphql operation that would be executed - * in a runtime sense. - * - * @param graphQLSchema the schema to be used - * @param document the {@link Document} holding the operation text - * @param operationName the operation name to use - * @param rawVariables the raw variables that have not yet been coerced - * @param locale the {@link Locale} to use during coercion - * @param graphQLContext the {@link GraphQLContext} to use during coercion - * - * @return a runtime representation of the graphql operation. - */ - public static ExecutableNormalizedOperation createExecutableNormalizedOperationWithRawVariables( - GraphQLSchema graphQLSchema, - Document document, - String operationName, - RawVariables rawVariables, - GraphQLContext graphQLContext, - Locale locale - ) { - return createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - operationName, - rawVariables, - Options.defaultOptions().graphQLContext(graphQLContext).locale(locale)); - } - - - /** - * This will create a runtime representation of the graphql operation that would be executed - * in a runtime sense. - * - * @param graphQLSchema the schema to be used - * @param document the {@link Document} holding the operation text - * @param operationName the operation name to use - * @param rawVariables the raw variables that have not yet been coerced - * @param options the {@link Options} to use for parsing - * - * @return a runtime representation of the graphql operation. - */ - public static ExecutableNormalizedOperation createExecutableNormalizedOperationWithRawVariables(GraphQLSchema graphQLSchema, - Document document, - String operationName, - RawVariables rawVariables, - Options options) { - NodeUtil.GetOperationResult getOperationResult = NodeUtil.getOperation(document, operationName); - OperationDefinition operationDefinition = getOperationResult.operationDefinition; - - List variableDefinitions = operationDefinition.getVariableDefinitions(); - CoercedVariables coercedVariableValues = ValuesResolver.coerceVariableValues(graphQLSchema, - variableDefinitions, - rawVariables, - options.getGraphQLContext(), - options.getLocale()); - NormalizedVariables normalizedVariableValues = ValuesResolver.getNormalizedVariableValues(graphQLSchema, - variableDefinitions, - rawVariables, - options.getGraphQLContext(), - options.getLocale()); - - return new ExecutableNormalizedOperationFactoryImpl( - graphQLSchema, - operationDefinition, - getOperationResult.fragmentsByName, - coercedVariableValues, - normalizedVariableValues, - options - ).createNormalizedQueryImpl(); - } - - - private static class ExecutableNormalizedOperationFactoryImpl { - private final GraphQLSchema graphQLSchema; - private final OperationDefinition operationDefinition; - private final Map fragments; - private final CoercedVariables coercedVariableValues; - private final @Nullable NormalizedVariables normalizedVariableValues; - private final Options options; - private final OperationDirectivesResolver directivesResolver = new OperationDirectivesResolver(); - - private final List possibleMergerList = new ArrayList<>(); - - private final ImmutableListMultimap.Builder fieldToNormalizedField = ImmutableListMultimap.builder(); - private final ImmutableMap.Builder normalizedFieldToMergedField = ImmutableMap.builder(); - private final ImmutableMap.Builder normalizedFieldToQueryDirectives = ImmutableMap.builder(); - private final ImmutableListMultimap.Builder coordinatesToNormalizedFields = ImmutableListMultimap.builder(); - private int fieldCount = 0; - private int maxDepthSeen = 0; - - private final List rootEnfs = new ArrayList<>(); - - private ExecutableNormalizedOperationFactoryImpl( - GraphQLSchema graphQLSchema, - OperationDefinition operationDefinition, - Map fragments, - CoercedVariables coercedVariableValues, - @Nullable NormalizedVariables normalizedVariableValues, - Options options - ) { - this.graphQLSchema = graphQLSchema; - this.operationDefinition = operationDefinition; - this.fragments = fragments; - this.coercedVariableValues = coercedVariableValues; - this.normalizedVariableValues = normalizedVariableValues; - this.options = options; - } - - /** - * Creates a new ExecutableNormalizedOperation for the provided query - */ - private ExecutableNormalizedOperation createNormalizedQueryImpl() { - buildEnfsRecursively(null, null, 0); - - for (PossibleMerger possibleMerger : possibleMergerList) { - ExecutableNormalizedField mergerParent = assertNotNull(possibleMerger.parent, "possibleMerger.parent should not be null"); - List childrenWithSameResultKey = mergerParent.getChildrenWithSameResultKey(possibleMerger.resultKey); - ENFMerger.merge(mergerParent, childrenWithSameResultKey, graphQLSchema, options.deferSupport); - } - - Map> operationDirectives = directivesResolver.resolveDirectivesByName(operationDefinition, - graphQLSchema, - coercedVariableValues, - options.graphQLContext, - options.locale); - - return new ExecutableNormalizedOperation( - operationDefinition.getOperation(), - operationDefinition.getName(), - operationDirectives, - new ArrayList<>(rootEnfs), - fieldToNormalizedField.build(), - normalizedFieldToMergedField.build(), - normalizedFieldToQueryDirectives.build(), - coordinatesToNormalizedFields.build(), - fieldCount, - maxDepthSeen - ); - } - - private void captureMergedField(ExecutableNormalizedField enf, MergedField mergedFld) { - // QueryDirectivesImpl is a lazy object and only computes itself when asked for - QueryDirectives queryDirectives = new QueryDirectivesImpl(mergedFld, - graphQLSchema, - coercedVariableValues, - () -> normalizedVariableValues, - options.getGraphQLContext(), - options.getLocale()); - normalizedFieldToQueryDirectives.put(enf, queryDirectives); - normalizedFieldToMergedField.put(enf, mergedFld); - } - - private void buildEnfsRecursively(@Nullable ExecutableNormalizedField executableNormalizedField, - @Nullable ImmutableList fieldAndAstParents, - int curLevel) { - if (this.maxDepthSeen < curLevel) { - this.maxDepthSeen = curLevel; - checkMaxDepthExceeded(curLevel); - } - Set possibleObjects; - List collectedFields; - Map deferredExecutions = new IdentityHashMap<>(); - - // special handling for the root selection Set - if (executableNormalizedField == null) { - GraphQLObjectType rootType = SchemaUtil.getOperationRootType(graphQLSchema, operationDefinition); - possibleObjects = ImmutableSet.of(rootType); - collectedFields = new ArrayList<>(); - collectFromSelectionSet(operationDefinition.getSelectionSet(), collectedFields, rootType, possibleObjects, null, deferredExecutions); - } else { - List fieldDefs = executableNormalizedField.getFieldDefinitions(graphQLSchema); - possibleObjects = resolvePossibleObjects(fieldDefs); - if (possibleObjects.isEmpty()) { - return; - } - collectedFields = new ArrayList<>(); - for (CollectedField fieldAndAstParent : assertNotNull(fieldAndAstParents, "fieldAndAstParents should not be null")) { - if (fieldAndAstParent.field.getSelectionSet() == null) { - continue; - } - // the AST parent comes from the previous collect from selection set call - // and is the type to which the field belongs (the container type of the field) and output type - // of the field needs to be determined based on the field name - GraphQLFieldDefinition fieldDefinition = Introspection.getFieldDef(graphQLSchema, fieldAndAstParent.astTypeCondition, fieldAndAstParent.field.getName()); - // it must a composite type, because the field has a selection set - GraphQLCompositeType selectionSetType = (GraphQLCompositeType) unwrapAll(fieldDefinition.getType()); - this.collectFromSelectionSet(fieldAndAstParent.field.getSelectionSet(), - collectedFields, - selectionSetType, - possibleObjects, - null, - deferredExecutions - ); - } - } - - Map> fieldsByName = fieldsByResultKey(collectedFields); - ImmutableList.Builder resultNFs = ImmutableList.builder(); - ImmutableListMultimap.Builder normalizedFieldToAstFields = ImmutableListMultimap.builder(); - createNFs(resultNFs, fieldsByName, normalizedFieldToAstFields, curLevel + 1, executableNormalizedField); - - ImmutableList nextLevelChildren = resultNFs.build(); - ImmutableListMultimap nextLevelNormalizedFieldToAstFields = normalizedFieldToAstFields.build(); - - for (ExecutableNormalizedField childENF : nextLevelChildren) { - if (executableNormalizedField == null) { - // all root ENFs don't have a parent, but are collected in the rootEnfs list - rootEnfs.add(childENF); - } else { - executableNormalizedField.addChild(childENF); - } - ImmutableList childFieldAndAstParents = nextLevelNormalizedFieldToAstFields.get(childENF); - - MergedField mergedField = newMergedField(childFieldAndAstParents); - captureMergedField(childENF, mergedField); - - updateFieldToNFMap(childENF, childFieldAndAstParents); - updateCoordinatedToNFMap(childENF); - - // recursive call - buildEnfsRecursively(childENF, - childFieldAndAstParents, - curLevel + 1); - } - } - - private void checkMaxDepthExceeded(int depthSeen) { - if (depthSeen > this.options.getMaxChildrenDepth()) { - throw new AbortExecutionException("Maximum query depth exceeded. " + depthSeen + " > " + this.options.getMaxChildrenDepth()); - } - } - - private static MergedField newMergedField(ImmutableList fieldAndAstParents) { - return MergedField.newMergedField(mapToSet(fieldAndAstParents, fieldAndAstParent -> fieldAndAstParent.field)).build(); - } - - private void updateFieldToNFMap(ExecutableNormalizedField executableNormalizedField, - ImmutableList mergedField) { - for (CollectedField astField : mergedField) { - fieldToNormalizedField.put(astField.field, executableNormalizedField); - } - } - - private void updateCoordinatedToNFMap(ExecutableNormalizedField topLevel) { - for (String objectType : topLevel.getObjectTypeNames()) { - FieldCoordinates coordinates = FieldCoordinates.coordinates(objectType, topLevel.getFieldName()); - coordinatesToNormalizedFields.put(coordinates, topLevel); - } - } - - - private Map> fieldsByResultKey(List collectedFields) { - Map> fieldsByName = new LinkedHashMap<>(); - for (CollectedField collectedField : collectedFields) { - fieldsByName.computeIfAbsent(collectedField.field.getResultKey(), ignored -> new ArrayList<>()).add(collectedField); - } - return fieldsByName; - } - - - private void createNFs(ImmutableList.Builder nfListBuilder, - Map> fieldsByName, - ImmutableListMultimap.Builder normalizedFieldToAstFields, - int level, - @Nullable ExecutableNormalizedField parent) { - for (String resultKey : fieldsByName.keySet()) { - List fieldsWithSameResultKey = fieldsByName.get(resultKey); - List commonParentsGroups = groupByCommonParents(fieldsWithSameResultKey); - for (CollectedFieldGroup fieldGroup : commonParentsGroups) { - ExecutableNormalizedField nf = createNF(fieldGroup, level, parent); - if (nf == null) { - continue; - } - for (CollectedField collectedField : fieldGroup.fields) { - normalizedFieldToAstFields.put(nf, collectedField); - } - nfListBuilder.add(nf); - - if (this.options.deferSupport) { - nf.addDeferredExecutions(assertNotNull(fieldGroup.deferredExecutions, "Deferred executions must exist when defer support is enabled")); - } - } - if (commonParentsGroups.size() > 1) { - possibleMergerList.add(new PossibleMerger(parent, resultKey)); - } - } - } - - // new single ENF - private ExecutableNormalizedField createNF(CollectedFieldGroup collectedFieldGroup, - int level, - @Nullable ExecutableNormalizedField parent) { - - this.fieldCount++; - if (this.fieldCount > this.options.getMaxFieldsCount()) { - throw new AbortExecutionException("Maximum field count exceeded. " + this.fieldCount + " > " + this.options.getMaxFieldsCount()); - } - Field field; - Set objectTypes = collectedFieldGroup.objectTypes; - field = collectedFieldGroup.fields.iterator().next().field; - String fieldName = field.getName(); - GraphQLFieldDefinition fieldDefinition = Introspection.getFieldDefinition(graphQLSchema, objectTypes.iterator().next(), fieldName); - - Map argumentValues = ValuesResolver.getArgumentValues(fieldDefinition.getArguments(), field.getArguments(), CoercedVariables.of(this.coercedVariableValues.toMap()), this.options.graphQLContext, this.options.locale); - Map normalizedArgumentValues = null; - if (this.normalizedVariableValues != null) { - normalizedArgumentValues = ValuesResolver.getNormalizedArgumentValues(fieldDefinition.getArguments(), field.getArguments(), this.normalizedVariableValues.toMap()); - } - ImmutableList objectTypeNames = map(objectTypes, GraphQLObjectType::getName); - return ExecutableNormalizedField.newNormalizedField() - .alias(field.getAlias()) - .resolvedArguments(argumentValues) - .normalizedArguments(normalizedArgumentValues) - .astArguments(field.getArguments()) - .objectTypeNames(objectTypeNames) - .fieldName(fieldName) - .level(level) - .parent(parent) - .build(); - } - - private List groupByCommonParents(Collection fields) { - if (this.options.deferSupport) { - return groupByCommonParentsWithDeferSupport(fields); - } else { - return groupByCommonParentsNoDeferSupport(fields); - } - } - - private List groupByCommonParentsNoDeferSupport(Collection fields) { - ImmutableSet.Builder objectTypes = ImmutableSet.builder(); - for (CollectedField collectedField : fields) { - objectTypes.addAll(collectedField.objectTypes); - } - Set allRelevantObjects = objectTypes.build(); - Map> groupByAstParent = groupingBy(fields, fieldAndType -> fieldAndType.astTypeCondition); - if (groupByAstParent.size() == 1) { - return singletonList(new CollectedFieldGroup(ImmutableSet.copyOf(fields), allRelevantObjects, null)); - } - ImmutableList.Builder result = ImmutableList.builder(); - for (GraphQLObjectType objectType : allRelevantObjects) { - Set relevantFields = filterSet(fields, field -> field.objectTypes.contains(objectType)); - result.add(new CollectedFieldGroup(relevantFields, singleton(objectType), null)); - } - return result.build(); - } - - private List groupByCommonParentsWithDeferSupport(Collection fields) { - ImmutableSet.Builder objectTypes = ImmutableSet.builder(); - ImmutableSet.Builder deferredExecutionsBuilder = ImmutableSet.builder(); - - for (CollectedField collectedField : fields) { - objectTypes.addAll(collectedField.objectTypes); - - NormalizedDeferredExecution collectedDeferredExecution = collectedField.deferredExecution; - - if (collectedDeferredExecution != null) { - deferredExecutionsBuilder.add(collectedDeferredExecution); - } - } - - Set allRelevantObjects = objectTypes.build(); - Set deferredExecutions = deferredExecutionsBuilder.build(); - - Set duplicatedLabels = listDuplicatedLabels(deferredExecutions); - - if (!duplicatedLabels.isEmpty()) { - // Query validation should pick this up - Assert.assertShouldNeverHappen("Duplicated @defer labels are not allowed: [%s]", String.join(",", duplicatedLabels)); - } - - Map> groupByAstParent = groupingBy(fields, fieldAndType -> fieldAndType.astTypeCondition); - if (groupByAstParent.size() == 1) { - return singletonList(new CollectedFieldGroup(ImmutableSet.copyOf(fields), allRelevantObjects, deferredExecutions)); - } - - ImmutableList.Builder result = ImmutableList.builder(); - for (GraphQLObjectType objectType : allRelevantObjects) { - Set relevantFields = filterSet(fields, field -> field.objectTypes.contains(objectType)); - - Set filteredDeferredExecutions = deferredExecutions.stream() - .filter(filterExecutionsFromType(objectType)) - .collect(toCollection(LinkedHashSet::new)); - - result.add(new CollectedFieldGroup(relevantFields, singleton(objectType), filteredDeferredExecutions)); - } - return result.build(); - } - - private static Predicate filterExecutionsFromType(GraphQLObjectType objectType) { - String objectTypeName = objectType.getName(); - return deferredExecution -> deferredExecution.getPossibleTypes() - .stream() - .map(GraphQLObjectType::getName) - .anyMatch(objectTypeName::equals); - } - - private Set listDuplicatedLabels(Collection deferredExecutions) { - return deferredExecutions.stream() - .map(NormalizedDeferredExecution::getLabel) - .filter(Objects::nonNull) - .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) - .entrySet() - .stream() - .filter(entry -> entry.getValue() > 1) - .map(Map.Entry::getKey) - .collect(toSet()); - } - - private void collectFromSelectionSet(SelectionSet selectionSet, - List result, - GraphQLCompositeType astTypeCondition, - Set possibleObjects, - @Nullable NormalizedDeferredExecution deferredExecution, - Map deferredExecutions - ) { - for (Selection selection : selectionSet.getSelections()) { - if (selection instanceof Field) { - collectField(result, (Field) selection, possibleObjects, astTypeCondition, deferredExecution); - } else if (selection instanceof InlineFragment) { - collectInlineFragment(result, (InlineFragment) selection, possibleObjects, astTypeCondition, deferredExecutions); - } else if (selection instanceof FragmentSpread) { - collectFragmentSpread(result, (FragmentSpread) selection, possibleObjects, deferredExecutions); - } - } - } - - private void collectFragmentSpread(List result, - FragmentSpread fragmentSpread, - Set possibleObjects, - Map deferredExecutions - ) { - if (!conditionalNodes.shouldInclude(fragmentSpread, - this.coercedVariableValues.toMap(), - this.graphQLSchema, - this.options.graphQLContext)) { - return; - } - FragmentDefinition fragmentDefinition = assertNotNull(this.fragments.get(fragmentSpread.getName())); - - if (!conditionalNodes.shouldInclude(fragmentDefinition, - this.coercedVariableValues.toMap(), - this.graphQLSchema, - this.options.graphQLContext)) { - return; - } - GraphQLCompositeType newAstTypeCondition = (GraphQLCompositeType) assertNotNull(this.graphQLSchema.getType(fragmentDefinition.getTypeCondition().getName())); - Set newPossibleObjects = narrowDownPossibleObjects(possibleObjects, newAstTypeCondition); - - NormalizedDeferredExecution newDeferredExecution = buildDeferredExecution( - fragmentSpread.getDirectives(), - newPossibleObjects, - deferredExecutions); - - collectFromSelectionSet(fragmentDefinition.getSelectionSet(), result, newAstTypeCondition, newPossibleObjects, newDeferredExecution, deferredExecutions); - } - - private void collectInlineFragment(List result, - InlineFragment inlineFragment, - Set possibleObjects, - GraphQLCompositeType astTypeCondition, - Map deferredExecutions - ) { - if (!conditionalNodes.shouldInclude(inlineFragment, this.coercedVariableValues.toMap(), this.graphQLSchema, this.options.graphQLContext)) { - return; - } - Set newPossibleObjects = possibleObjects; - GraphQLCompositeType newAstTypeCondition = astTypeCondition; - - if (inlineFragment.getTypeCondition() != null) { - newAstTypeCondition = (GraphQLCompositeType) assertNotNull(this.graphQLSchema.getType(inlineFragment.getTypeCondition().getName()), "type should not be null"); - newPossibleObjects = narrowDownPossibleObjects(possibleObjects, newAstTypeCondition); - - } - - NormalizedDeferredExecution newDeferredExecution = buildDeferredExecution( - inlineFragment.getDirectives(), - newPossibleObjects, - deferredExecutions - ); - - collectFromSelectionSet(inlineFragment.getSelectionSet(), result, newAstTypeCondition, newPossibleObjects, newDeferredExecution, deferredExecutions); - } - - private @Nullable NormalizedDeferredExecution buildDeferredExecution( - List directives, - Set newPossibleObjects, - Map deferredExecutions) { - if (!options.deferSupport) { - return null; - } - Directive deferDirective = NodeUtil.findNodeByName(directives, Directives.DeferDirective.getName()); - if (deferDirective == null) { - return null; - } - NormalizedDeferredExecution deferredExecution = deferredExecutions.get(deferDirective); - if (deferredExecution != null) { - deferredExecution.getPossibleTypes().addAll(newPossibleObjects); - return deferredExecution; - } - - deferredExecution = IncrementalUtils.createDeferredExecution( - this.coercedVariableValues.toMap(), - directives, - (label) -> new NormalizedDeferredExecution(label, new LinkedHashSet<>(newPossibleObjects)) - ); - if (deferredExecution != null) { - deferredExecutions.put(deferDirective, deferredExecution); - } - return deferredExecution; - } - - private void collectField(List result, - Field field, - Set possibleObjectTypes, - GraphQLCompositeType astTypeCondition, - @Nullable NormalizedDeferredExecution deferredExecution - ) { - if (!conditionalNodes.shouldInclude(field, - this.coercedVariableValues.toMap(), - this.graphQLSchema, - this.options.graphQLContext)) { - return; - } - // this means there is actually no possible type for this field, and we are done - if (possibleObjectTypes.isEmpty()) { - return; - } - result.add(new CollectedField(field, possibleObjectTypes, astTypeCondition, deferredExecution)); - } - - private Set narrowDownPossibleObjects(Set currentOnes, - GraphQLCompositeType typeCondition) { - - ImmutableSet resolvedTypeCondition = resolvePossibleObjects(typeCondition); - if (currentOnes.isEmpty()) { - return resolvedTypeCondition; - } - - // Faster intersection, as either set often has a size of 1. - return intersection(currentOnes, resolvedTypeCondition); - } - - private ImmutableSet resolvePossibleObjects(List defs) { - ImmutableSet.Builder builder = ImmutableSet.builder(); - - for (GraphQLFieldDefinition def : defs) { - GraphQLUnmodifiedType outputType = unwrapAll(def.getType()); - if (outputType instanceof GraphQLCompositeType) { - builder.addAll(resolvePossibleObjects((GraphQLCompositeType) outputType)); - } - } - - return builder.build(); - } - - private ImmutableSet resolvePossibleObjects(GraphQLCompositeType type) { - if (type instanceof GraphQLObjectType) { - return ImmutableSet.of((GraphQLObjectType) type); - } else if (type instanceof GraphQLInterfaceType) { - return ImmutableSet.copyOf(graphQLSchema.getImplementations((GraphQLInterfaceType) type)); - } else if (type instanceof GraphQLUnionType) { - List unionTypes = ((GraphQLUnionType) type).getTypes(); - return ImmutableSet.copyOf(ImmutableKit.map(unionTypes, GraphQLObjectType.class::cast)); - } else { - return assertShouldNeverHappen(); - } - } - - private static class PossibleMerger { - @Nullable ExecutableNormalizedField parent; - String resultKey; - - public PossibleMerger(@Nullable ExecutableNormalizedField parent, String resultKey) { - this.parent = parent; - this.resultKey = resultKey; - } - } - - private static class CollectedField { - Field field; - Set objectTypes; - GraphQLCompositeType astTypeCondition; - @Nullable NormalizedDeferredExecution deferredExecution; - - public CollectedField(Field field, Set objectTypes, GraphQLCompositeType astTypeCondition, @Nullable NormalizedDeferredExecution deferredExecution) { - this.field = field; - this.objectTypes = objectTypes; - this.astTypeCondition = astTypeCondition; - this.deferredExecution = deferredExecution; - } - } - - private static class CollectedFieldGroup { - Set objectTypes; - Set fields; - @Nullable Set deferredExecutions; - - public CollectedFieldGroup(Set fields, Set objectTypes, @Nullable Set deferredExecutions) { - this.fields = fields; - this.objectTypes = objectTypes; - this.deferredExecutions = deferredExecutions; - } - } - } - -} diff --git a/src/main/java/graphql/normalized/ExecutableNormalizedOperationToAstCompiler.java b/src/main/java/graphql/normalized/ExecutableNormalizedOperationToAstCompiler.java deleted file mode 100644 index 95cb59f6de..0000000000 --- a/src/main/java/graphql/normalized/ExecutableNormalizedOperationToAstCompiler.java +++ /dev/null @@ -1,473 +0,0 @@ -package graphql.normalized; - -import com.google.common.collect.ImmutableList; -import graphql.Assert; -import graphql.Directives; -import graphql.ExperimentalApi; -import graphql.PublicApi; -import graphql.execution.directives.QueryAppliedDirective; -import graphql.execution.directives.QueryDirectives; -import graphql.introspection.Introspection; -import graphql.language.Argument; -import graphql.language.Directive; -import graphql.language.Document; -import graphql.language.Field; -import graphql.language.InlineFragment; -import graphql.language.OperationDefinition; -import graphql.language.Selection; -import graphql.language.SelectionSet; -import graphql.language.StringValue; -import graphql.language.TypeName; -import graphql.normalized.incremental.NormalizedDeferredExecution; -import graphql.schema.GraphQLCompositeType; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLUnmodifiedType; -import graphql.util.LinkedHashMapFactory; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -import static graphql.collect.ImmutableKit.emptyList; -import static graphql.language.Argument.newArgument; -import static graphql.language.Field.newField; -import static graphql.language.InlineFragment.newInlineFragment; -import static graphql.language.SelectionSet.newSelectionSet; -import static graphql.language.TypeName.newTypeName; -import static graphql.normalized.ArgumentMaker.createArguments; -import static graphql.schema.GraphQLTypeUtil.unwrapAll; - -/** - * This class can take a list of {@link ExecutableNormalizedField}s and compiling out a - * normalised operation {@link Document} that would represent how those fields - * may be executed. - *

- * This is essentially the reverse of {@link ExecutableNormalizedOperationFactory} which takes - * operation text and makes {@link ExecutableNormalizedField}s from it, this takes {@link ExecutableNormalizedField}s - * and makes operation text from it. - *

- * You could for example send that operation text onto to some other graphql server if it - * has the same schema as the one provided. - */ -@PublicApi -@NullMarked -public class ExecutableNormalizedOperationToAstCompiler { - - /** - * The result is a {@link Document} and a map of variables - * that would go with that document. - */ - public static class CompilerResult { - private final Document document; - private final Map variables; - - public CompilerResult(Document document, Map variables) { - this.document = document; - this.variables = variables; - } - - public Document getDocument() { - return document; - } - - public Map getVariables() { - return variables; - } - } - - /** - * This will compile an operation text {@link Document} with possibly variables from the given {@link ExecutableNormalizedField}s - *

- * The {@link VariablePredicate} is used called to decide if the given argument values should be made into a variable - * OR inlined into the operation text as a graphql literal. - * - * @param schema the graphql schema to use - * @param operationKind the kind of operation - * @param operationName the name of the operation to use - * @param topLevelFields the top level {@link ExecutableNormalizedField}s to start from - * @param variablePredicate the variable predicate that decides if arguments turn into variables or not during compilation - * - * @return a {@link CompilerResult} object - */ - public static CompilerResult compileToDocument(GraphQLSchema schema, - OperationDefinition.Operation operationKind, - @Nullable String operationName, - List topLevelFields, - @Nullable VariablePredicate variablePredicate) { - return compileToDocument(schema, operationKind, operationName, topLevelFields, LinkedHashMapFactory.of(), variablePredicate); - } - - /** - * This will compile an operation text {@link Document} with possibly variables from the given {@link ExecutableNormalizedField}s - *

- * The {@link VariablePredicate} is used called to decide if the given argument values should be made into a variable - * OR inlined into the operation text as a graphql literal. - * - * @param schema the graphql schema to use - * @param operationKind the kind of operation - * @param operationName the name of the operation to use - * @param topLevelFields the top level {@link ExecutableNormalizedField}s to start from - * @param normalizedFieldToQueryDirectives the map of normalized field to query directives - * @param variablePredicate the variable predicate that decides if arguments turn into variables or not during compilation - * - * @return a {@link CompilerResult} object - */ - public static CompilerResult compileToDocument(GraphQLSchema schema, - OperationDefinition.Operation operationKind, - @Nullable String operationName, - List topLevelFields, - Map normalizedFieldToQueryDirectives, - @Nullable VariablePredicate variablePredicate) { - return compileToDocument(schema, operationKind, operationName, topLevelFields, normalizedFieldToQueryDirectives, variablePredicate, false); - } - - - /** - * This will compile an operation text {@link Document} with possibly variables from the given {@link ExecutableNormalizedField}s, with support for the experimental @defer directive. - *

- * The {@link VariablePredicate} is used called to decide if the given argument values should be made into a variable - * OR inlined into the operation text as a graphql literal. - * - * @param schema the graphql schema to use - * @param operationKind the kind of operation - * @param operationName the name of the operation to use - * @param topLevelFields the top level {@link ExecutableNormalizedField}s to start from - * @param variablePredicate the variable predicate that decides if arguments turn into variables or not during compilation - * - * @return a {@link CompilerResult} object - * - * @see ExecutableNormalizedOperationToAstCompiler#compileToDocument(GraphQLSchema, OperationDefinition.Operation, String, List, VariablePredicate) - */ - @ExperimentalApi - public static CompilerResult compileToDocumentWithDeferSupport(GraphQLSchema schema, - OperationDefinition.Operation operationKind, - @Nullable String operationName, - List topLevelFields, - @Nullable VariablePredicate variablePredicate - ) { - return compileToDocumentWithDeferSupport(schema, operationKind, operationName, topLevelFields, LinkedHashMapFactory.of(), variablePredicate); - } - - /** - * This will compile an operation text {@link Document} with possibly variables from the given {@link ExecutableNormalizedField}s, with support for the experimental @defer directive. - *

- * The {@link VariablePredicate} is used called to decide if the given argument values should be made into a variable - * OR inlined into the operation text as a graphql literal. - * - * @param schema the graphql schema to use - * @param operationKind the kind of operation - * @param operationName the name of the operation to use - * @param topLevelFields the top level {@link ExecutableNormalizedField}s to start from - * @param normalizedFieldToQueryDirectives the map of normalized field to query directives - * @param variablePredicate the variable predicate that decides if arguments turn into variables or not during compilation - * - * @return a {@link CompilerResult} object - * - * @see ExecutableNormalizedOperationToAstCompiler#compileToDocument(GraphQLSchema, OperationDefinition.Operation, String, List, Map, VariablePredicate) - */ - @ExperimentalApi - public static CompilerResult compileToDocumentWithDeferSupport(GraphQLSchema schema, - OperationDefinition.Operation operationKind, - @Nullable String operationName, - List topLevelFields, - Map normalizedFieldToQueryDirectives, - @Nullable VariablePredicate variablePredicate - ) { - return compileToDocument(schema, operationKind, operationName, topLevelFields, normalizedFieldToQueryDirectives, variablePredicate, true); - } - - private static CompilerResult compileToDocument(GraphQLSchema schema, - OperationDefinition.Operation operationKind, - @Nullable String operationName, - List topLevelFields, - Map normalizedFieldToQueryDirectives, - @Nullable VariablePredicate variablePredicate, - boolean deferSupport) { - GraphQLObjectType operationType = Assert.assertNotNull(getOperationType(schema, operationKind), "operationType should not be null"); - - VariableAccumulator variableAccumulator = new VariableAccumulator(variablePredicate); - List> selections = subselectionsForNormalizedField(schema, operationType.getName(), topLevelFields, normalizedFieldToQueryDirectives, variableAccumulator, deferSupport); - SelectionSet selectionSet = new SelectionSet(selections); - - OperationDefinition.Builder definitionBuilder = OperationDefinition.newOperationDefinition() - .name(operationName) - .operation(operationKind) - .selectionSet(selectionSet); - - definitionBuilder.variableDefinitions(variableAccumulator.getVariableDefinitions()); - - return new CompilerResult( - Document.newDocument() - .definition(definitionBuilder.build()) - .build(), - variableAccumulator.getVariablesMap() - ); - } - - private static List> subselectionsForNormalizedField(GraphQLSchema schema, - String parentOutputType, - List executableNormalizedFields, - Map normalizedFieldToQueryDirectives, - VariableAccumulator variableAccumulator, - boolean deferSupport) { - if (deferSupport) { - return subselectionsForNormalizedFieldWithDeferSupport(schema, parentOutputType, executableNormalizedFields, normalizedFieldToQueryDirectives, variableAccumulator); - } else { - return subselectionsForNormalizedFieldNoDeferSupport(schema, parentOutputType, executableNormalizedFields, normalizedFieldToQueryDirectives, variableAccumulator); - } - } - - private static List> subselectionsForNormalizedFieldNoDeferSupport(GraphQLSchema schema, - String parentOutputType, - List executableNormalizedFields, - Map normalizedFieldToQueryDirectives, - VariableAccumulator variableAccumulator) { - ImmutableList.Builder> selections = ImmutableList.builder(); - - // All conditional fields go here instead of directly to selections, so they can be grouped together - // in the same inline fragment in the output - Map> fieldsByTypeCondition = new LinkedHashMap<>(); - - for (ExecutableNormalizedField nf : executableNormalizedFields) { - if (nf.isConditional(schema)) { - selectionForNormalizedField(schema, nf, normalizedFieldToQueryDirectives, variableAccumulator, false) - .forEach((objectTypeName, field) -> - fieldsByTypeCondition - .computeIfAbsent(objectTypeName, ignored -> new ArrayList<>()) - .add(field)); - } else { - selections.add(selectionForNormalizedField(schema, parentOutputType, nf, normalizedFieldToQueryDirectives, variableAccumulator, false)); - } - } - - fieldsByTypeCondition.forEach((objectTypeName, fields) -> { - TypeName typeName = newTypeName(objectTypeName).build(); - InlineFragment inlineFragment = newInlineFragment() - .typeCondition(typeName) - .selectionSet(selectionSet(fields)) - .build(); - selections.add(inlineFragment); - }); - - return selections.build(); - } - - - private static List> subselectionsForNormalizedFieldWithDeferSupport(GraphQLSchema schema, - String parentOutputType, - List executableNormalizedFields, - Map normalizedFieldToQueryDirectives, - VariableAccumulator variableAccumulator) { - ImmutableList.Builder> selections = ImmutableList.builder(); - - // All conditional and deferred fields go here instead of directly to selections, so they can be grouped together - // in the same inline fragment in the output - // - Map> fieldsByFragmentDetails = new LinkedHashMap<>(); - - for (ExecutableNormalizedField nf : executableNormalizedFields) { - LinkedHashSet deferredExecutions = nf.getDeferredExecutions(); - - if (nf.isConditional(schema)) { - selectionForNormalizedField(schema, nf, normalizedFieldToQueryDirectives, variableAccumulator, true) - .forEach((objectTypeName, field) -> { - if (deferredExecutions == null || deferredExecutions.isEmpty()) { - fieldsByFragmentDetails - .computeIfAbsent(new ExecutionFragmentDetails(objectTypeName, null), ignored -> new ArrayList<>()) - .add(field); - } else { - deferredExecutions.forEach(deferredExecution -> { - fieldsByFragmentDetails - .computeIfAbsent(new ExecutionFragmentDetails(objectTypeName, deferredExecution), ignored -> new ArrayList<>()) - .add(field); - }); - } - }); - - } else if (deferredExecutions != null && !deferredExecutions.isEmpty()) { - Field field = selectionForNormalizedField(schema, parentOutputType, nf, normalizedFieldToQueryDirectives, variableAccumulator, true); - - deferredExecutions.forEach(deferredExecution -> { - fieldsByFragmentDetails - .computeIfAbsent(new ExecutionFragmentDetails(null, deferredExecution), ignored -> new ArrayList<>()) - .add(field); - }); - } else { - selections.add(selectionForNormalizedField(schema, parentOutputType, nf, normalizedFieldToQueryDirectives, variableAccumulator, true)); - } - } - - fieldsByFragmentDetails.forEach((typeAndDeferPair, fields) -> { - InlineFragment.Builder fragmentBuilder = newInlineFragment() - .selectionSet(selectionSet(fields)); - - if (typeAndDeferPair.typeName != null) { - TypeName typeName = newTypeName(typeAndDeferPair.typeName).build(); - fragmentBuilder.typeCondition(typeName); - } - - if (typeAndDeferPair.deferredExecution != null) { - Directive.Builder deferBuilder = Directive.newDirective().name(Directives.DeferDirective.getName()); - - if (typeAndDeferPair.deferredExecution.getLabel() != null) { - deferBuilder.argument(newArgument().name("label").value(StringValue.of(typeAndDeferPair.deferredExecution.getLabel())).build()); - } - - fragmentBuilder.directive(deferBuilder.build()); - } - - - selections.add(fragmentBuilder.build()); - }); - - return selections.build(); - } - - /** - * @return Map of object type names to list of fields - */ - private static Map selectionForNormalizedField(GraphQLSchema schema, - ExecutableNormalizedField executableNormalizedField, - Map normalizedFieldToQueryDirectives, - VariableAccumulator variableAccumulator, - boolean deferSupport) { - Map groupedFields = new LinkedHashMap<>(); - - for (String objectTypeName : executableNormalizedField.getObjectTypeNames()) { - groupedFields.put(objectTypeName, selectionForNormalizedField(schema, objectTypeName, executableNormalizedField, normalizedFieldToQueryDirectives, variableAccumulator, deferSupport)); - } - - return groupedFields; - } - - /** - * @return Map of object type names to list of fields - */ - private static Field selectionForNormalizedField(GraphQLSchema schema, - String objectTypeName, - ExecutableNormalizedField executableNormalizedField, - Map normalizedFieldToQueryDirectives, - VariableAccumulator variableAccumulator, - boolean deferSupport) { - final List> subSelections; - if (executableNormalizedField.getChildren().isEmpty()) { - subSelections = emptyList(); - } else { - GraphQLFieldDefinition fieldDef = getFieldDefinition(schema, objectTypeName, executableNormalizedField); - GraphQLUnmodifiedType fieldOutputType = unwrapAll(fieldDef.getType()); - - subSelections = subselectionsForNormalizedField( - schema, - fieldOutputType.getName(), - executableNormalizedField.getChildren(), - normalizedFieldToQueryDirectives, - variableAccumulator, - deferSupport - ); - } - - SelectionSet selectionSet = selectionSetOrNullIfEmpty(subSelections); - List arguments = createArguments(executableNormalizedField, variableAccumulator); - - QueryDirectives queryDirectives = normalizedFieldToQueryDirectives.get(executableNormalizedField); - - Field.Builder builder = newField() - .name(executableNormalizedField.getFieldName()) - .alias(executableNormalizedField.getAlias()) - .selectionSet(selectionSet) - .arguments(arguments); - - List directives = buildDirectives(executableNormalizedField, queryDirectives, variableAccumulator); - return builder - .directives(directives) - .build(); - } - - private static List buildDirectives(ExecutableNormalizedField executableNormalizedField, @Nullable QueryDirectives queryDirectives, VariableAccumulator variableAccumulator) { - if (queryDirectives == null || queryDirectives.getImmediateAppliedDirectivesByField().isEmpty()) { - return emptyList(); - } - return queryDirectives.getImmediateAppliedDirectivesByField().entrySet().stream() - .flatMap(entry -> entry.getValue().stream()) - .map(queryAppliedDirective -> buildDirective(executableNormalizedField, queryDirectives, queryAppliedDirective, variableAccumulator)) - .collect(Collectors.toList()); - } - - private static Directive buildDirective(ExecutableNormalizedField executableNormalizedField, QueryDirectives queryDirectives, QueryAppliedDirective queryAppliedDirective, VariableAccumulator variableAccumulator) { - - List arguments = ArgumentMaker.createDirectiveArguments(executableNormalizedField, queryDirectives, queryAppliedDirective, variableAccumulator); - return Directive.newDirective() - .name(queryAppliedDirective.getName()) - .arguments(arguments).build(); - } - - @Nullable - private static SelectionSet selectionSetOrNullIfEmpty(List> selections) { - return selections.isEmpty() ? null : newSelectionSet().selections(selections).build(); - } - - private static SelectionSet selectionSet(List fields) { - return newSelectionSet().selections(fields).build(); - } - - - private static GraphQLFieldDefinition getFieldDefinition(GraphQLSchema schema, - String parentType, - ExecutableNormalizedField nf) { - return Introspection.getFieldDef(schema, (GraphQLCompositeType) Assert.assertNotNull(schema.getType(parentType), "type '%s' should not be null", parentType), nf.getName()); - } - - - @Nullable - private static GraphQLObjectType getOperationType(GraphQLSchema schema, - OperationDefinition.Operation operationKind) { - switch (operationKind) { - case QUERY: - return schema.getQueryType(); - case MUTATION: - return schema.getMutationType(); - case SUBSCRIPTION: - return schema.getSubscriptionType(); - } - - return Assert.assertShouldNeverHappen("Unknown operation kind " + operationKind); - } - - /** - * Represents important execution details that can be associated with a fragment. - */ - private static class ExecutionFragmentDetails { - private final @Nullable String typeName; - private final @Nullable NormalizedDeferredExecution deferredExecution; - - public ExecutionFragmentDetails(@Nullable String typeName, @Nullable NormalizedDeferredExecution deferredExecution) { - this.typeName = typeName; - this.deferredExecution = deferredExecution; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ExecutionFragmentDetails that = (ExecutionFragmentDetails) o; - return Objects.equals(typeName, that.typeName) && Objects.equals(deferredExecution, that.deferredExecution); - } - - @Override - public int hashCode() { - return Objects.hash(typeName, deferredExecution); - } - } -} diff --git a/src/main/java/graphql/normalized/NormalizedDocument.java b/src/main/java/graphql/normalized/NormalizedDocument.java new file mode 100644 index 0000000000..55be916508 --- /dev/null +++ b/src/main/java/graphql/normalized/NormalizedDocument.java @@ -0,0 +1,111 @@ +package graphql.normalized; + +import graphql.PublicApi; +import graphql.language.Document; +import graphql.language.Field; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.NullUnmarked; + +import java.io.Serializable; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; + +import static graphql.Assert.assertNotNull; + +/** + * An immutable, variable-independent selection graph produced during validation. + * IDs index {@link #getSelectionSets()}; named fragment bodies are stored once. + * This object is valid only for the document and schema against which it was validated. + * It contains no coerced arguments or execution-specific state. + */ +@PublicApi +@NullMarked +public final class NormalizedDocument implements Serializable { + + /** + * Boolean GraphQLContext key enabling construction during validation. Default: false. + * Preparsed document caches must distinguish enabled and disabled entries and retain this artifact. + */ + public static final String ENABLED = "graphql.normalizedDocument.enabled"; + + private final Document document; + private final List operations; + private final List selectionSets; + private final Map fields; + + private NormalizedDocument(Builder builder) { + this.document = assertNotNull(builder.document); + this.operations = List.copyOf(builder.operations); + this.selectionSets = List.copyOf(builder.selectionSets); + this.fields = Collections.unmodifiableMap(new LinkedHashMap<>(builder.fields)); + } + + /** @return the validated source document */ + public Document getDocument() { + return document; + } + + /** @return all operations in document order */ + public List getOperations() { + return operations; + } + + /** @return the shared selection sets indexed by ID */ + public List getSelectionSets() { + return selectionSets; + } + + /** @return stored fields indexed by their original AST nodes */ + public Map getFields() { + return fields; + } + + public static Builder newNormalizedDocument() { + return new Builder(); + } + + public NormalizedDocument transform(Consumer consumer) { + Builder builder = new Builder(); + builder.document = document; + builder.operations = operations; + builder.selectionSets = selectionSets; + builder.fields = fields; + consumer.accept(builder); + return builder.build(); + } + + @NullUnmarked + public static class Builder { + private Document document; + private List operations = List.of(); + private List selectionSets = List.of(); + private Map fields = Collections.emptyMap(); + + public Builder document(Document document) { + this.document = document; + return this; + } + + public Builder operations(List operations) { + this.operations = operations; + return this; + } + + public Builder selectionSets(List selectionSets) { + this.selectionSets = selectionSets; + return this; + } + + public Builder fields(Map fields) { + this.fields = fields; + return this; + } + + public NormalizedDocument build() { + return new NormalizedDocument(this); + } + } +} diff --git a/src/main/java/graphql/normalized/NormalizedField.java b/src/main/java/graphql/normalized/NormalizedField.java new file mode 100644 index 0000000000..e994631ad5 --- /dev/null +++ b/src/main/java/graphql/normalized/NormalizedField.java @@ -0,0 +1,84 @@ +package graphql.normalized; + +import graphql.PublicApi; +import graphql.language.Field; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.NullUnmarked; + +import java.util.function.Consumer; + +import static graphql.Assert.assertNotNull; + +/** + * One field AST node in the shared graph. Each reference to its fragment can + * contribute a logical occurrence without copying this node. + * Arguments and directives remain AST values; they are not coerced during validation. + */ +@PublicApi +@NullMarked +public final class NormalizedField implements NormalizedSelection { + + private final Field source; + private final String parentTypeName; + private final int selectionSetId; + + private NormalizedField(Builder builder) { + this.source = assertNotNull(builder.source); + this.parentTypeName = assertNotNull(builder.parentTypeName); + this.selectionSetId = builder.selectionSetId; + } + + /** @return the original field, including its alias, arguments, directives and location */ + public Field getSource() { + return source; + } + + /** @return the declared parent type at this AST location */ + public String getParentTypeName() { + return parentTypeName; + } + + /** @return the child selection set ID, or -1 for a leaf */ + public int getSelectionSetId() { + return selectionSetId; + } + + public static Builder newNormalizedField() { + return new Builder(); + } + + public NormalizedField transform(Consumer consumer) { + Builder builder = new Builder(); + builder.source = source; + builder.parentTypeName = parentTypeName; + builder.selectionSetId = selectionSetId; + consumer.accept(builder); + return builder.build(); + } + + @NullUnmarked + public static class Builder { + private Field source; + private String parentTypeName; + private int selectionSetId = -1; + + public Builder source(Field source) { + this.source = source; + return this; + } + + public Builder parentTypeName(String parentTypeName) { + this.parentTypeName = parentTypeName; + return this; + } + + public Builder selectionSetId(int selectionSetId) { + this.selectionSetId = selectionSetId; + return this; + } + + public NormalizedField build() { + return new NormalizedField(this); + } + } +} diff --git a/src/main/java/graphql/normalized/NormalizedFieldCollector.java b/src/main/java/graphql/normalized/NormalizedFieldCollector.java new file mode 100644 index 0000000000..8cf5163c41 --- /dev/null +++ b/src/main/java/graphql/normalized/NormalizedFieldCollector.java @@ -0,0 +1,103 @@ +package graphql.normalized; + +import graphql.Internal; +import graphql.execution.ExecutionContext; +import graphql.execution.conditional.ConditionalNodes; +import graphql.language.Field; +import graphql.schema.GraphQLCompositeType; +import graphql.schema.GraphQLObjectType; + +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Deque; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static graphql.Assert.assertNotNull; + +@Internal +public final class NormalizedFieldCollector { + private final NormalizedDocument document; + private final ExecutionContext context; + private final ConditionalNodes conditionalNodes = new ConditionalNodes(); + + public NormalizedFieldCollector(NormalizedDocument document, ExecutionContext context) { + this.document = document; + this.context = context; + } + + public List> collect(List parentFields, GraphQLObjectType objectType) { + Set roots = new LinkedHashSet<>(); + for (Field parent : parentFields) { + NormalizedField field = assertNotNull(document.getFields().get(parent), + () -> "Lookahead requires the AST used to create the NormalizedDocument"); + if (field.getSelectionSetId() >= 0) { + roots.add(field.getSelectionSetId()); + } + } + Map> groups = new LinkedHashMap<>(); + Set visitedFragments = new LinkedHashSet<>(); + for (int root : roots) { + collectSelectionSet(root, objectType, groups, visitedFragments); + } + List> result = new ArrayList<>(); + groups.values().forEach(fields -> result.add(List.copyOf(fields))); + return List.copyOf(result); + } + + private void collectSelectionSet(int root, GraphQLObjectType objectType, Map> groups, Set visitedFragments) { + Deque> frames = new ArrayDeque<>(); + frames.push(selections(root)); + while (!frames.isEmpty()) { + Iterator frame = frames.peek(); + if (!frame.hasNext()) { + frames.pop(); + continue; + } + collectSelection(frame.next(), objectType, groups, visitedFragments, frames); + } + } + + private void collectSelection(NormalizedSelection selection, GraphQLObjectType objectType, Map> groups, + Set visitedFragments, Deque> frames) { + if (!conditionalNodes.shouldInclude(selection.getSource(), context.getCoercedVariables().toMap(), context.getGraphQLSchema(), context.getGraphQLContext())) { + return; + } + if (selection instanceof NormalizedField field) { + groups.computeIfAbsent(field.getSource().getResultKey(), ignored -> new LinkedHashSet<>()).add(field.getSource()); + return; + } + NormalizedSelectionScope scope = (NormalizedSelectionScope) selection; + if (!matchesType(scope, objectType) || !includeFragment(scope, visitedFragments)) { + return; + } + frames.push(selections(scope.getSelectionSetId())); + } + + private boolean matchesType(NormalizedSelectionScope scope, GraphQLObjectType objectType) { + String condition = scope.getTypeCondition(); + if (condition == null || condition.equals(objectType.getName())) { + return true; + } + GraphQLCompositeType type = (GraphQLCompositeType) context.getGraphQLSchema().getType(condition); + return !(type instanceof GraphQLObjectType) && context.getGraphQLSchema().isPossibleType(type, objectType); + } + + private boolean includeFragment(NormalizedSelectionScope scope, Set visitedFragments) { + if (scope.getFragmentDefinition() == null) { + return true; + } + if (!conditionalNodes.shouldInclude(scope.getFragmentDefinition(), context.getCoercedVariables().toMap(), context.getGraphQLSchema(), context.getGraphQLContext())) { + return false; + } + return visitedFragments.add(scope.getSelectionSetId()); + } + + private Iterator selections(int id) { + return document.getSelectionSets().get(id).getSelections().iterator(); + } +} diff --git a/src/main/java/graphql/normalized/NormalizedOperation.java b/src/main/java/graphql/normalized/NormalizedOperation.java new file mode 100644 index 0000000000..709b65c90b --- /dev/null +++ b/src/main/java/graphql/normalized/NormalizedOperation.java @@ -0,0 +1,69 @@ +package graphql.normalized; + +import graphql.PublicApi; +import graphql.language.OperationDefinition; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.NullUnmarked; + +import java.io.Serializable; +import java.util.function.Consumer; + +import static graphql.Assert.assertNotNull; + +/** + * A validated operation and the root of its shared selection graph. + */ +@PublicApi +@NullMarked +public final class NormalizedOperation implements Serializable { + + private final OperationDefinition source; + private final int selectionSetId; + + private NormalizedOperation(Builder builder) { + this.source = assertNotNull(builder.source); + this.selectionSetId = builder.selectionSetId; + } + + /** @return the operation, including its variable definitions and directives */ + public OperationDefinition getSource() { + return source; + } + + /** @return the root selection set ID */ + public int getSelectionSetId() { + return selectionSetId; + } + + public static Builder newNormalizedOperation() { + return new Builder(); + } + + public NormalizedOperation transform(Consumer consumer) { + Builder builder = new Builder(); + builder.source = source; + builder.selectionSetId = selectionSetId; + consumer.accept(builder); + return builder.build(); + } + + @NullUnmarked + public static class Builder { + private OperationDefinition source; + private int selectionSetId; + + public Builder source(OperationDefinition source) { + this.source = source; + return this; + } + + public Builder selectionSetId(int selectionSetId) { + this.selectionSetId = selectionSetId; + return this; + } + + public NormalizedOperation build() { + return new NormalizedOperation(this); + } + } +} diff --git a/src/main/java/graphql/normalized/NormalizedSelection.java b/src/main/java/graphql/normalized/NormalizedSelection.java new file mode 100644 index 0000000000..8537be3436 --- /dev/null +++ b/src/main/java/graphql/normalized/NormalizedSelection.java @@ -0,0 +1,18 @@ +package graphql.normalized; + +import graphql.PublicApi; +import graphql.language.DirectivesContainer; +import org.jspecify.annotations.NullMarked; + +import java.io.Serializable; + +/** A stored field or fragment scope, with its unevaluated source directives. */ +@PublicApi +@NullMarked +public sealed interface NormalizedSelection extends Serializable permits NormalizedField, NormalizedSelectionScope { + /** @return the original AST node, including symbolic skip/include conditions */ + DirectivesContainer getSource(); + + /** @return the child selection set ID, or -1 for a leaf */ + int getSelectionSetId(); +} diff --git a/src/main/java/graphql/normalized/NormalizedSelectionScope.java b/src/main/java/graphql/normalized/NormalizedSelectionScope.java new file mode 100644 index 0000000000..a5765df445 --- /dev/null +++ b/src/main/java/graphql/normalized/NormalizedSelectionScope.java @@ -0,0 +1,100 @@ +package graphql.normalized; + +import graphql.PublicApi; +import graphql.language.DirectivesContainer; +import graphql.language.FragmentDefinition; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.NullUnmarked; +import org.jspecify.annotations.Nullable; + +import java.util.function.Consumer; + +import static graphql.Assert.assertNotNull; + +/** + * An inline fragment or a reference to a shared named fragment body. + * The source directives belong to this reference: two spreads of the same fragment + * can have different conditions. Enclosing scopes and this scope must all be included. + */ +@PublicApi +@NullMarked +public final class NormalizedSelectionScope implements NormalizedSelection { + + private final DirectivesContainer source; + private final @Nullable String typeCondition; + private final @Nullable FragmentDefinition fragmentDefinition; + private final int selectionSetId; + + private NormalizedSelectionScope(Builder builder) { + this.source = assertNotNull(builder.source); + this.typeCondition = builder.typeCondition; + this.fragmentDefinition = builder.fragmentDefinition; + this.selectionSetId = builder.selectionSetId; + } + + /** @return the original spread or inline fragment with its symbolic conditions */ + public DirectivesContainer getSource() { + return source; + } + + /** @return the required type, or null for an inline fragment without a type condition */ + public @Nullable String getTypeCondition() { + return typeCondition; + } + + /** @return the shared fragment definition, or null for an inline fragment */ + public @Nullable FragmentDefinition getFragmentDefinition() { + return fragmentDefinition; + } + + /** @return the referenced selection set ID */ + public int getSelectionSetId() { + return selectionSetId; + } + + public static Builder newNormalizedSelectionScope() { + return new Builder(); + } + + public NormalizedSelectionScope transform(Consumer consumer) { + Builder builder = new Builder(); + builder.source = source; + builder.typeCondition = typeCondition; + builder.fragmentDefinition = fragmentDefinition; + builder.selectionSetId = selectionSetId; + consumer.accept(builder); + return builder.build(); + } + + @NullUnmarked + public static class Builder { + private DirectivesContainer source; + private @Nullable String typeCondition; + private @Nullable FragmentDefinition fragmentDefinition; + private int selectionSetId; + + public Builder source(DirectivesContainer source) { + this.source = source; + return this; + } + + public Builder typeCondition(@Nullable String typeCondition) { + this.typeCondition = typeCondition; + return this; + } + + public Builder fragmentDefinition(@Nullable FragmentDefinition fragmentDefinition) { + this.fragmentDefinition = fragmentDefinition; + return this; + } + + public Builder selectionSetId(int selectionSetId) { + this.selectionSetId = selectionSetId; + return this; + } + + public NormalizedSelectionScope build() { + return new NormalizedSelectionScope(this); + } + } +} diff --git a/src/main/java/graphql/normalized/NormalizedSelectionSet.java b/src/main/java/graphql/normalized/NormalizedSelectionSet.java new file mode 100644 index 0000000000..f313c6221b --- /dev/null +++ b/src/main/java/graphql/normalized/NormalizedSelectionSet.java @@ -0,0 +1,55 @@ +package graphql.normalized; + +import graphql.PublicApi; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.NullUnmarked; + +import java.io.Serializable; +import java.util.List; +import java.util.function.Consumer; + +import static graphql.Assert.assertNotNull; + +/** + * An ordered selection set. Fragment references are retained instead of expanded. + */ +@PublicApi +@NullMarked +public final class NormalizedSelectionSet implements Serializable { + + private final List selections; + + private NormalizedSelectionSet(Builder builder) { + this.selections = List.copyOf(builder.selections); + } + + /** @return the fields and scopes in source order */ + public List getSelections() { + return selections; + } + + public static Builder newNormalizedSelectionSet() { + return new Builder(); + } + + public NormalizedSelectionSet transform(Consumer consumer) { + Builder builder = new Builder(); + builder.selections = selections; + consumer.accept(builder); + return builder.build(); + } + + @NullUnmarked + public static class Builder { + private List selections = List.of(); + + public Builder selections(List selections) { + this.selections = selections; + return this; + } + + public NormalizedSelectionSet build() { + return new NormalizedSelectionSet(this); + } + } +} diff --git a/src/main/java/graphql/normalized/ValueToVariableValueCompiler.java b/src/main/java/graphql/normalized/ValueToVariableValueCompiler.java deleted file mode 100644 index 87144dcc42..0000000000 --- a/src/main/java/graphql/normalized/ValueToVariableValueCompiler.java +++ /dev/null @@ -1,138 +0,0 @@ -package graphql.normalized; - -import graphql.AssertException; -import graphql.Internal; -import graphql.language.ArrayValue; -import graphql.language.BooleanValue; -import graphql.language.EnumValue; -import graphql.language.FloatValue; -import graphql.language.IntValue; -import graphql.language.NullValue; -import graphql.language.ObjectField; -import graphql.language.ObjectValue; -import graphql.language.StringValue; -import graphql.language.Value; -import graphql.language.VariableDefinition; -import graphql.language.VariableReference; -import graphql.parser.Parser; -import org.jspecify.annotations.NonNull; -import org.jspecify.annotations.Nullable; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import static java.util.stream.Collectors.toList; - -@Internal -public class ValueToVariableValueCompiler { - - static VariableValueWithDefinition normalizedInputValueToVariable(NormalizedInputValue normalizedInputValue, int queryVariableCount) { - Object variableValue = normalisedValueToVariableValue(normalizedInputValue); - String varName = getVarName(queryVariableCount); - return new VariableValueWithDefinition( - variableValue, - VariableDefinition.newVariableDefinition() - .name(varName) - .type(Parser.parseType(normalizedInputValue.getTypeName())) - .build(), - VariableReference.newVariableReference().name(varName).build()); - } - - @SuppressWarnings("unchecked") - @Nullable - static Object normalisedValueToVariableValue(Object maybeValue) { - Object variableValue; - if (maybeValue instanceof NormalizedInputValue) { - NormalizedInputValue normalizedInputValue = (NormalizedInputValue) maybeValue; - Object inputValue = normalizedInputValue.getValue(); - if (inputValue instanceof Value) { - variableValue = toVariableValue((Value) inputValue); - } else if (inputValue instanceof List) { - variableValue = normalisedValueToVariableValues((List) inputValue); - } else if (inputValue instanceof Map) { - variableValue = normalisedValueToVariableValues((Map) inputValue); - } else if (inputValue == null) { - variableValue = null; - } else { - throw new AssertException("Should never happen. Did not expect NormalizedInputValue.getValue() of type: " + maybeClass(inputValue)); - } - } else if (maybeValue instanceof Value) { - Value value = (Value) maybeValue; - variableValue = toVariableValue(value); - } else if (maybeValue instanceof List) { - variableValue = normalisedValueToVariableValues((List) maybeValue); - } else if (maybeValue instanceof Map) { - variableValue = normalisedValueToVariableValues((Map) maybeValue); - } else { - throw new AssertException("Should never happen. Did not expect type: " + maybeClass(maybeValue)); - } - return variableValue; - } - - private static List normalisedValueToVariableValues(List arrayValues) { - return arrayValues.stream() - .map(ValueToVariableValueCompiler::normalisedValueToVariableValue) - .collect(toList()); - } - - @NonNull - private static Map normalisedValueToVariableValues(Map objectMap) { - Map output = new LinkedHashMap<>(); - objectMap.forEach((k, v) -> { - Object value = normalisedValueToVariableValue(v); - output.put(k, value); - }); - return output; - } - - private static Map toVariableValue(ObjectValue objectValue) { - Map map = new LinkedHashMap<>(); - List objectFields = objectValue.getObjectFields(); - for (ObjectField objectField : objectFields) { - String objectFieldName = objectField.getName(); - Value objectFieldValue = objectField.getValue(); - map.put(objectFieldName, toVariableValue(objectFieldValue)); - } - return map; - } - - @NonNull - private static List toVariableValues(List arrayValues) { - // some values can be null (NullValue) and hence we can use Immutable Lists - return arrayValues.stream() - .map(ValueToVariableValueCompiler::toVariableValue) - .collect(toList()); - } - - @Nullable - private static Object toVariableValue(Value value) { - if (value instanceof ObjectValue) { - return toVariableValue((ObjectValue) value); - } else if (value instanceof ArrayValue) { - return toVariableValues(((ArrayValue) value).getValues()); - } else if (value instanceof StringValue) { - return ((StringValue) value).getValue(); - } else if (value instanceof FloatValue) { - return ((FloatValue) value).getValue(); - } else if (value instanceof IntValue) { - return ((IntValue) value).getValue(); - } else if (value instanceof BooleanValue) { - return ((BooleanValue) value).isValue(); - } else if (value instanceof EnumValue) { - return ((EnumValue) value).getName(); - } else if (value instanceof NullValue) { - return null; - } - throw new AssertException("Should never happen. Cannot handle node of type: " + maybeClass(value)); - } - - private static Object maybeClass(Object maybe) { - return maybe == null ? "null" : maybe.getClass(); - } - - private static String getVarName(int variableOrdinal) { - return "v" + variableOrdinal; - } - -} diff --git a/src/main/java/graphql/normalized/VariableAccumulator.java b/src/main/java/graphql/normalized/VariableAccumulator.java deleted file mode 100644 index 08b3db4eb4..0000000000 --- a/src/main/java/graphql/normalized/VariableAccumulator.java +++ /dev/null @@ -1,70 +0,0 @@ -package graphql.normalized; - -import graphql.Internal; -import graphql.execution.directives.QueryAppliedDirective; -import graphql.language.VariableDefinition; -import org.jspecify.annotations.Nullable; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static graphql.normalized.ValueToVariableValueCompiler.normalizedInputValueToVariable; - -/** - * This accumulator class decides on whether to create a variable for a query argument and if so it tracks what variables were made. - * The {@link ExecutableNormalizedOperationToAstCompiler} then uses all the variables when it compiles the final document. - */ -@Internal -public class VariableAccumulator { - - private final List valueWithDefinitions; - @Nullable - private final VariablePredicate variablePredicate; - - public VariableAccumulator(@Nullable VariablePredicate variablePredicate) { - this.variablePredicate = variablePredicate; - valueWithDefinitions = new ArrayList<>(); - } - - public boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, QueryAppliedDirective queryAppliedDirective, String argName, NormalizedInputValue normalizedInputValue) { - // when a variable is used on the argument to a query directive then the queryAppliedDirective will be nonnull. - // otherwise it must be a field argument - if (queryAppliedDirective != null) { - return variablePredicate != null && variablePredicate.shouldMakeVariable(executableNormalizedField, queryAppliedDirective, argName, normalizedInputValue); - } else { - return variablePredicate != null && variablePredicate.shouldMakeVariable(executableNormalizedField, argName, normalizedInputValue); - } - } - - public VariableValueWithDefinition accumulateVariable(NormalizedInputValue normalizedInputValue) { - VariableValueWithDefinition variableWithDefinition = normalizedInputValueToVariable(normalizedInputValue, getAccumulatedSize()); - valueWithDefinitions.add(variableWithDefinition); - return variableWithDefinition; - } - - public int getAccumulatedSize() { - return valueWithDefinitions.size(); - } - - /** - * @return the variable definitions that would go on the operation declaration - */ - public List getVariableDefinitions() { - return valueWithDefinitions.stream().map(VariableValueWithDefinition::getDefinition).collect(Collectors.toList()); - } - - /** - * @return the map of variable names to variable values - */ - public Map getVariablesMap() { - Map map = new LinkedHashMap<>(); - valueWithDefinitions.forEach(variableWithDefinition -> { - String name = variableWithDefinition.getDefinition().getName(); - map.put(name, variableWithDefinition.getValue()); - }); - return map; - } -} diff --git a/src/main/java/graphql/normalized/VariablePredicate.java b/src/main/java/graphql/normalized/VariablePredicate.java deleted file mode 100644 index 7bc7b891a6..0000000000 --- a/src/main/java/graphql/normalized/VariablePredicate.java +++ /dev/null @@ -1,44 +0,0 @@ -package graphql.normalized; - -import graphql.PublicSpi; -import graphql.execution.directives.QueryAppliedDirective; -import org.jspecify.annotations.NullMarked; - -/** - * This predicate indicates whether a variable should be made for this field argument OR whether it will be compiled - * into a graphql AST literal. - */ -@NullMarked -@PublicSpi -public interface VariablePredicate { - /** - * Return true if a variable should be made for this field argument - * - * @param executableNormalizedField the field in question - * @param argName the argument on the field - * @param normalizedInputValue the input value for that argument - * - * @return true if a variable should be made - */ - boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, - String argName, - NormalizedInputValue normalizedInputValue); - - /** - * Return true if a variable should be made for this query directive argument - * on the specified field - * - * @param executableNormalizedField the field in question - * @param queryAppliedDirective the query directive in question - * @param argName the argument on the directive - * @param normalizedInputValue the input value for that argument - * - * @return true if a variable should be made - */ - default boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, - QueryAppliedDirective queryAppliedDirective, - String argName, - NormalizedInputValue normalizedInputValue) { - return false; - } -} diff --git a/src/main/java/graphql/normalized/VariableValueWithDefinition.java b/src/main/java/graphql/normalized/VariableValueWithDefinition.java deleted file mode 100644 index 39950b8786..0000000000 --- a/src/main/java/graphql/normalized/VariableValueWithDefinition.java +++ /dev/null @@ -1,30 +0,0 @@ -package graphql.normalized; - -import graphql.Internal; -import graphql.language.VariableDefinition; -import graphql.language.VariableReference; - -@Internal -public class VariableValueWithDefinition { - private final Object value; - private final VariableDefinition definition; - private final VariableReference variableReference; - - public VariableValueWithDefinition(Object value, VariableDefinition definition, VariableReference variableReference) { - this.value = value; - this.definition = definition; - this.variableReference = variableReference; - } - - public Object getValue() { - return value; - } - - public VariableDefinition getDefinition() { - return definition; - } - - public VariableReference getVariableReference() { - return variableReference; - } -} diff --git a/src/main/java/graphql/normalized/incremental/NormalizedDeferredExecution.java b/src/main/java/graphql/normalized/incremental/NormalizedDeferredExecution.java deleted file mode 100644 index a9fbaa2e0f..0000000000 --- a/src/main/java/graphql/normalized/incremental/NormalizedDeferredExecution.java +++ /dev/null @@ -1,131 +0,0 @@ -package graphql.normalized.incremental; - -import graphql.ExperimentalApi; -import graphql.schema.GraphQLObjectType; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -import java.util.Set; - -/** - * Represents details about the defer execution that can be associated with a {@link graphql.normalized.ExecutableNormalizedField}. - * - * Taking this schema as an example: - *
- *     type Query { animal: Animal }
- *     interface Animal { name: String, age: Int }
- *     type Cat implements Animal { name: String, age: Int }
- *     type Dog implements Animal { name: String, age: Int }
- * 
- * - * An ENF can be associated with multiple `NormalizedDeferredExecution`s - * - * For example, this query: - *
- *     query MyQuery {
- *         animal {
- *             ... @defer {
- *                 name
- *             }
- *             ... @defer {
- *                 name
- *             }
- *         }
- *     }
- * 
- * - * Would result in one ENF (name) associated with 2 `NormalizedDeferredExecution` instances. This is relevant for the execution - * since the field would have to be included in 2 incremental payloads. (I know, there's some duplication here, but - * this is the current state of the spec. There are some discussions happening around de-duplicating data in scenarios - * like this, so this behaviour might change in the future). - * - * A `NormalizedDeferredExecution` may be associated with a list of possible types - * - * For example, this query: - *
- *     query MyQuery {
- *         animal {
- *             ... @defer {
- *                 name
- *             }
- *         }
- *     }
- * 
- * results in a `NormalizedDeferredExecution` with no label and possible types [Dog, Cat] - * - * A `NormalizedDeferredExecution` may be associated with specific types - * For example, this query: - *
- *     query MyQuery {
- *         animal {
- *             ... on Cat @defer {
- *                 name
- *             }
- *             ... on Dog {
- *                 name
- *             }
- *         }
- *     }
- * 
- * results in a single ENF (name) associated with a `NormalizedDeferredExecution` with only "Cat" as a possible type. This means - * that, at execution time, `name` should be deferred only if the return object is a "Cat" (but not a if it is a "Dog"). - * - * ENFs associated with the same instance of `NormalizedDeferredExecution` will be resolved in the same incremental response payload - * For example, take these queries: - * - *
- *     query Query1 {
- *         animal {
- *             ... @defer {
- *                 name
- *             }
- *             ... @defer {
- *                 age
- *             }
- *         }
- *     }
- *
- *     query Query2 {
- *         animal {
- *             ... @defer {
- *                 name
- *                 age
- *             }
- *         }
- *     }
- * 
- * - * In `Query1`, the ENFs name and age are associated with different instances of `NormalizedDeferredExecution`. This means that, - * during execution, `name` and `age` can be delivered at different times (if name is resolved faster, it will be - * delivered first, and vice-versa). - * In `Query2` the fields will share the same instance of `NormalizedDeferredExecution`. This ensures that, at execution time, the - * fields are guaranteed to be delivered together. In other words, execution should wait until the slowest field resolves - * and deliver both fields at the same time. - * - */ -@NullMarked -@ExperimentalApi -public class NormalizedDeferredExecution { - private final @Nullable String label; - private final Set possibleTypes; - - public NormalizedDeferredExecution(@Nullable String label, Set possibleTypes) { - this.label = label; - this.possibleTypes = possibleTypes; - } - - /** - * @return the label associated with this defer declaration - */ - @Nullable - public String getLabel() { - return label; - } - - /** - * @return the concrete object types that are associated with this defer execution - */ - public Set getPossibleTypes() { - return possibleTypes; - } -} diff --git a/src/main/java/graphql/normalized/nf/NormalizedDocument.java b/src/main/java/graphql/normalized/nf/NormalizedDocument.java deleted file mode 100644 index 3e94a7b063..0000000000 --- a/src/main/java/graphql/normalized/nf/NormalizedDocument.java +++ /dev/null @@ -1,49 +0,0 @@ -package graphql.normalized.nf; - -import graphql.Assert; -import graphql.ExperimentalApi; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -import java.util.List; -import java.util.Map; - -@NullMarked -@ExperimentalApi -public class NormalizedDocument { - - private final List normalizedOperations; - - public NormalizedDocument(List normalizedOperations) { - this.normalizedOperations = normalizedOperations; - } - - public List getNormalizedOperations() { - return normalizedOperations; - } - - public NormalizedOperation getSingleNormalizedOperation() { - Assert.assertTrue(normalizedOperations.size() == 1, "Expecting a single normalized operation"); - return normalizedOperations.get(0).getNormalizedOperation(); - } - - public static class NormalizedOperationWithAssumedSkipIncludeVariables { - - @Nullable Map assumedSkipIncludeVariables; - NormalizedOperation normalizedOperation; - - public NormalizedOperationWithAssumedSkipIncludeVariables(@Nullable Map assumedSkipIncludeVariables, NormalizedOperation normalizedOperation) { - this.assumedSkipIncludeVariables = assumedSkipIncludeVariables; - this.normalizedOperation = normalizedOperation; - } - - public @Nullable Map getAssumedSkipIncludeVariables() { - return assumedSkipIncludeVariables; - } - - public NormalizedOperation getNormalizedOperation() { - return normalizedOperation; - } - } -} - diff --git a/src/main/java/graphql/normalized/nf/NormalizedDocumentFactory.java b/src/main/java/graphql/normalized/nf/NormalizedDocumentFactory.java deleted file mode 100644 index 987eac749b..0000000000 --- a/src/main/java/graphql/normalized/nf/NormalizedDocumentFactory.java +++ /dev/null @@ -1,686 +0,0 @@ -package graphql.normalized.nf; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableListMultimap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import graphql.Assert; -import graphql.ExperimentalApi; -import graphql.GraphQLContext; -import graphql.collect.ImmutableKit; -import graphql.execution.AbortExecutionException; -import graphql.execution.MergedField; -import graphql.execution.conditional.ConditionalNodes; -import graphql.execution.directives.QueryDirectives; -import graphql.introspection.Introspection; -import graphql.language.Directive; -import graphql.language.Document; -import graphql.language.Field; -import graphql.language.FragmentDefinition; -import graphql.language.FragmentSpread; -import graphql.language.InlineFragment; -import graphql.language.NodeUtil; -import graphql.language.OperationDefinition; -import graphql.language.Selection; -import graphql.language.SelectionSet; -import graphql.schema.FieldCoordinates; -import graphql.schema.GraphQLCompositeType; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLInterfaceType; -import graphql.schema.GraphQLNamedOutputType; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLType; -import graphql.schema.GraphQLUnionType; -import graphql.schema.GraphQLUnmodifiedType; -import graphql.schema.impl.SchemaUtil; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import static graphql.Assert.assertNotNull; -import static graphql.Assert.assertShouldNeverHappen; -import static graphql.collect.ImmutableKit.map; -import static graphql.schema.GraphQLTypeUtil.unwrapAll; -import static graphql.util.FpKit.filterSet; -import static graphql.util.FpKit.groupingBy; -import static graphql.util.FpKit.intersection; -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; - -@NullMarked -@ExperimentalApi -public class NormalizedDocumentFactory { - - public static class Options { - - - private final GraphQLContext graphQLContext; - private final Locale locale; - private final int maxChildrenDepth; - private final int maxFieldsCount; - - private final boolean deferSupport; - - /** - * The default max fields count is 100,000. - * This is big enough for even very large queries, but - * can be changed via {#setDefaultOptions - */ - public static final int DEFAULT_MAX_FIELDS_COUNT = 100_000; - private static Options defaultOptions = new Options(GraphQLContext.getDefault(), - Locale.getDefault(), - Integer.MAX_VALUE, - DEFAULT_MAX_FIELDS_COUNT, - false); - - private Options(GraphQLContext graphQLContext, - Locale locale, - int maxChildrenDepth, - int maxFieldsCount, - boolean deferSupport) { - this.graphQLContext = graphQLContext; - this.locale = locale; - this.maxChildrenDepth = maxChildrenDepth; - this.deferSupport = deferSupport; - this.maxFieldsCount = maxFieldsCount; - } - - /** - * Sets new default Options used when creating instances of {@link NormalizedDocument}. - * - * @param options new default options - */ - public static void setDefaultOptions(Options options) { - defaultOptions = Assert.assertNotNull(options); - } - - - /** - * Returns the default options used when creating instances of {@link NormalizedDocument}. - * - * @return the default options - */ - public static Options defaultOptions() { - return defaultOptions; - } - - /** - * Locale to use when parsing the query. - *

- * e.g. can be passed to {@link graphql.schema.Coercing} for parsing. - * - * @param locale the locale to use - * - * @return new options object to use - */ - public Options locale(Locale locale) { - return new Options(this.graphQLContext, locale, this.maxChildrenDepth, this.maxFieldsCount, this.deferSupport); - } - - /** - * Context object to use when parsing the operation. - *

- * Can be used to intercept input values e.g. using {@link graphql.execution.values.InputInterceptor}. - * - * @param graphQLContext the context to use - * - * @return new options object to use - */ - public Options graphQLContext(GraphQLContext graphQLContext) { - return new Options(graphQLContext, this.locale, this.maxChildrenDepth, this.maxFieldsCount, this.deferSupport); - } - - /** - * Controls the maximum depth of the operation. Can be used to prevent - * against malicious operations. - * - * @param maxChildrenDepth the max depth - * - * @return new options object to use - */ - public Options maxChildrenDepth(int maxChildrenDepth) { - return new Options(this.graphQLContext, this.locale, maxChildrenDepth, this.maxFieldsCount, this.deferSupport); - } - - /** - * Controls the maximum number of ENFs created. Can be used to prevent - * against malicious operations. - * - * @param maxFieldsCount the max number of ENFs created - * - * @return new options object to use - */ - public Options maxFieldsCount(int maxFieldsCount) { - return new Options(this.graphQLContext, this.locale, this.maxChildrenDepth, maxFieldsCount, this.deferSupport); - } - - /** - * Controls whether defer execution is supported when creating instances of {@link NormalizedDocument}. - * - * @param deferSupport true to enable support for defer - * - * @return new options object to use - */ - @ExperimentalApi - public Options deferSupport(boolean deferSupport) { - return new Options(this.graphQLContext, this.locale, this.maxChildrenDepth, this.maxFieldsCount, deferSupport); - } - - /** - * @return context to use during operation parsing - * - * @see #graphQLContext(GraphQLContext) - */ - public GraphQLContext getGraphQLContext() { - return graphQLContext; - } - - /** - * @return locale to use during operation parsing - * - * @see #locale(Locale) - */ - public Locale getLocale() { - return locale; - } - - /** - * @return maximum children depth before aborting parsing - * - * @see #maxChildrenDepth(int) - */ - public int getMaxChildrenDepth() { - return maxChildrenDepth; - } - - public int getMaxFieldsCount() { - return maxFieldsCount; - } - - } - - private static final ConditionalNodes conditionalNodes = new ConditionalNodes(); - - private NormalizedDocumentFactory() { - - } - - public static NormalizedDocument createNormalizedDocument( - GraphQLSchema graphQLSchema, - Document document) { - return createNormalizedDocument( - graphQLSchema, - document, - Options.defaultOptions()); - } - - - public static NormalizedDocument createNormalizedDocument(GraphQLSchema graphQLSchema, - Document document, - Options options) { - return new NormalizedDocumentFactoryImpl( - graphQLSchema, - document, - options - ).createNormalizedQueryImpl(); - } - - - private static class NormalizedDocumentFactoryImpl { - private final GraphQLSchema graphQLSchema; - private final Document document; - private final Options options; - private final Map fragments; - - private final List possibleMergerList = new ArrayList<>(); - - private ImmutableListMultimap.Builder fieldToNormalizedField = ImmutableListMultimap.builder(); - private ImmutableMap.Builder normalizedFieldToMergedField = ImmutableMap.builder(); - private ImmutableMap.Builder normalizedFieldToQueryDirectives = ImmutableMap.builder(); - private ImmutableListMultimap.Builder coordinatesToNormalizedFields = ImmutableListMultimap.builder(); - - private int fieldCount = 0; - private int maxDepthSeen = 0; - - private final List rootEnfs = new ArrayList<>(); - - private final Set skipIncludeVariableNames = new LinkedHashSet<>(); - - private @Nullable Map assumedSkipIncludeVariableValues; - - private NormalizedDocumentFactoryImpl( - GraphQLSchema graphQLSchema, - Document document, - Options options - ) { - this.graphQLSchema = graphQLSchema; - this.document = document; - this.options = options; - this.fragments = NodeUtil.getFragmentsByName(document); - } - - /** - * Creates a new NormalizedDocument for the provided query - */ - private NormalizedDocument createNormalizedQueryImpl() { - List normalizedOperations = new ArrayList<>(); - for (OperationDefinition operationDefinition : document.getDefinitionsOfType(OperationDefinition.class)) { - - assumedSkipIncludeVariableValues = null; - skipIncludeVariableNames.clear(); - NormalizedOperation normalizedOperation = createNormalizedOperation(operationDefinition); - - if (skipIncludeVariableNames.size() == 0) { - normalizedOperations.add(new NormalizedDocument.NormalizedOperationWithAssumedSkipIncludeVariables(null, normalizedOperation)); - } else { - int combinations = (int) Math.pow(2, skipIncludeVariableNames.size()); - for (int i = 0; i < combinations; i++) { - assumedSkipIncludeVariableValues = new LinkedHashMap<>(); - int variableIndex = 0; - for (String variableName : skipIncludeVariableNames) { - assumedSkipIncludeVariableValues.put(variableName, (i & (1 << variableIndex++)) != 0); - } - NormalizedOperation operationWithAssumedVariables = createNormalizedOperation(operationDefinition); - normalizedOperations.add(new NormalizedDocument.NormalizedOperationWithAssumedSkipIncludeVariables(assumedSkipIncludeVariableValues, operationWithAssumedVariables)); - } - } - } - - return new NormalizedDocument( - normalizedOperations - ); - } - - private NormalizedOperation createNormalizedOperation(OperationDefinition operationDefinition) { - this.rootEnfs.clear(); - this.fieldCount = 0; - this.maxDepthSeen = 0; - this.possibleMergerList.clear(); - fieldToNormalizedField = ImmutableListMultimap.builder(); - normalizedFieldToMergedField = ImmutableMap.builder(); - normalizedFieldToQueryDirectives = ImmutableMap.builder(); - coordinatesToNormalizedFields = ImmutableListMultimap.builder(); - - buildNormalizedFieldsRecursively(null, operationDefinition, null, 0); - - for (PossibleMerger possibleMerger : possibleMergerList) { - List childrenWithSameResultKey = possibleMerger.parent.getChildrenWithSameResultKey(possibleMerger.resultKey); - NormalizedFieldsMerger.merge(possibleMerger.parent, childrenWithSameResultKey, graphQLSchema); - } - - NormalizedOperation normalizedOperation = new NormalizedOperation( - operationDefinition.getOperation(), - operationDefinition.getName(), - new ArrayList<>(rootEnfs), - fieldToNormalizedField.build(), - normalizedFieldToMergedField.build(), - normalizedFieldToQueryDirectives.build(), - coordinatesToNormalizedFields.build(), - fieldCount, - maxDepthSeen - ); - return normalizedOperation; - } - - - private void captureMergedField(NormalizedField enf, MergedField mergedFld) { -// // QueryDirectivesImpl is a lazy object and only computes itself when asked for -// QueryDirectives queryDirectives = new QueryDirectivesImpl(mergedFld, graphQLSchema, coercedVariableValues.toMap(), options.getGraphQLContext(), options.getLocale()); -// normalizedFieldToQueryDirectives.put(enf, queryDirectives); - normalizedFieldToMergedField.put(enf, mergedFld); - } - - private void buildNormalizedFieldsRecursively(@Nullable NormalizedField normalizedField, - @Nullable OperationDefinition operationDefinition, - @Nullable ImmutableList fieldAndAstParents, - int curLevel) { - if (this.maxDepthSeen < curLevel) { - this.maxDepthSeen = curLevel; - checkMaxDepthExceeded(curLevel); - } - Set possibleObjects; - List collectedFields; - - // special handling for the root selection Set - if (normalizedField == null) { - assertNotNull(operationDefinition, "Root fields require an operation definition"); - GraphQLObjectType rootType = SchemaUtil.getOperationRootType(graphQLSchema, operationDefinition); - possibleObjects = ImmutableSet.of(rootType); - collectedFields = new ArrayList<>(); - collectFromSelectionSet(operationDefinition.getSelectionSet(), collectedFields, rootType, possibleObjects); - } else { - List fieldDefs = normalizedField.getFieldDefinitions(graphQLSchema); - possibleObjects = resolvePossibleObjects(fieldDefs); - if (possibleObjects.isEmpty()) { - return; - } - collectedFields = new ArrayList<>(); - for (CollectedField fieldAndAstParent : assertNotNull(fieldAndAstParents, "Child fields require their collected AST fields")) { - if (fieldAndAstParent.field.getSelectionSet() == null) { - continue; - } - // the AST parent comes from the previous collect from selection set call - // and is the type to which the field belongs (the container type of the field) and output type - // of the field needs to be determined based on the field name - GraphQLFieldDefinition fieldDefinition = Introspection.getFieldDef(graphQLSchema, fieldAndAstParent.astTypeCondition, fieldAndAstParent.field.getName()); - // it must a composite type, because the field has a selection set - GraphQLCompositeType selectionSetType = (GraphQLCompositeType) unwrapAll(fieldDefinition.getType()); - this.collectFromSelectionSet(fieldAndAstParent.field.getSelectionSet(), - collectedFields, - selectionSetType, - possibleObjects - ); - } - } - - Map> fieldsByName = fieldsByResultKey(collectedFields); - ImmutableList.Builder resultNFs = ImmutableList.builder(); - ImmutableListMultimap.Builder normalizedFieldToAstFields = ImmutableListMultimap.builder(); - createNFs(resultNFs, fieldsByName, normalizedFieldToAstFields, curLevel + 1, normalizedField); - - ImmutableList nextLevelChildren = resultNFs.build(); - ImmutableListMultimap nextLevelNormalizedFieldToAstFields = normalizedFieldToAstFields.build(); - - for (NormalizedField childENF : nextLevelChildren) { - if (normalizedField == null) { - // all root ENFs don't have a parent, but are collected in the rootEnfs list - rootEnfs.add(childENF); - } else { - normalizedField.addChild(childENF); - } - ImmutableList childFieldAndAstParents = nextLevelNormalizedFieldToAstFields.get(childENF); - - MergedField mergedField = newMergedField(childFieldAndAstParents); - captureMergedField(childENF, mergedField); - - updateFieldToNFMap(childENF, childFieldAndAstParents); - updateCoordinatedToNFMap(childENF); - - // recursive call - buildNormalizedFieldsRecursively(childENF, - null, - childFieldAndAstParents, - curLevel + 1); - } - } - - private void checkMaxDepthExceeded(int depthSeen) { - if (depthSeen > this.options.getMaxChildrenDepth()) { - throw new AbortExecutionException("Maximum query depth exceeded. " + depthSeen + " > " + this.options.getMaxChildrenDepth()); - } - } - - private static MergedField newMergedField(ImmutableList fieldAndAstParents) { - return MergedField.newMergedField(map(fieldAndAstParents, fieldAndAstParent -> fieldAndAstParent.field)).build(); - } - - private void updateFieldToNFMap(NormalizedField NormalizedField, - ImmutableList mergedField) { - for (CollectedField astField : mergedField) { - fieldToNormalizedField.put(astField.field, NormalizedField); - } - } - - private void updateCoordinatedToNFMap(NormalizedField topLevel) { - for (String objectType : topLevel.getObjectTypeNames()) { - FieldCoordinates coordinates = FieldCoordinates.coordinates(objectType, topLevel.getFieldName()); - coordinatesToNormalizedFields.put(coordinates, topLevel); - } - } - - - private Map> fieldsByResultKey(List collectedFields) { - Map> fieldsByName = new LinkedHashMap<>(); - for (CollectedField collectedField : collectedFields) { - fieldsByName.computeIfAbsent(collectedField.field.getResultKey(), ignored -> new ArrayList<>()).add(collectedField); - } - return fieldsByName; - } - - - private void createNFs(ImmutableList.Builder nfListBuilder, - Map> fieldsByName, - ImmutableListMultimap.Builder normalizedFieldToAstFields, - int level, - @Nullable NormalizedField parent) { - for (String resultKey : fieldsByName.keySet()) { - List fieldsWithSameResultKey = fieldsByName.get(resultKey); - List commonParentsGroups = groupByCommonParents(fieldsWithSameResultKey); - for (CollectedFieldGroup fieldGroup : commonParentsGroups) { - NormalizedField nf = createNF(fieldGroup, level, parent); - if (nf == null) { - continue; - } - for (CollectedField collectedField : fieldGroup.fields) { - normalizedFieldToAstFields.put(nf, collectedField); - } - nfListBuilder.add(nf); - - } - if (commonParentsGroups.size() > 1) { - possibleMergerList.add(new PossibleMerger(assertNotNull(parent, "Fields with multiple concrete parent types require a parent"), resultKey)); - } - } - } - - // new single ENF - private NormalizedField createNF(CollectedFieldGroup collectedFieldGroup, - int level, - @Nullable NormalizedField parent) { - - this.fieldCount++; - if (this.fieldCount > this.options.getMaxFieldsCount()) { - throw new AbortExecutionException("Maximum field count exceeded. " + this.fieldCount + " > " + this.options.getMaxFieldsCount()); - } - Field field; - Set objectTypes = collectedFieldGroup.objectTypes; - field = collectedFieldGroup.fields.iterator().next().field; - List directives = collectedFieldGroup.fields.stream().flatMap(f -> f.field.getDirectives().stream()).collect(Collectors.toList()); - String fieldName = field.getName(); - ImmutableList objectTypeNames = map(objectTypes, GraphQLObjectType::getName); - return NormalizedField.newNormalizedField() - .alias(field.getAlias()) - .astArguments(field.getArguments()) - .astDirectives(directives) - .objectTypeNames(objectTypeNames) - .fieldName(fieldName) - .level(level) - .parent(parent) - .build(); - } - - - private List groupByCommonParents(Collection fields) { - ImmutableSet.Builder objectTypes = ImmutableSet.builder(); - for (CollectedField collectedField : fields) { - objectTypes.addAll(collectedField.objectTypes); - } - Set allRelevantObjects = objectTypes.build(); - Map> groupByAstParent = groupingBy(fields, fieldAndType -> fieldAndType.astTypeCondition); - if (groupByAstParent.size() == 1) { - return singletonList(new CollectedFieldGroup(ImmutableSet.copyOf(fields), allRelevantObjects)); - } - ImmutableList.Builder result = ImmutableList.builder(); - for (GraphQLObjectType objectType : allRelevantObjects) { - Set relevantFields = filterSet(fields, field -> field.objectTypes.contains(objectType)); - result.add(new CollectedFieldGroup(relevantFields, singleton(objectType))); - } - return result.build(); - } - - - private void collectFromSelectionSet(SelectionSet selectionSet, - List result, - GraphQLCompositeType astTypeCondition, - Set possibleObjects - ) { - for (Selection selection : selectionSet.getSelections()) { - if (selection instanceof Field) { - collectField(result, (Field) selection, possibleObjects, astTypeCondition); - } else if (selection instanceof InlineFragment) { - collectInlineFragment(result, (InlineFragment) selection, possibleObjects, astTypeCondition); - } else if (selection instanceof FragmentSpread) { - collectFragmentSpread(result, (FragmentSpread) selection, possibleObjects); - } - } - } - - private void collectFragmentSpread(List result, - FragmentSpread fragmentSpread, - Set possibleObjects - ) { -// if (!conditionalNodes.shouldInclude(fragmentSpread, -// this.coercedVariableValues.toMap(), -// this.graphQLSchema, -// this.options.graphQLContext)) { -// return; -// } - FragmentDefinition fragmentDefinition = assertNotNull(this.fragments.get(fragmentSpread.getName())); - -// if (!conditionalNodes.shouldInclude(fragmentDefinition, -// this.coercedVariableValues.toMap(), -// this.graphQLSchema, -// this.options.graphQLContext)) { -// return; -// } - GraphQLCompositeType newAstTypeCondition = (GraphQLCompositeType) assertNotNull(this.graphQLSchema.getType(fragmentDefinition.getTypeCondition().getName())); - Set newPossibleObjects = narrowDownPossibleObjects(possibleObjects, newAstTypeCondition); - collectFromSelectionSet(fragmentDefinition.getSelectionSet(), result, newAstTypeCondition, newPossibleObjects); - } - - private void collectInlineFragment(List result, - InlineFragment inlineFragment, - Set possibleObjects, - GraphQLCompositeType astTypeCondition - ) { -// if (!conditionalNodes.shouldInclude(inlineFragment, this.coercedVariableValues.toMap(), this.graphQLSchema, this.options.graphQLContext)) { -// return; -// } - Set newPossibleObjects = possibleObjects; - GraphQLCompositeType newAstTypeCondition = astTypeCondition; - - if (inlineFragment.getTypeCondition() != null) { - newAstTypeCondition = (GraphQLCompositeType) assertNotNull(this.graphQLSchema.getType(inlineFragment.getTypeCondition().getName()), "Inline fragment type must exist"); - newPossibleObjects = narrowDownPossibleObjects(possibleObjects, newAstTypeCondition); - - } - - - collectFromSelectionSet(inlineFragment.getSelectionSet(), result, newAstTypeCondition, newPossibleObjects); - } - - private void collectField(List result, - Field field, - Set possibleObjectTypes, - GraphQLCompositeType astTypeCondition - ) { - Boolean shouldInclude; - if (assumedSkipIncludeVariableValues == null) { - if ((shouldInclude = conditionalNodes.shouldIncludeWithoutVariables(field)) == null) { - - String skipVariableName = conditionalNodes.getSkipVariableName(field); - String includeVariableName = conditionalNodes.getIncludeVariableName(field); - if (skipVariableName != null) { - skipIncludeVariableNames.add(skipVariableName); - } - if (includeVariableName != null) { - skipIncludeVariableNames.add(includeVariableName); - } - } - if (shouldInclude != null && !shouldInclude) { - return; - } - } else { - if (!conditionalNodes.shouldInclude(field, (Map) assumedSkipIncludeVariableValues, graphQLSchema, null)) { - return; - } - } - // this means there is actually no possible type for this field, and we are done - if (possibleObjectTypes.isEmpty()) { - return; - } - result.add(new CollectedField(field, possibleObjectTypes, astTypeCondition)); - } - - private Set narrowDownPossibleObjects(Set currentOnes, - GraphQLCompositeType typeCondition) { - - ImmutableSet resolvedTypeCondition = resolvePossibleObjects(typeCondition); - if (currentOnes.isEmpty()) { - return resolvedTypeCondition; - } - - // Faster intersection, as either set often has a size of 1. - return intersection(currentOnes, resolvedTypeCondition); - } - - private ImmutableSet resolvePossibleObjects(List defs) { - ImmutableSet.Builder builder = ImmutableSet.builder(); - - for (GraphQLFieldDefinition def : defs) { - GraphQLUnmodifiedType outputType = unwrapAll(def.getType()); - if (outputType instanceof GraphQLCompositeType) { - builder.addAll(resolvePossibleObjects((GraphQLCompositeType) outputType)); - } - } - - return builder.build(); - } - - private ImmutableSet resolvePossibleObjects(GraphQLCompositeType type) { - if (type instanceof GraphQLObjectType) { - return ImmutableSet.of((GraphQLObjectType) type); - } else if (type instanceof GraphQLInterfaceType) { - return ImmutableSet.copyOf(graphQLSchema.getImplementations((GraphQLInterfaceType) type)); - } else if (type instanceof GraphQLUnionType) { - List unionTypes = ((GraphQLUnionType) type).getTypes(); - return ImmutableSet.copyOf(ImmutableKit.map(unionTypes, GraphQLObjectType.class::cast)); - } else { - return assertShouldNeverHappen(); - } - } - - private static class PossibleMerger { - NormalizedField parent; - String resultKey; - - public PossibleMerger(NormalizedField parent, String resultKey) { - this.parent = parent; - this.resultKey = resultKey; - } - } - - private static class CollectedField { - Field field; - Set objectTypes; - GraphQLCompositeType astTypeCondition; - - public CollectedField(Field field, Set objectTypes, GraphQLCompositeType astTypeCondition) { - this.field = field; - this.objectTypes = objectTypes; - this.astTypeCondition = astTypeCondition; - } - } - - private static class CollectedFieldGroup { - Set objectTypes; - Set fields; - - public CollectedFieldGroup(Set fields, Set objectTypes) { - this.fields = fields; - this.objectTypes = objectTypes; - } - } - } - -} diff --git a/src/main/java/graphql/normalized/nf/NormalizedField.java b/src/main/java/graphql/normalized/nf/NormalizedField.java deleted file mode 100644 index 9c25f5222b..0000000000 --- a/src/main/java/graphql/normalized/nf/NormalizedField.java +++ /dev/null @@ -1,682 +0,0 @@ -package graphql.normalized.nf; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import graphql.ExperimentalApi; -import graphql.Internal; -import graphql.Mutable; -import graphql.collect.ImmutableKit; -import graphql.introspection.Introspection; -import graphql.language.Argument; -import graphql.language.Directive; -import graphql.normalized.ExecutableNormalizedOperation; -import graphql.normalized.NormalizedInputValue; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLInterfaceType; -import graphql.schema.GraphQLNamedOutputType; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLOutputType; -import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLUnionType; -import graphql.util.FpKit; -import graphql.util.MutableRef; -import org.jspecify.annotations.NonNull; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.NullUnmarked; -import org.jspecify.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; - -import static graphql.Assert.assertNotNull; -import static graphql.Assert.assertTrue; -import static graphql.schema.GraphQLTypeUtil.simplePrint; -import static graphql.schema.GraphQLTypeUtil.unwrapAll; -import static java.util.stream.Collectors.joining; -import static java.util.stream.Collectors.toList; -import static java.util.stream.Collectors.toSet; - -/** - * An {@link NormalizedField} represents a field in an executable graphql operation. Its models what - * could be executed during a given operation. - *

- * This class is intentionally mutable for performance reasons since building immutable parent child - * objects is too expensive. - */ -@NullMarked -@ExperimentalApi -@Mutable -public class NormalizedField { - private final @Nullable String alias; - private final ImmutableMap normalizedArguments; - private final LinkedHashMap resolvedArguments; - private final ImmutableList astArguments; - private List astDirectives; - - // Mutable List on purpose: it is modified after creation - private final LinkedHashSet objectTypeNames; - private final ArrayList children; - private @Nullable NormalizedField parent; - - private final String fieldName; - private final int level; - - - private NormalizedField(Builder builder) { - this.alias = builder.alias; - this.resolvedArguments = builder.resolvedArguments; - this.normalizedArguments = builder.normalizedArguments; - this.astArguments = builder.astArguments; - this.objectTypeNames = builder.objectTypeNames; - this.fieldName = assertNotNull(builder.fieldName); - this.children = builder.children; - this.level = builder.level; - this.parent = builder.parent; - this.astDirectives = builder.astDirectives; - } - - /** - * Determines whether this {@link NormalizedField} needs a fragment to select the field. However, it considers the parent - * output type when determining whether it needs a fragment. - *

- * Consider the following schema - * - *

-     * interface Animal {
-     *     name: String
-     *     parent: Animal
-     * }
-     * type Cat implements Animal {
-     *     name: String
-     *     parent: Cat
-     * }
-     * type Dog implements Animal {
-     *     name: String
-     *     parent: Dog
-     *     isGoodBoy: Boolean
-     * }
-     * type Query {
-     *     animal: Animal
-     * }
-     * 
- *

- * and the following query - * - *

-     * {
-     *     animal {
-     *         parent {
-     *             name
-     *         }
-     *     }
-     * }
-     * 
- *

- * Then we would get the following {@link ExecutableNormalizedOperation} - * - *

-     * -Query.animal: Animal
-     * --[Cat, Dog].parent: Cat, Dog
-     * ---[Cat, Dog].name: String
-     * 
- *

- * If we simply checked the {@link #parent}'s {@link #getFieldDefinitions(GraphQLSchema)} that would - * point us to {@code Cat.parent} and {@code Dog.parent} whose output types would incorrectly answer - * our question whether this is conditional? - *

- * We MUST consider that the output type of the {@code parent} field is {@code Animal} and - * NOT {@code Cat} or {@code Dog} as their respective implementations would say. - * - * @param schema - the graphql schema in play - * @return true if the field is conditional - */ - public boolean isConditional(GraphQLSchema schema) { - if (parent == null) { - return false; - } - - for (GraphQLInterfaceType commonParentOutputInterface : parent.getInterfacesCommonToAllOutputTypes(schema)) { - List implementations = schema.getImplementations(commonParentOutputInterface); - // __typename - if (fieldName.equals(Introspection.TypeNameMetaFieldDef.getName()) && implementations.size() == objectTypeNames.size()) { - return false; - } - if (commonParentOutputInterface.getField(fieldName) == null) { - continue; - } - if (implementations.size() == objectTypeNames.size()) { - return false; - } - } - - // __typename is the only field in a union type that CAN be NOT conditional - GraphQLFieldDefinition parentFieldDef = parent.getOneFieldDefinition(schema); - if (unwrapAll(parentFieldDef.getType()) instanceof GraphQLUnionType) { - GraphQLUnionType parentOutputTypeAsUnion = (GraphQLUnionType) unwrapAll(parentFieldDef.getType()); - if (fieldName.equals(Introspection.TypeNameMetaFieldDef.getName()) && objectTypeNames.size() == parentOutputTypeAsUnion.getTypes().size()) { - return false; // Not conditional - } - } - - // This means there is no Union or Interface which could serve as unconditional parent - if (objectTypeNames.size() > 1) { - return true; // Conditional - } - if (parent.objectTypeNames.size() > 1) { - return true; - } - - GraphQLObjectType oneObjectType = (GraphQLObjectType) schema.getType(objectTypeNames.iterator().next()); - return unwrapAll(parentFieldDef.getType()) != oneObjectType; - } - - public boolean hasChildren() { - return children.size() > 0; - } - - public GraphQLOutputType getType(GraphQLSchema schema) { - List fieldDefinitions = getFieldDefinitions(schema); - Set fieldTypes = fieldDefinitions.stream().map(fd -> simplePrint(fd.getType())).collect(toSet()); - assertTrue(fieldTypes.size() == 1, "More than one type ... use getTypes"); - return fieldDefinitions.get(0).getType(); - } - - public List getTypes(GraphQLSchema schema) { - return ImmutableKit.map(getFieldDefinitions(schema), fd -> fd.getType()); - } - - public void forEachFieldDefinition(GraphQLSchema schema, Consumer consumer) { - var fieldDefinition = resolveIntrospectionField(schema, objectTypeNames, fieldName); - if (fieldDefinition != null) { - consumer.accept(fieldDefinition); - return; - } - - for (String objectTypeName : objectTypeNames) { - GraphQLObjectType type = (GraphQLObjectType) assertNotNull(schema.getType(objectTypeName)); - consumer.accept(assertNotNull(type.getField(fieldName), "No field %s found for type %s", fieldName, objectTypeName)); - } - } - - public List getFieldDefinitions(GraphQLSchema schema) { - ImmutableList.Builder builder = ImmutableList.builder(); - forEachFieldDefinition(schema, builder::add); - return builder.build(); - } - - /** - * This is NOT public as it is not recommended usage. - *

- * Internally there are cases where we know it is safe to use this, so this exists. - */ - private GraphQLFieldDefinition getOneFieldDefinition(GraphQLSchema schema) { - var fieldDefinition = resolveIntrospectionField(schema, objectTypeNames, fieldName); - if (fieldDefinition != null) { - return fieldDefinition; - } - - String objectTypeName = objectTypeNames.iterator().next(); - GraphQLObjectType type = (GraphQLObjectType) assertNotNull(schema.getType(objectTypeName)); - return assertNotNull(type.getField(fieldName), "No field %s found for type %s", fieldName, objectTypeName); - } - - private static @Nullable GraphQLFieldDefinition resolveIntrospectionField(GraphQLSchema schema, Set objectTypeNames, String fieldName) { - if (fieldName.equals(schema.getIntrospectionTypenameFieldDefinition().getName())) { - return schema.getIntrospectionTypenameFieldDefinition(); - } else if (objectTypeNames.size() == 1 && objectTypeNames.iterator().next().equals(schema.getQueryType().getName())) { - if (fieldName.equals(schema.getIntrospectionSchemaFieldDefinition().getName())) { - return schema.getIntrospectionSchemaFieldDefinition(); - } else if (fieldName.equals(schema.getIntrospectionTypeFieldDefinition().getName())) { - return schema.getIntrospectionTypeFieldDefinition(); - } - } - return null; - } - - @Internal - public void addObjectTypeNames(Collection objectTypeNames) { - this.objectTypeNames.addAll(objectTypeNames); - } - - @Internal - public void setObjectTypeNames(Collection objectTypeNames) { - this.objectTypeNames.clear(); - this.objectTypeNames.addAll(objectTypeNames); - } - - @Internal - public void addChild(NormalizedField normalizedField) { - this.children.add(normalizedField); - } - - @Internal - public void clearChildren() { - this.children.clear(); - } - - - /** - * All merged fields have the same name so this is the name of the {@link NormalizedField}. - *

- * WARNING: This is not always the key in the execution result, because of possible field aliases. - * - * @return the name of this {@link NormalizedField} - * @see #getResultKey() - * @see #getAlias() - */ - public String getName() { - return getFieldName(); - } - - /** - * @return the same value as {@link #getName()} - * @see #getResultKey() - * @see #getAlias() - */ - public String getFieldName() { - return fieldName; - } - - /** - * Returns the result key of this {@link NormalizedField} within the overall result. - * This is either a field alias or the value of {@link #getName()} - * - * @return the result key for this {@link NormalizedField}. - * @see #getName() - */ - public String getResultKey() { - if (alias != null) { - return alias; - } - return getName(); - } - - /** - * @return the field alias used or null if there is none - * @see #getResultKey() - * @see #getName() - */ - public @Nullable String getAlias() { - return alias; - } - - /** - * @return a list of the {@link Argument}s on the field - */ - public ImmutableList getAstArguments() { - return astArguments; - } - - public List getAstDirectives() { - return astDirectives; - } - - public void setAstDirectives(List astDirectives) { - this.astDirectives = astDirectives; - } - - - /** - * Returns an argument value as a {@link NormalizedInputValue} which contains its type name and its current value - * - * @param name the name of the argument - * @return an argument value - */ - public @Nullable NormalizedInputValue getNormalizedArgument(String name) { - return normalizedArguments.get(name); - } - - /** - * @return a map of all the arguments in {@link NormalizedInputValue} form - */ - public ImmutableMap getNormalizedArguments() { - return normalizedArguments; - } - - /** - * @return a map of the resolved argument values - */ - public LinkedHashMap getResolvedArguments() { - return resolvedArguments; - } - - - /** - * A {@link NormalizedField} can sometimes (for non-concrete types like interfaces and unions) - * have more than one object type it could be when executed. There is no way to know what it will be until - * the field is executed over data and the type is resolved via a {@link graphql.schema.TypeResolver}. - *

- * This method returns all the possible types a field can be which is one or more {@link GraphQLObjectType} - * names. - *

- * Warning: This returns a Mutable Set. No defensive copy is made for performance reasons. - * - * @return a set of the possible type names this field could be. - */ - public Set getObjectTypeNames() { - return objectTypeNames; - } - - - /** - * This returns the first entry in {@link #getObjectTypeNames()}. Sometimes you know a field cant be more than one - * type and this method is a shortcut one to help you. - * - * @return the first entry from - */ - public String getSingleObjectTypeName() { - return objectTypeNames.iterator().next(); - } - - /** - * @return a helper method show field details - */ - public String printDetails() { - StringBuilder result = new StringBuilder(); - if (getAlias() != null) { - result.append(getAlias()).append(": "); - } - return result + objectTypeNamesToString() + "." + fieldName; - } - - /** - * @return a helper method to show the object types names as a string - */ - public String objectTypeNamesToString() { - if (objectTypeNames.size() == 1) { - return objectTypeNames.iterator().next(); - } else { - return objectTypeNames.toString(); - } - } - - /** - * This returns the list of the result keys (see {@link #getResultKey()} that lead from this field upwards to - * its parent field - * - * @return a list of the result keys from this {@link NormalizedField} to the top of the operation via parent fields - */ - public List getListOfResultKeys() { - LinkedList list = new LinkedList<>(); - NormalizedField current = this; - while (current != null) { - list.addFirst(current.getResultKey()); - current = current.parent; - } - return list; - } - - /** - * @return the children of the {@link NormalizedField} - */ - public List getChildren() { - return children; - } - - /** - * Returns the list of child fields that would have the same result key - * - * @param resultKey the result key to check - * @return a list of all direct {@link NormalizedField} children with the specified result key - */ - public List getChildrenWithSameResultKey(String resultKey) { - return FpKit.filterList(children, child -> child.getResultKey().equals(resultKey)); - } - - public List getChildren(int includingRelativeLevel) { - assertTrue(includingRelativeLevel >= 1, "relative level must be >= 1"); - List result = new ArrayList<>(); - - this.getChildren().forEach(child -> { - traverseImpl(child, result::add, 1, includingRelativeLevel); - }); - return result; - } - - /** - * This returns the child fields that can be used if the object is of the specified object type - * - * @param objectTypeName the object type - * @return a list of child fields that would apply to that object type - */ - public List getChildren(String objectTypeName) { - return children.stream() - .filter(cld -> cld.objectTypeNames.contains(objectTypeName)) - .collect(toList()); - } - - /** - * the level of the {@link NormalizedField} in the operation hierarchy with top level fields - * starting at 1 - * - * @return the level of the {@link NormalizedField} in the operation hierarchy - */ - public int getLevel() { - return level; - } - - /** - * @return the parent of this {@link NormalizedField} or null if it's a top level field - */ - public @Nullable NormalizedField getParent() { - return parent; - } - - - @Internal - public void replaceParent(@Nullable NormalizedField newParent) { - this.parent = newParent; - } - - - @Override - public String toString() { - return "NormalizedField{" + - objectTypeNamesToString() + "." + fieldName + - ", alias=" + alias + - ", level=" + level + - ", children=" + children.stream().map(NormalizedField::toString).collect(joining("\n")) + - '}'; - } - - - /** - * Traverse from this {@link NormalizedField} down into itself and all of its children - * - * @param consumer the callback for each {@link NormalizedField} in the hierarchy. - */ - public void traverseSubTree(Consumer consumer) { - this.getChildren().forEach(child -> { - traverseImpl(child, consumer, 1, Integer.MAX_VALUE); - }); - } - - private void traverseImpl(NormalizedField root, - Consumer consumer, - int curRelativeLevel, - int abortAfter) { - if (curRelativeLevel > abortAfter) { - return; - } - consumer.accept(root); - root.getChildren().forEach(child -> { - traverseImpl(child, consumer, curRelativeLevel + 1, abortAfter); - }); - } - - /** - * This tries to find interfaces common to all the field output types. - *

- * i.e. goes through {@link #getFieldDefinitions(GraphQLSchema)} and finds interfaces that - * all the field's unwrapped output types are assignable to. - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - private Set getInterfacesCommonToAllOutputTypes(GraphQLSchema schema) { - // Shortcut for performance - if (objectTypeNames.size() == 1) { - var fieldDef = getOneFieldDefinition(schema); - var outputType = unwrapAll(fieldDef.getType()); - - if (outputType instanceof GraphQLObjectType) { - return new LinkedHashSet<>((List) ((GraphQLObjectType) outputType).getInterfaces()); - } else if (outputType instanceof GraphQLInterfaceType) { - var result = new LinkedHashSet<>((List) ((GraphQLInterfaceType) outputType).getInterfaces()); - result.add(outputType); - return result; - } else { - return Collections.emptySet(); - } - } - - MutableRef> commonInterfaces = new MutableRef<>(); - forEachFieldDefinition(schema, (fieldDef) -> { - var outputType = unwrapAll(fieldDef.getType()); - - List outputTypeInterfaces; - if (outputType instanceof GraphQLObjectType) { - outputTypeInterfaces = (List) ((GraphQLObjectType) outputType).getInterfaces(); - } else if (outputType instanceof GraphQLInterfaceType) { - // This interface and superinterfaces - List superInterfaces = ((GraphQLInterfaceType) outputType).getInterfaces(); - - outputTypeInterfaces = new ArrayList<>(superInterfaces.size() + 1); - outputTypeInterfaces.add((GraphQLInterfaceType) outputType); - - if (!superInterfaces.isEmpty()) { - outputTypeInterfaces.addAll((List) superInterfaces); - } - } else { - outputTypeInterfaces = Collections.emptyList(); - } - - if (commonInterfaces.value == null) { - commonInterfaces.value = new LinkedHashSet<>(outputTypeInterfaces); - } else { - commonInterfaces.value.retainAll(outputTypeInterfaces); - } - }); - - return commonInterfaces.value; - } - - /** - * @return a {@link Builder} of {@link NormalizedField}s - */ - public static Builder newNormalizedField() { - return new Builder(); - } - - /** - * Allows this {@link NormalizedField} to be transformed via a {@link Builder} consumer callback - * - * @param builderConsumer the consumer given a builder - * @return a new transformed {@link NormalizedField} - */ - public NormalizedField transform(Consumer builderConsumer) { - Builder builder = new Builder(this); - builderConsumer.accept(builder); - return builder.build(); - } - - - @NullUnmarked - public static class Builder { - private LinkedHashSet objectTypeNames = new LinkedHashSet<>(); - private String fieldName; - private ArrayList children = new ArrayList<>(); - private int level; - private @Nullable NormalizedField parent; - private String alias; - private ImmutableMap normalizedArguments = ImmutableKit.emptyMap(); - private LinkedHashMap resolvedArguments = new LinkedHashMap<>(); - private ImmutableList astArguments = ImmutableKit.emptyList(); - private List astDirectives = Collections.emptyList(); - - - private Builder() { - } - - private Builder(NormalizedField existing) { - this.alias = existing.alias; - this.normalizedArguments = existing.normalizedArguments; - this.astArguments = existing.astArguments; - this.resolvedArguments = existing.resolvedArguments; - this.objectTypeNames = new LinkedHashSet<>(existing.getObjectTypeNames()); - this.fieldName = existing.getFieldName(); - this.children = new ArrayList<>(existing.children); - this.level = existing.getLevel(); - this.parent = existing.getParent(); - } - - public Builder clearObjectTypesNames() { - this.objectTypeNames.clear(); - return this; - } - - public Builder objectTypeNames(List objectTypeNames) { - this.objectTypeNames.addAll(objectTypeNames); - return this; - } - - public Builder alias(String alias) { - this.alias = alias; - return this; - } - - public Builder normalizedArguments(@Nullable Map arguments) { - this.normalizedArguments = arguments == null ? ImmutableKit.emptyMap() : ImmutableMap.copyOf(arguments); - return this; - } - - public Builder resolvedArguments(@Nullable Map arguments) { - this.resolvedArguments = arguments == null ? new LinkedHashMap<>() : new LinkedHashMap<>(arguments); - return this; - } - - public Builder astArguments(@NonNull List astArguments) { - this.astArguments = ImmutableList.copyOf(astArguments); - return this; - } - - public Builder astDirectives(@NonNull List astDirectives) { - this.astDirectives = astDirectives; - return this; - } - - - public Builder fieldName(String fieldName) { - this.fieldName = fieldName; - return this; - } - - - public Builder children(List children) { - this.children.clear(); - this.children.addAll(children); - return this; - } - - public Builder level(int level) { - this.level = level; - return this; - } - - public Builder parent(NormalizedField parent) { - this.parent = parent; - return this; - } - - - public NormalizedField build() { - return new NormalizedField(this); - } - } -} diff --git a/src/main/java/graphql/normalized/nf/NormalizedFieldsMerger.java b/src/main/java/graphql/normalized/nf/NormalizedFieldsMerger.java deleted file mode 100644 index fa61e36cea..0000000000 --- a/src/main/java/graphql/normalized/nf/NormalizedFieldsMerger.java +++ /dev/null @@ -1,195 +0,0 @@ -package graphql.normalized.nf; - -import graphql.Internal; -import graphql.introspection.Introspection; -import graphql.language.Argument; -import graphql.language.AstComparator; -import graphql.language.Directive; -import graphql.schema.GraphQLInterfaceType; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLSchema; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -@Internal -public class NormalizedFieldsMerger { - - public static void merge( - NormalizedField parent, - List childrenWithSameResultKey, - GraphQLSchema schema - ) { - // they have all the same result key - // we can only merge the fields if they have the same field name + arguments + all children are the same - List> possibleGroupsToMerge = new ArrayList<>(); - for (NormalizedField field : childrenWithSameResultKey) { - boolean addToGroup = false; - overPossibleGroups: - for (Set group : possibleGroupsToMerge) { - for (NormalizedField fieldInGroup : group) { - if (field.getFieldName().equals(Introspection.TypeNameMetaFieldDef.getName())) { - addToGroup = true; - group.add(field); - continue overPossibleGroups; - } - if (field.getFieldName().equals(fieldInGroup.getFieldName()) && - sameArguments(field.getAstArguments(), fieldInGroup.getAstArguments()) - && isFieldInSharedInterface(field, fieldInGroup, schema) - ) { - addToGroup = true; - group.add(field); - continue overPossibleGroups; - } - } - } - if (!addToGroup) { - LinkedHashSet group = new LinkedHashSet<>(); - group.add(field); - possibleGroupsToMerge.add(group); - } - } - for (Set groupOfFields : possibleGroupsToMerge) { - // for each group we check if it could be merged - List> listOfChildrenForGroup = new ArrayList<>(); - for (NormalizedField fieldInGroup : groupOfFields) { - Set childrenSets = new LinkedHashSet<>(fieldInGroup.getChildren()); - listOfChildrenForGroup.add(childrenSets); - } - boolean mergeable = areFieldSetsTheSame(listOfChildrenForGroup); - if (mergeable) { - Set mergedObjects = new LinkedHashSet<>(); - List mergedDirectives = new ArrayList<>(); - groupOfFields.forEach(f -> mergedObjects.addAll(f.getObjectTypeNames())); - groupOfFields.forEach(f -> mergedDirectives.addAll(f.getAstDirectives())); - // patching the first one to contain more objects, remove all others - Iterator iterator = groupOfFields.iterator(); - NormalizedField first = iterator.next(); - - while (iterator.hasNext()) { - NormalizedField next = iterator.next(); - parent.getChildren().remove(next); - } - first.setObjectTypeNames(mergedObjects); - first.setAstDirectives(mergedDirectives); - } - } - } - - private static boolean isFieldInSharedInterface(NormalizedField fieldOne, NormalizedField fieldTwo, GraphQLSchema schema) { - - /* - * we can get away with only checking one of the object names, because all object names in one ENF are guaranteed to be the same field. - * This comes from how the ENFs are created in the factory before. - */ - String firstObject = fieldOne.getSingleObjectTypeName(); - String secondObject = fieldTwo.getSingleObjectTypeName(); - // we know that the field names are the same, therefore we can just take the first one - String fieldName = fieldOne.getFieldName(); - - GraphQLObjectType objectTypeOne = schema.getObjectType(firstObject); - GraphQLObjectType objectTypeTwo = schema.getObjectType(secondObject); - List interfacesOne = (List) objectTypeOne.getInterfaces(); - List interfacesTwo = (List) objectTypeTwo.getInterfaces(); - - Optional firstInterfaceFound = interfacesOne.stream().filter(singleInterface -> singleInterface.getFieldDefinition(fieldName) != null).findFirst(); - Optional secondInterfaceFound = interfacesTwo.stream().filter(singleInterface -> singleInterface.getFieldDefinition(fieldName) != null).findFirst(); - if (!firstInterfaceFound.isPresent() || !secondInterfaceFound.isPresent()) { - return false; - } - return firstInterfaceFound.get().getName().equals(secondInterfaceFound.get().getName()); - } - - - private static boolean areFieldSetsTheSame(List> listOfSets) { - if (listOfSets.size() == 0 || listOfSets.size() == 1) { - return true; - } - Set first = listOfSets.get(0); - Iterator> iterator = listOfSets.iterator(); - iterator.next(); - while (iterator.hasNext()) { - Set set = iterator.next(); - if (!compareTwoFieldSets(first, set)) { - return false; - } - } - List> nextLevel = new ArrayList<>(); - for (Set set : listOfSets) { - for (NormalizedField fieldInSet : set) { - nextLevel.add(new LinkedHashSet<>(fieldInSet.getChildren())); - } - } - return areFieldSetsTheSame(nextLevel); - } - - private static boolean compareTwoFieldSets(Set setOne, Set setTwo) { - if (setOne.size() != setTwo.size()) { - return false; - } - for (NormalizedField field : setOne) { - if (!isContained(field, setTwo)) { - return false; - } - } - return true; - } - - private static boolean isContained(NormalizedField searchFor, Set set) { - for (NormalizedField field : set) { - if (compareWithoutChildren(searchFor, field)) { - return true; - } - } - return false; - } - - private static boolean compareWithoutChildren(NormalizedField one, NormalizedField two) { - - if (!one.getObjectTypeNames().equals(two.getObjectTypeNames())) { - return false; - } - if (!Objects.equals(one.getAlias(), two.getAlias())) { - return false; - } - if (!Objects.equals(one.getFieldName(), two.getFieldName())) { - return false; - } - if (!sameArguments(one.getAstArguments(), two.getAstArguments())) { - return false; - } - return true; - } - - // copied from graphql.validation.OperationValidator - private static boolean sameArguments(List arguments1, List arguments2) { - if (arguments1.size() != arguments2.size()) { - return false; - } - for (Argument argument : arguments1) { - Argument matchedArgument = findArgumentByName(argument.getName(), arguments2); - if (matchedArgument == null) { - return false; - } - if (!AstComparator.sameValue(argument.getValue(), matchedArgument.getValue())) { - return false; - } - } - return true; - } - - private static Argument findArgumentByName(String name, List arguments) { - for (Argument argument : arguments) { - if (argument.getName().equals(name)) { - return argument; - } - } - return null; - } - -} diff --git a/src/main/java/graphql/normalized/nf/NormalizedOperation.java b/src/main/java/graphql/normalized/nf/NormalizedOperation.java deleted file mode 100644 index b142fe78f1..0000000000 --- a/src/main/java/graphql/normalized/nf/NormalizedOperation.java +++ /dev/null @@ -1,183 +0,0 @@ -package graphql.normalized.nf; - -import com.google.common.collect.ImmutableListMultimap; -import graphql.Assert; -import graphql.ExperimentalApi; -import graphql.execution.MergedField; -import graphql.execution.ResultPath; -import graphql.execution.directives.QueryDirectives; -import graphql.language.Field; -import graphql.language.OperationDefinition; -import graphql.schema.FieldCoordinates; -import graphql.schema.GraphQLFieldsContainer; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -import java.util.List; -import java.util.Map; - -/** - * A {@link NormalizedOperation} represent how the text of a graphql operation (sometimes known colloquially as a query) - * will be executed at runtime according to the graphql specification. It handles complex mechanisms like merging - * duplicate fields into one and also detecting when the types of a given field may actually be for more than one possible object - * type. - *

- * An operation consists of a list of {@link NormalizedField}s in a parent child hierarchy - */ -@NullMarked -@ExperimentalApi -public class NormalizedOperation { - private final OperationDefinition.Operation operation; - private final @Nullable String operationName; - private final List rootFields; - private final ImmutableListMultimap fieldToNormalizedField; - private final Map normalizedFieldToMergedField; - private final Map normalizedFieldToQueryDirectives; - private final ImmutableListMultimap coordinatesToNormalizedFields; - private final int operationFieldCount; - private final int operationDepth; - - public NormalizedOperation( - OperationDefinition.Operation operation, - @Nullable String operationName, - List rootFields, - ImmutableListMultimap fieldToNormalizedField, - Map normalizedFieldToMergedField, - Map normalizedFieldToQueryDirectives, - ImmutableListMultimap coordinatesToNormalizedFields, - int operationFieldCount, - int operationDepth) { - this.operation = operation; - this.operationName = operationName; - this.rootFields = rootFields; - this.fieldToNormalizedField = fieldToNormalizedField; - this.normalizedFieldToMergedField = normalizedFieldToMergedField; - this.normalizedFieldToQueryDirectives = normalizedFieldToQueryDirectives; - this.coordinatesToNormalizedFields = coordinatesToNormalizedFields; - this.operationFieldCount = operationFieldCount; - this.operationDepth = operationDepth; - } - - /** - * @return operation AST being executed - */ - public OperationDefinition.Operation getOperation() { - return operation; - } - - /** - * @return the operation name, which can be null - */ - public @Nullable String getOperationName() { - return operationName; - } - - /** - * @return This returns how many {@link NormalizedField}s are in the operation. - */ - public int getOperationFieldCount() { - return operationFieldCount; - } - - /** - * @return This returns the depth of the operation - */ - public int getOperationDepth() { - return operationDepth; - } - - /** - * This multimap shows how a given {@link NormalizedField} maps to a one or more field coordinate in the schema - * - * @return a multimap of fields to schema field coordinates - */ - public ImmutableListMultimap getCoordinatesToNormalizedFields() { - return coordinatesToNormalizedFields; - } - - /** - * @return a list of the top level {@link NormalizedField}s in this operation. - */ - public List getRootFields() { - return rootFields; - } - - /** - * This is a multimap and the size of it reflects all the normalized fields in the operation - * - * @return an immutable list multimap of {@link Field} to {@link NormalizedField} - */ - public ImmutableListMultimap getFieldToNormalizedField() { - return fieldToNormalizedField; - } - - /** - * Looks up one or more {@link NormalizedField}s given a {@link Field} AST element in the operation - * - * @param field the field to look up - * - * @return zero, one or more possible {@link NormalizedField}s that represent that field - */ - public List getNormalizedFields(Field field) { - return fieldToNormalizedField.get(field); - } - - /** - * @return a map of {@link NormalizedField} to {@link MergedField}s - */ - public Map getNormalizedFieldToMergedField() { - return normalizedFieldToMergedField; - } - - /** - * Looks up the {@link MergedField} given a {@link NormalizedField} - * - * @param NormalizedField the field to use the key - * - * @return a {@link MergedField} or null if its not present - */ - public @Nullable MergedField getMergedField(NormalizedField NormalizedField) { - return normalizedFieldToMergedField.get(NormalizedField); - } - - /** - * @return a map of {@link NormalizedField} to its {@link QueryDirectives} - */ - public Map getNormalizedFieldToQueryDirectives() { - return normalizedFieldToQueryDirectives; - - } - - /** - * This looks up the {@link QueryDirectives} associated with the given {@link NormalizedField} - * - * @param NormalizedField the executable normalised field in question - * - * @return the fields query directives or null - */ - public @Nullable QueryDirectives getQueryDirectives(NormalizedField NormalizedField) { - return normalizedFieldToQueryDirectives.get(NormalizedField); - } - - /** - * This will find a {@link NormalizedField} given a merged field and a result path. If this does not find a field it will assert with an exception - * - * @param mergedField the merged field - * @param fieldsContainer the containing type of that field - * @param resultPath the result path in play - * - * @return the NormalizedField - */ - public NormalizedField getNormalizedField(MergedField mergedField, GraphQLFieldsContainer fieldsContainer, ResultPath resultPath) { - List NormalizedFields = fieldToNormalizedField.get(mergedField.getSingleField()); - List keysOnlyPath = resultPath.getKeysOnly(); - for (NormalizedField NormalizedField : NormalizedFields) { - if (NormalizedField.getListOfResultKeys().equals(keysOnlyPath)) { - if (NormalizedField.getObjectTypeNames().contains(fieldsContainer.getName())) { - return NormalizedField; - } - } - } - return Assert.assertShouldNeverHappen("normalized field not found"); - } -} diff --git a/src/main/java/graphql/normalized/nf/NormalizedOperationToAstCompiler.java b/src/main/java/graphql/normalized/nf/NormalizedOperationToAstCompiler.java deleted file mode 100644 index 454e56b1c5..0000000000 --- a/src/main/java/graphql/normalized/nf/NormalizedOperationToAstCompiler.java +++ /dev/null @@ -1,249 +0,0 @@ -package graphql.normalized.nf; - -import com.google.common.collect.ImmutableList; -import graphql.Assert; -import graphql.ExperimentalApi; -import graphql.introspection.Introspection; -import graphql.language.Argument; -import graphql.language.Directive; -import graphql.language.Document; -import graphql.language.Field; -import graphql.language.InlineFragment; -import graphql.language.OperationDefinition; -import graphql.language.Selection; -import graphql.language.SelectionSet; -import graphql.language.TypeName; -import graphql.schema.GraphQLCompositeType; -import graphql.schema.GraphQLFieldDefinition; -import graphql.schema.GraphQLObjectType; -import graphql.schema.GraphQLSchema; -import graphql.schema.GraphQLUnmodifiedType; -import org.jspecify.annotations.NullMarked; -import org.jspecify.annotations.Nullable; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import static graphql.Assert.assertNotNull; -import static graphql.collect.ImmutableKit.emptyList; -import static graphql.language.Field.newField; -import static graphql.language.InlineFragment.newInlineFragment; -import static graphql.language.SelectionSet.newSelectionSet; -import static graphql.language.TypeName.newTypeName; -import static graphql.schema.GraphQLTypeUtil.unwrapAll; - -/** - * This class can take a list of {@link NormalizedField}s and compiling out a - * normalised operation {@link Document} that would represent how those fields - * may be executed. - *

- * This is essentially the reverse of {@link NormalizedDocumentFactory} which takes - * operation text and makes {@link NormalizedField}s from it, this takes {@link NormalizedField}s - * and makes operation text from it. - *

- * You could for example send that operation text onto to some other graphql server if it - * has the same schema as the one provided. - */ -@NullMarked -@ExperimentalApi -public class NormalizedOperationToAstCompiler { - - /** - * The result is a {@link Document} and a map of variables - * that would go with that document. - */ - public static class CompilerResult { - private final Document document; - private final @Nullable Map variables; - - public CompilerResult(Document document, @Nullable Map variables) { - this.document = document; - this.variables = variables; - } - - public Document getDocument() { - return document; - } - - public @Nullable Map getVariables() { - return variables; - } - } - - public static CompilerResult compileToDocument(GraphQLSchema graphQLSchema, - GraphQLObjectType rootType, - List rootFields, - @Nullable String operationName, - OperationDefinition.Operation operationKind) { - - return compileToDocumentImpl(graphQLSchema, rootType, rootFields, operationName, operationKind); - } - - public static CompilerResult compileToDocument(GraphQLSchema graphQLSchema, - GraphQLObjectType rootType, - NormalizedField singleRootField, - @Nullable String operationName, - OperationDefinition.Operation operationKind) { - return compileToDocumentImpl(graphQLSchema, rootType, ImmutableList.of(singleRootField), operationName, operationKind); - - - } - - - public static CompilerResult compileToDocument(GraphQLSchema schema, - NormalizedOperation normalizedOperation) { - GraphQLObjectType operationType = getOperationType(schema, normalizedOperation.getOperation()); - - return compileToDocumentImpl( - schema, - operationType, - normalizedOperation.getRootFields(), - normalizedOperation.getOperationName(), - normalizedOperation.getOperation() - ); - } - - private static CompilerResult compileToDocumentImpl(GraphQLSchema schema, - GraphQLObjectType rootType, - List rootFields, - @Nullable String operationName, - OperationDefinition.Operation operationKind) { - - List> selections = subSelectionsForNormalizedFields(schema, rootType.getName(), rootFields); - SelectionSet selectionSet = new SelectionSet(selections); - - OperationDefinition.Builder definitionBuilder = OperationDefinition.newOperationDefinition() - .name(operationName) - .operation(operationKind) - .selectionSet(selectionSet); - -// definitionBuilder.variableDefinitions(variableAccumulator.getVariableDefinitions()); - - return new CompilerResult( - Document.newDocument() - .definition(definitionBuilder.build()) - .build(), - null - ); - } - - - private static List> subSelectionsForNormalizedFields(GraphQLSchema schema, - String parentOutputType, - List normalizedFields - ) { - ImmutableList.Builder> selections = ImmutableList.builder(); - - // All conditional fields go here instead of directly to selections, so they can be grouped together - // in the same inline fragment in the output - Map> fieldsByTypeCondition = new LinkedHashMap<>(); - - for (NormalizedField nf : normalizedFields) { - if (nf.isConditional(schema)) { - selectionForNormalizedField(schema, nf) - .forEach((objectTypeName, field) -> - fieldsByTypeCondition - .computeIfAbsent(objectTypeName, ignored -> new ArrayList<>()) - .add(field)); - } else { - selections.add(selectionForNormalizedField(schema, parentOutputType, nf)); - } - } - - fieldsByTypeCondition.forEach((objectTypeName, fields) -> { - TypeName typeName = newTypeName(objectTypeName).build(); - InlineFragment inlineFragment = newInlineFragment() - .typeCondition(typeName) - .selectionSet(selectionSet(fields)) - .build(); - selections.add(inlineFragment); - }); - - return selections.build(); - } - - /** - * @return Map of object type names to list of fields - */ - private static Map selectionForNormalizedField(GraphQLSchema schema, - NormalizedField normalizedField - ) { - Map groupedFields = new LinkedHashMap<>(); - - for (String objectTypeName : normalizedField.getObjectTypeNames()) { - groupedFields.put(objectTypeName, selectionForNormalizedField(schema, objectTypeName, normalizedField)); - } - - return groupedFields; - } - - /** - * @return Map of object type names to list of fields - */ - private static Field selectionForNormalizedField(GraphQLSchema schema, - String objectTypeName, - NormalizedField normalizedField) { - - final List> subSelections; - if (normalizedField.getChildren().isEmpty()) { - subSelections = emptyList(); - } else { - GraphQLFieldDefinition fieldDef = getFieldDefinition(schema, objectTypeName, normalizedField); - GraphQLUnmodifiedType fieldOutputType = unwrapAll(fieldDef.getType()); - - subSelections = subSelectionsForNormalizedFields( - schema, - fieldOutputType.getName(), - normalizedField.getChildren() - ); - } - - SelectionSet selectionSet = selectionSetOrNullIfEmpty(subSelections); -// List arguments = createArguments(executableNormalizedField, variableAccumulator); - List arguments = normalizedField.getAstArguments(); - List directives = normalizedField.getAstDirectives(); - - - Field.Builder builder = newField() - .name(normalizedField.getFieldName()) - .alias(normalizedField.getAlias()) - .selectionSet(selectionSet) - .directives(directives) - .arguments(arguments); - return builder.build(); - } - - @Nullable - private static SelectionSet selectionSetOrNullIfEmpty(List> selections) { - return selections.isEmpty() ? null : newSelectionSet().selections(selections).build(); - } - - private static SelectionSet selectionSet(List fields) { - return newSelectionSet().selections(fields).build(); - } - - - private static GraphQLFieldDefinition getFieldDefinition(GraphQLSchema schema, - String parentType, - NormalizedField nf) { - return Introspection.getFieldDef(schema, (GraphQLCompositeType) assertNotNull(schema.getType(parentType), "Parent type %s must exist", parentType), nf.getName()); - } - - - private static GraphQLObjectType getOperationType(GraphQLSchema schema, - OperationDefinition.Operation operationKind) { - switch (operationKind) { - case QUERY: - return schema.getQueryType(); - case MUTATION: - return assertNotNull(schema.getMutationType(), "Schema must define a mutation root"); - case SUBSCRIPTION: - return assertNotNull(schema.getSubscriptionType(), "Schema must define a subscription root"); - } - - return Assert.assertShouldNeverHappen("Unknown operation kind " + operationKind); - } - -} diff --git a/src/main/java/graphql/schema/DataFetchingFieldSelectionSet.java b/src/main/java/graphql/schema/DataFetchingFieldSelectionSet.java index 17deabfd4d..990b652cb0 100644 --- a/src/main/java/graphql/schema/DataFetchingFieldSelectionSet.java +++ b/src/main/java/graphql/schema/DataFetchingFieldSelectionSet.java @@ -10,6 +10,11 @@ * This class allows you to retrieve the selection set of fields that have been asked for when the * {@link DataFetcher} was invoked. *

+ * Inspection requires {@link graphql.normalized.NormalizedDocument#ENABLED} to be true in + * {@link graphql.GraphQLContext} before validation and the resulting graph to be retained + * in any preparsed cache. Otherwise inspection methods throw {@link IllegalStateException}. + * Creation is off by default; inspection does not build a missing graph. + *

* For example imagine we are fetching the field 'user' in the following query * *

@@ -59,7 +64,7 @@
  * 
  * {@code
  *  selectionSet.contains("name") == true
- *  selectionSet.contains("Dog.name", "Cat.name") == true
+ *  selectionSet.containsAllOf("Dog.name", "Cat.name") == true
  *
  *  List petNames = selectionSet.getFields("name")
  *  petNames.size() == 2
@@ -148,11 +153,11 @@ public interface DataFetchingFieldSelectionSet {
     /**
      * This will return all selected fields.
      * 

- * The fields are guaranteed to be in pre-order as they appear in the query. + * Fields are in preorder. At each level, concrete types are ordered by name; + * within each type, result keys follow their first active occurrence in the query. *

- * A selected field may have an alias - and hence is a unique field in the returned list. It may - * have the same field names as others in the list but when you also consider the alias then it is indeed unique - * because it would be another entry in the graphql result. + * Each entry represents one concrete parent type and result key. Different types can + * have separate entries with the same field name and alias. * * @return a list of all selected fields or empty list if none match */ @@ -162,11 +167,11 @@ public interface DataFetchingFieldSelectionSet { * This will return all selected fields that are immediate child fields * of the field being fetched. *

- * The fields are guaranteed to be in pre-order as they appear in the query. + * Fields are in preorder. At each level, concrete types are ordered by name; + * within each type, result keys follow their first active occurrence in the query. *

- * A selected field may have an alias - and hence is a unique field in the returned list. It may - * have the same field names as others in the list but when you also consider the alias then it is indeed unique - * because it would be another entry in the graphql result. + * Each entry represents one concrete parent type and result key. Different types can + * have separate entries with the same field name and alias. * * @return a list of all selected immediate child fields or empty list if none match */ @@ -179,11 +184,11 @@ public interface DataFetchingFieldSelectionSet { * This will allow you to use '*', '**' and '?' as special matching characters such that "invoice/customer*" would * match an invoice field with child fields that start with 'customer'. *

- * The fields are guaranteed to be in pre-order as they appear in the query. + * Fields are in preorder. At each level, concrete types are ordered by name; + * within each type, result keys follow their first active occurrence in the query. *

- * A selected field may have an alias - and hence is a unique field in the returned list. It may - * have the same field names as others in the list but when you also consider the alias then it is indeed unique - * because it would be another entry in the graphql result. + * Each entry represents one concrete parent type and result key. Different types can + * have separate entries with the same field name and alias. * * @param fieldGlobPattern the glob pattern to match fields against * @param fieldGlobPatterns optionally more glob pattern to match fields against @@ -195,8 +200,8 @@ public interface DataFetchingFieldSelectionSet { /** * The result key of a selected field represents what the graphql return value will be. The same {@link graphql.schema.GraphQLFieldDefinition} * may lead to a field being asked for multiple times (with differing arguments) if field aliases are used. This method - * helps you get all possible field invocations grouped by their result key. The arguments are guaranteed to be the same if - * the result key is the same, otherwise the query would not have validated correctly. + * helps you get all possible field invocations grouped by their result key. Entries on + * mutually exclusive concrete types can have different field names and arguments. * * @return a map of selected fields grouped by result key or an empty map if none match */ @@ -205,8 +210,8 @@ public interface DataFetchingFieldSelectionSet { /** * The result key of a selected field represents what the graphql return value will be. The same {@link graphql.schema.GraphQLFieldDefinition} * may lead to a field being asked for multiple times (with differing arguments) if field aliases are used. This method - * helps you get all possible field invocations grouped by their result key. The arguments are guaranteed to be the same if - * the result key is the same, otherwise the query would not have validated correctly. + * helps you get all possible field invocations grouped by their result key. Entries on + * mutually exclusive concrete types can have different field names and arguments. * * @param fieldGlobPattern the glob pattern to match fields against * @param fieldGlobPatterns optionally more glob pattern to match fields against diff --git a/src/main/java/graphql/schema/DataFetchingFieldSelectionSetImpl.java b/src/main/java/graphql/schema/DataFetchingFieldSelectionSetImpl.java index 4800a0dfcf..99865d1d8b 100644 --- a/src/main/java/graphql/schema/DataFetchingFieldSelectionSetImpl.java +++ b/src/main/java/graphql/schema/DataFetchingFieldSelectionSetImpl.java @@ -1,429 +1,196 @@ package graphql.schema; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; import graphql.Internal; -import graphql.collect.ImmutableKit; -import graphql.normalized.ExecutableNormalizedField; -import graphql.util.LockKit; +import graphql.execution.ExecutionContext; +import graphql.execution.MergedField; +import graphql.language.Field; +import graphql.normalized.NormalizedDocument; +import graphql.normalized.NormalizedFieldCollector; +import org.jspecify.annotations.Nullable; import java.io.File; import java.nio.file.FileSystems; -import java.nio.file.Path; import java.nio.file.PathMatcher; import java.nio.file.Paths; +import java.util.ArrayDeque; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; +import java.util.Comparator; +import java.util.Deque; import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import java.util.Objects; -import java.util.Set; import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.Stream; import static graphql.Assert.assertNotNull; -import static graphql.collect.ImmutableKit.emptyList; -import static graphql.util.FpKit.newList; +import static graphql.util.FpKit.interThreadMemoize; @Internal -public class DataFetchingFieldSelectionSetImpl implements DataFetchingFieldSelectionSet { +public final class DataFetchingFieldSelectionSetImpl implements DataFetchingFieldSelectionSet { + private final ExecutionContext context; + private final List parentFields; + private final GraphQLOutputType outputType; + private final int parentLevel; + private final @Nullable SelectedField parent; + private final String simplePrefix; + private final String typePrefix; + private final Supplier> immediateFields; + private final Supplier> allFields; - private final static String SEP = "/"; - private final static boolean UNIXY = SEP.equals(File.separator); - - private final static DataFetchingFieldSelectionSet NOOP = new DataFetchingFieldSelectionSet() { - - @Override - public boolean contains(String fieldGlobPattern) { - return false; - } - - @Override - public boolean containsAnyOf(String fieldGlobPattern, String... fieldGlobPatterns) { - return false; - } - - @Override - public boolean containsAllOf(String fieldGlobPattern, String... fieldGlobPatterns) { - return false; - } - - - @Override - public List getFields() { - return emptyList(); - } - - @Override - public List getImmediateFields() { - return emptyList(); - } - - @Override - public List getFields(String fieldGlobPattern, String... fieldGlobPatterns) { - return ImmutableKit.emptyList(); - } - - @Override - public Map> getFieldsGroupedByResultKey() { - return ImmutableKit.emptyMap(); - } - - @Override - public Map> getFieldsGroupedByResultKey(String fieldGlobPattern, String... fieldGlobPatterns) { - return ImmutableKit.emptyMap(); - } - }; - - public static DataFetchingFieldSelectionSet newCollector(GraphQLSchema schema, GraphQLOutputType fieldType, Supplier normalizedFieldSupplier) { - if (!GraphQLTypeUtil.isLeaf(fieldType)) { - return new DataFetchingFieldSelectionSetImpl(normalizedFieldSupplier, schema); - } else { - // we can only collect fields on object types and interfaces and unions. - return NOOP; + public static DataFetchingFieldSelectionSet newCollector(ExecutionContext context, MergedField field, GraphQLOutputType outputType, int parentLevel) { + if (!context.getGraphQLContext().getBoolean(NormalizedDocument.ENABLED) || context.getNormalizedDocument() == null) { + return UnavailableFieldSelectionSet.INSTANCE; } + return new DataFetchingFieldSelectionSetImpl(context, field.getFields(), outputType, parentLevel, null, "", ""); } - private final Supplier normalizedFieldSupplier; - - private final LockKit.ReentrantLock lock = new LockKit.ReentrantLock(); - private volatile boolean computedValues; - private volatile boolean computedImmediateValues; - - // we have multiple entries in this map so that we can do glob matching in multiple ways - // however it needs to be normalised back to a set of unique fields when give back out to - // the caller. - private Map> normalisedSelectionSetFields; - private List immediateFields; - private Set flattenedFieldsForGlobSearching; - private final GraphQLSchema schema; - - private DataFetchingFieldSelectionSetImpl(Supplier normalizedFieldSupplier, GraphQLSchema schema) { - this.schema = schema; - this.normalizedFieldSupplier = normalizedFieldSupplier; + public DataFetchingFieldSelectionSetImpl(ExecutionContext context, List parentFields, GraphQLOutputType outputType, + int parentLevel, @Nullable SelectedField parent, String simplePrefix, String typePrefix) { + this.context = context; + this.parentFields = List.copyOf(parentFields); + this.outputType = outputType; + this.parentLevel = parentLevel; + this.parent = parent; + this.simplePrefix = simplePrefix; + this.typePrefix = typePrefix; + this.immediateFields = interThreadMemoize(this::collectImmediateFields); + this.allFields = interThreadMemoize(this::collectAllFields); } - @Override - public boolean contains(String fieldGlobPattern) { - if (fieldGlobPattern == null || fieldGlobPattern.isEmpty()) { - return false; - } - computeValuesLazily(false); - fieldGlobPattern = removeLeadingSlash(fieldGlobPattern); - PathMatcher globMatcher = globMatcher(fieldGlobPattern); - for (String flattenedField : flattenedFieldsForGlobSearching) { - flattenedField = osAppropriate(flattenedField); - Path path = Paths.get(flattenedField); - if (globMatcher.matches(path)) { - return true; - } + private NormalizedDocument requireDocument() { + NormalizedDocument document = context.getNormalizedDocument(); + if (!context.getGraphQLContext().getBoolean(NormalizedDocument.ENABLED) || document == null) { + throw UnavailableFieldSelectionSet.unavailable(); } - return false; + return document; } - private String osAppropriate(String flattenedField) { - if (UNIXY) { - return flattenedField; - } else { - return flattenedField.replace(SEP, "\\"); + private List collectImmediateFields() { + NormalizedFieldCollector collector = new NormalizedFieldCollector(requireDocument(), context); + List types = possibleTypes(); + List fields = new ArrayList<>(); + for (GraphQLObjectType type : types) { + addFields(fields, collector.collect(parentFields, type), type, types.size() > 1); } + return List.copyOf(fields); } - @Override - public boolean containsAnyOf(String fieldGlobPattern, String... fieldGlobPatterns) { - assertNotNull(fieldGlobPattern); - assertNotNull(fieldGlobPatterns); - for (String globPattern : mkIterable(fieldGlobPattern, fieldGlobPatterns)) { - if (contains(globPattern)) { - return true; - } + private List possibleTypes() { + GraphQLType type = GraphQLTypeUtil.unwrapAll(outputType); + if (type instanceof GraphQLObjectType objectType) { + return List.of(objectType); } - return false; - } - - @Override - public boolean containsAllOf(String fieldGlobPattern, String... fieldGlobPatterns) { - assertNotNull(fieldGlobPattern); - assertNotNull(fieldGlobPatterns); - for (String globPattern : mkIterable(fieldGlobPattern, fieldGlobPatterns)) { - if (!contains(globPattern)) { - return false; - } + List types = new ArrayList<>(); + if (type instanceof GraphQLInterfaceType interfaceType) { + types.addAll(context.getGraphQLSchema().getImplementations(interfaceType)); + } else if (type instanceof GraphQLUnionType unionType) { + unionType.getTypes().forEach(member -> types.add((GraphQLObjectType) member)); } - return true; + types.sort(Comparator.comparing(GraphQLObjectType::getName)); + return types; } - @Override - public List getFields(String fieldGlobPattern, String... fieldGlobPatterns) { - if (fieldGlobPattern == null || fieldGlobPattern.isEmpty()) { - return emptyList(); + private void addFields(List result, List> groups, GraphQLObjectType objectType, boolean conditional) { + for (List fields : groups) { + result.add(new SelectedFieldImpl(context, fields, objectType, parentLevel + 1, conditional, parent, simplePrefix, typePrefix)); } - computeValuesLazily(false); - - List targetNames = new ArrayList<>(); - for (String flattenedField : flattenedFieldsForGlobSearching) { - for (String globPattern : mkIterable(fieldGlobPattern, fieldGlobPatterns)) { - PathMatcher globMatcher = globMatcher(globPattern); - Path path = Paths.get(flattenedField); - if (globMatcher.matches(path)) { - targetNames.add(flattenedField); - } - } - } - - return toSetSemanticsList(targetNames.stream() - .flatMap(name -> normalisedSelectionSetFields.getOrDefault(name, emptyList()).stream())); } - @Override - public List getFields() { - computeValuesLazily(false); - return toSetSemanticsList(normalisedSelectionSetFields.values().stream() - .flatMap(Collection::stream)); + private List collectAllFields() { + List result = new ArrayList<>(); + Deque pending = new ArrayDeque<>(); + pushReverse(pending, getImmediateFields()); + while (!pending.isEmpty()) { + SelectedFieldImpl field = (SelectedFieldImpl) pending.pop(); + result.add(field); + pushReverse(pending, field.getTraversalChildren()); + } + return List.copyOf(result); } - private List toSetSemanticsList(Stream stream) { - return ImmutableList.copyOf(stream - .collect(ImmutableSet.toImmutableSet())); + private void pushReverse(Deque pending, List fields) { + for (int index = fields.size() - 1; index >= 0; index--) { + pending.push(fields.get(index)); + } } @Override public List getImmediateFields() { - computeValuesLazily(true); - return immediateFields; + requireDocument(); + return immediateFields.get(); } @Override - public Map> getFieldsGroupedByResultKey() { - return getFields().stream().collect(Collectors.groupingBy(SelectedField::getResultKey)); + public List getFields() { + requireDocument(); + return allFields.get(); } @Override - public Map> getFieldsGroupedByResultKey(String fieldGlobPattern, String... fieldGlobPatterns) { - return getFields(fieldGlobPattern, fieldGlobPatterns).stream().collect(Collectors.groupingBy(SelectedField::getResultKey)); - } - - private void computeValuesLazily(boolean immediate) { - if (computedValues) { - return; + public List getFields(String pattern, String... patterns) { + requireDocument(); + if (pattern == null || pattern.isEmpty()) { + return List.of(); } - - // Avoid recomputing the immediate fields if they have already been computed. - if (immediate && computedImmediateValues) { - return; - } - - // this supplier is a once only thread synced call - so do it outside this lock - // if only to have only 1 lock in action at a time - ExecutableNormalizedField currentNormalisedField = normalizedFieldSupplier.get(); - - lock.runLocked(() -> { - if (computedValues) { - return; - } - - if (computedImmediateValues && immediate) { - return; - } - - flattenedFieldsForGlobSearching = new LinkedHashSet<>(); - normalisedSelectionSetFields = new LinkedHashMap<>(); - ImmutableList.Builder immediateFieldsBuilder = ImmutableList.builder(); - traverseSubSelectedFields(currentNormalisedField, immediateFieldsBuilder, "", "", true, immediate); - immediateFields = immediateFieldsBuilder.build(); - computedImmediateValues = true; - computedValues = !immediate; - }); + List matchers = patterns(pattern, patterns).stream().map(this::matcher).toList(); + return getFields().stream().filter(field -> matches(field, matchers)).toList(); } - private void traverseSubSelectedFields(ExecutableNormalizedField currentNormalisedField, ImmutableList.Builder immediateFieldsBuilder, String qualifiedFieldPrefix, String simpleFieldPrefix, boolean firstLevel, boolean immediate) { - List children = currentNormalisedField.getChildren(); - for (ExecutableNormalizedField normalizedSubSelectedField : children) { - String typeQualifiedName = mkTypeQualifiedName(normalizedSubSelectedField); - String simpleName = normalizedSubSelectedField.getName(); - - String globQualifiedName = mkFieldGlobName(qualifiedFieldPrefix, typeQualifiedName); - String globSimpleName = mkFieldGlobName(simpleFieldPrefix, simpleName); - - flattenedFieldsForGlobSearching.add(globQualifiedName); - // put in entries for the simple names - eg `Invoice.payments/Payment.amount` becomes `payments/amount` - flattenedFieldsForGlobSearching.add(globSimpleName); - - SelectedFieldImpl selectedField = new SelectedFieldImpl(globSimpleName, globQualifiedName, normalizedSubSelectedField, schema); - if (firstLevel) { - immediateFieldsBuilder.add(selectedField); - } - normalisedSelectionSetFields.computeIfAbsent(globQualifiedName, newList()).add(selectedField); - normalisedSelectionSetFields.computeIfAbsent(globSimpleName, newList()).add(selectedField); - - if (normalizedSubSelectedField.hasChildren() && !immediate) { - traverseSubSelectedFields(normalizedSubSelectedField, immediateFieldsBuilder, globQualifiedName, globSimpleName, false, false); + private boolean matches(SelectedField field, List matchers) { + for (PathMatcher matcher : matchers) { + if (matcher.matches(Paths.get(osPath(field.getQualifiedName()))) || matcher.matches(Paths.get(osPath(field.getFullyQualifiedName())))) { + return true; } } + return false; } - - private String removeLeadingSlash(String fieldGlobPattern) { - if (fieldGlobPattern.startsWith(SEP)) { - fieldGlobPattern = fieldGlobPattern.substring(1); - } - return fieldGlobPattern; + private String osPath(String path) { + return path.replace('/', File.separatorChar); } - private static String mkTypeQualifiedName(ExecutableNormalizedField executableNormalizedField) { - return executableNormalizedField.objectTypeNamesToString() + "." + executableNormalizedField.getName(); + private PathMatcher matcher(String pattern) { + return FileSystems.getDefault().getPathMatcher("glob:" + (pattern.startsWith("/") ? pattern.substring(1) : pattern)); } - private static String mkFieldGlobName(String fieldPrefix, String fieldName) { - return (!fieldPrefix.isEmpty() ? fieldPrefix + SEP : "") + fieldName; + private List patterns(String first, String[] rest) { + List patterns = new ArrayList<>(); + patterns.add(assertNotNull(first)); + Collections.addAll(patterns, assertNotNull(rest)); + return patterns; } - private static PathMatcher globMatcher(String fieldGlobPattern) { - return FileSystems.getDefault().getPathMatcher("glob:" + fieldGlobPattern); + @Override + public boolean contains(String pattern) { + return !getFields(pattern).isEmpty(); } - private List mkIterable(String fieldGlobPattern, String[] fieldGlobPatterns) { - List l = new ArrayList<>(); - l.add(fieldGlobPattern); - Collections.addAll(l, fieldGlobPatterns); - return l; + @Override + public boolean containsAnyOf(String pattern, String... patterns) { + requireDocument(); + return patterns(pattern, patterns).stream().anyMatch(this::contains); } @Override - public String toString() { - if (!computedValues) { - return "notComputed"; - } - return String.join("\n", flattenedFieldsForGlobSearching); + public boolean containsAllOf(String pattern, String... patterns) { + requireDocument(); + return patterns(pattern, patterns).stream().allMatch(this::contains); } - private static class SelectedFieldImpl implements SelectedField { - - private final String qualifiedName; - private final String fullyQualifiedName; - private final DataFetchingFieldSelectionSet selectionSet; - private final ExecutableNormalizedField executableNormalizedField; - private final GraphQLSchema schema; - - private SelectedFieldImpl(String simpleQualifiedName, String fullyQualifiedName, ExecutableNormalizedField executableNormalizedField, GraphQLSchema schema) { - this.schema = schema; - this.qualifiedName = simpleQualifiedName; - this.fullyQualifiedName = fullyQualifiedName; - this.executableNormalizedField = executableNormalizedField; - this.selectionSet = new DataFetchingFieldSelectionSetImpl(() -> executableNormalizedField, schema); - } - - private SelectedField mkParent(ExecutableNormalizedField executableNormalizedField) { - String parentSimpleQualifiedName = beforeLastSlash(qualifiedName); - String parentFullyQualifiedName = beforeLastSlash(fullyQualifiedName); - return executableNormalizedField.getParent() == null ? null : - new SelectedFieldImpl(parentSimpleQualifiedName, parentFullyQualifiedName, executableNormalizedField.getParent(), schema); - } - - private String beforeLastSlash(String name) { - int index = name.lastIndexOf("/"); - if (index > 0) { - return name.substring(0, index); - } - return ""; - } - - @Override - public String getName() { - return executableNormalizedField.getName(); - } - - @Override - public String getQualifiedName() { - return qualifiedName; - } - - @Override - public String getFullyQualifiedName() { - return fullyQualifiedName; - } - - @Override - public List getFieldDefinitions() { - return executableNormalizedField.getFieldDefinitions(schema); - } - - @Override - public GraphQLOutputType getType() { - return executableNormalizedField.getType(schema); - } - - @Override - public List getObjectTypes() { - return this.schema.getTypes(executableNormalizedField.getObjectTypeNames()); - } - - @Override - public List getObjectTypeNames() { - return ImmutableList.copyOf(executableNormalizedField.getObjectTypeNames()); - } - - @Override - public Map getArguments() { - return executableNormalizedField.getResolvedArguments(); - } - - @Override - public int getLevel() { - return executableNormalizedField.getLevel(); - } - - @Override - public boolean isConditional() { - return executableNormalizedField.isConditional(this.schema); - } - - @Override - public String getAlias() { - return executableNormalizedField.getAlias(); - } - - @Override - public String getResultKey() { - return executableNormalizedField.getResultKey(); - } - - @Override - public SelectedField getParentField() { - // lazy - return mkParent(executableNormalizedField); - } - - @Override - public DataFetchingFieldSelectionSet getSelectionSet() { - return selectionSet; - } - - // a selected field is the same as another selected field if it's the same ExecutableNF - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SelectedFieldImpl that = (SelectedFieldImpl) o; - return executableNormalizedField.equals(that.executableNormalizedField); - } + @Override + public Map> getFieldsGroupedByResultKey() { + return groupByResultKey(getFields()); + } - @Override - public int hashCode() { - return Objects.hash(executableNormalizedField); - } + @Override + public Map> getFieldsGroupedByResultKey(String pattern, String... patterns) { + return groupByResultKey(getFields(pattern, patterns)); + } - @Override - public String toString() { - return getFullyQualifiedName(); - } + private Map> groupByResultKey(List fields) { + Map> groups = new LinkedHashMap<>(); + fields.forEach(field -> groups.computeIfAbsent(field.getResultKey(), ignored -> new ArrayList<>()).add(field)); + groups.replaceAll((key, value) -> List.copyOf(value)); + return Collections.unmodifiableMap(groups); } } diff --git a/src/main/java/graphql/schema/SelectedField.java b/src/main/java/graphql/schema/SelectedField.java index b369dbd1fd..a3ce9a12b2 100644 --- a/src/main/java/graphql/schema/SelectedField.java +++ b/src/main/java/graphql/schema/SelectedField.java @@ -30,24 +30,24 @@ public interface SelectedField { /** * The selected field has a more complex type qualified name which is the path of field names to it - * as well as the object type of the parent. For example `[Invoice, Statement].payments/[Payment].amount` + * as well as the object type of the parent. For example `Invoice.payments/Payment.amount` * * @return the fully qualified name of the selected field */ String getFullyQualifiedName(); /** - * @return the object types of this SelectedField + * @return the singleton list containing this entry's concrete parent object type */ List getObjectTypes(); /** - * @return The list of all object types + * @return the singleton list containing this entry's concrete parent type name */ List getObjectTypeNames(); /** - * @return the field runtime definition + * @return the singleton list containing the concrete field definition */ List getFieldDefinitions(); @@ -57,7 +57,7 @@ public interface SelectedField { GraphQLOutputType getType(); /** - * @return a map of the arguments to this selected field + * @return the arguments resolved on demand with this concrete definition and execution variables */ Map getArguments(); @@ -67,7 +67,7 @@ public interface SelectedField { int getLevel(); /** - * @return whether the field is conditionally present. + * @return whether this entry is one of several possible concrete parent types at its level */ boolean isConditional(); @@ -84,8 +84,8 @@ public interface SelectedField { String getResultKey(); /** - * This will return the parent of the selected field OR null if there is no single parent, it that field - * was a top level field OR the parent was a non concrete field. + * Returns the parent within this lookahead view. Immediate fields in the data fetcher's + * view have no parent; descendants refer to their parent selected field. * * @return the fields selected parent or null if there is not one */ diff --git a/src/main/java/graphql/schema/SelectedFieldImpl.java b/src/main/java/graphql/schema/SelectedFieldImpl.java new file mode 100644 index 0000000000..6e5f9d9897 --- /dev/null +++ b/src/main/java/graphql/schema/SelectedFieldImpl.java @@ -0,0 +1,134 @@ +package graphql.schema; + +import graphql.Internal; +import graphql.execution.ExecutionContext; +import graphql.execution.ValuesResolver; +import graphql.introspection.Introspection; +import graphql.language.Field; +import org.jspecify.annotations.Nullable; + +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +import static graphql.util.FpKit.interThreadMemoize; + +@Internal +public final class SelectedFieldImpl implements SelectedField { + private final ExecutionContext context; + private final List fields; + private final GraphQLObjectType objectType; + private final GraphQLFieldDefinition definition; + private final int level; + private final boolean conditional; + private final @Nullable SelectedField parent; + private final String qualifiedName; + private final String fullyQualifiedName; + private final Supplier> arguments; + private final Supplier children; + private final Supplier> traversalChildren; + + public SelectedFieldImpl(ExecutionContext context, List fields, GraphQLObjectType objectType, int level, + boolean conditional, @Nullable SelectedField parent, String simplePrefix, String typePrefix) { + this.context = context; + this.fields = List.copyOf(fields); + this.objectType = objectType; + this.definition = Introspection.getFieldDef(context.getGraphQLSchema(), objectType, fields.get(0).getName()); + this.level = level; + this.conditional = conditional; + this.parent = parent; + this.qualifiedName = qualify(simplePrefix, getName()); + this.fullyQualifiedName = qualify(typePrefix, objectType.getName() + "." + getName()); + this.arguments = interThreadMemoize(() -> ValuesResolver.getArgumentValues(context.getGraphQLSchema().getCodeRegistry(), + definition.getArguments(), fields.get(0).getArguments(), context.getCoercedVariables(), context.getGraphQLContext(), context.getLocale())); + this.children = interThreadMemoize(() -> childSelectionSet("", "")); + this.traversalChildren = interThreadMemoize(() -> childSelectionSet(qualifiedName, fullyQualifiedName).getImmediateFields()); + } + + private String qualify(String prefix, String name) { + return prefix.isEmpty() ? name : prefix + "/" + name; + } + + private DataFetchingFieldSelectionSet childSelectionSet(String simplePrefix, String typePrefix) { + return new DataFetchingFieldSelectionSetImpl(context, fields, getType(), level, this, simplePrefix, typePrefix); + } + + public List getTraversalChildren() { + return traversalChildren.get(); + } + + @Override + public String getName() { + return fields.get(0).getName(); + } + + @Override + public String getQualifiedName() { + return qualifiedName; + } + + @Override + public String getFullyQualifiedName() { + return fullyQualifiedName; + } + + @Override + public List getObjectTypes() { + return List.of(objectType); + } + + @Override + public List getObjectTypeNames() { + return List.of(objectType.getName()); + } + + @Override + public List getFieldDefinitions() { + return List.of(definition); + } + + @Override + public GraphQLOutputType getType() { + return definition.getType(); + } + + @Override + public Map getArguments() { + return arguments.get(); + } + + @Override + public int getLevel() { + return level; + } + + @Override + public boolean isConditional() { + return conditional; + } + + @Override + public @Nullable String getAlias() { + return fields.get(0).getAlias(); + } + + @Override + public String getResultKey() { + return fields.get(0).getResultKey(); + } + + @Override + public @Nullable SelectedField getParentField() { + return parent; + } + + @Override + public DataFetchingFieldSelectionSet getSelectionSet() { + return children.get(); + } + + @Override + public String toString() { + return fullyQualifiedName; + } +} diff --git a/src/main/java/graphql/schema/UnavailableFieldSelectionSet.java b/src/main/java/graphql/schema/UnavailableFieldSelectionSet.java new file mode 100644 index 0000000000..0d34f9a184 --- /dev/null +++ b/src/main/java/graphql/schema/UnavailableFieldSelectionSet.java @@ -0,0 +1,58 @@ +package graphql.schema; + +import graphql.Internal; + +import java.util.List; +import java.util.Map; + +@Internal +public final class UnavailableFieldSelectionSet implements DataFetchingFieldSelectionSet { + public static final UnavailableFieldSelectionSet INSTANCE = new UnavailableFieldSelectionSet(); + + private UnavailableFieldSelectionSet() { + } + + public static IllegalStateException unavailable() { + return new IllegalStateException("Lookahead requires NormalizedDocument creation. Set NormalizedDocument.ENABLED to true in GraphQLContext before validation, and retain the NormalizedDocument in preparsed cache entries."); + } + + @Override + public boolean contains(String pattern) { + throw unavailable(); + } + + @Override + public boolean containsAnyOf(String pattern, String... patterns) { + throw unavailable(); + } + + @Override + public boolean containsAllOf(String pattern, String... patterns) { + throw unavailable(); + } + + @Override + public List getFields() { + throw unavailable(); + } + + @Override + public List getImmediateFields() { + throw unavailable(); + } + + @Override + public List getFields(String pattern, String... patterns) { + throw unavailable(); + } + + @Override + public Map> getFieldsGroupedByResultKey() { + throw unavailable(); + } + + @Override + public Map> getFieldsGroupedByResultKey(String pattern, String... patterns) { + throw unavailable(); + } +} diff --git a/src/main/java/graphql/validation/DocumentValidationResult.java b/src/main/java/graphql/validation/DocumentValidationResult.java new file mode 100644 index 0000000000..c929b4151e --- /dev/null +++ b/src/main/java/graphql/validation/DocumentValidationResult.java @@ -0,0 +1,16 @@ +package graphql.validation; + +import graphql.Internal; +import graphql.normalized.NormalizedDocument; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +import java.util.List; + +@Internal +@NullMarked +public record DocumentValidationResult(List errors, @Nullable NormalizedDocument normalizedDocument) { + public DocumentValidationResult { + errors = List.copyOf(errors); + } +} diff --git a/src/main/java/graphql/validation/NormalizedDocumentBuilder.java b/src/main/java/graphql/validation/NormalizedDocumentBuilder.java new file mode 100644 index 0000000000..b1222fe393 --- /dev/null +++ b/src/main/java/graphql/validation/NormalizedDocumentBuilder.java @@ -0,0 +1,99 @@ +package graphql.validation; + +import graphql.Internal; +import graphql.language.Document; +import graphql.language.Field; +import graphql.language.FragmentDefinition; +import graphql.language.FragmentSpread; +import graphql.language.InlineFragment; +import graphql.language.OperationDefinition; +import graphql.language.Selection; +import graphql.language.SelectionSet; +import graphql.normalized.NormalizedDocument; +import graphql.normalized.NormalizedField; +import graphql.normalized.NormalizedOperation; +import graphql.normalized.NormalizedSelection; +import graphql.normalized.NormalizedSelectionScope; +import graphql.normalized.NormalizedSelectionSet; +import graphql.schema.GraphQLCompositeType; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static graphql.Assert.assertNotNull; + +@Internal +public final class NormalizedDocumentBuilder { + private final ValidationContext context; + private final Map selectionSetIds = new LinkedHashMap<>(); + private final List selectionSets = new ArrayList<>(); + private final Map fields = new LinkedHashMap<>(); + + public NormalizedDocumentBuilder(ValidationContext context) { + this.context = context; + } + + public int selectionSet(SelectionSet selectionSet) { + Integer existing = selectionSetIds.get(selectionSet); + if (existing != null) { + return existing; + } + int id = selectionSets.size(); + selectionSetIds.put(selectionSet, id); + selectionSets.add(selectionSet); + return id; + } + + public void field(Field field, GraphQLCompositeType parentType) { + if (fields.containsKey(field)) { + return; + } + SelectionSet children = field.getSelectionSet(); + fields.put(field, NormalizedField.newNormalizedField() + .source(field) + .parentTypeName(parentType.getName()) + .selectionSetId(children == null ? -1 : selectionSet(children)) + .build()); + } + + public NormalizedDocument build() { + Document document = context.getDocument(); + List operations = new ArrayList<>(); + for (OperationDefinition operation : document.getDefinitionsOfType(OperationDefinition.class)) { + operations.add(NormalizedOperation.newNormalizedOperation().source(operation) + .selectionSetId(selectionSet(operation.getSelectionSet())).build()); + } + List result = new ArrayList<>(); + for (int index = 0; index < selectionSets.size(); index++) { + result.add(buildSelectionSet(selectionSets.get(index))); + } + return NormalizedDocument.newNormalizedDocument().document(document) + .operations(operations).selectionSets(result).fields(fields).build(); + } + + private NormalizedSelectionSet buildSelectionSet(SelectionSet selectionSet) { + List selections = new ArrayList<>(); + for (Selection selection : selectionSet.getSelections()) { + selections.add(buildSelection(selection)); + } + return NormalizedSelectionSet.newNormalizedSelectionSet().selections(selections).build(); + } + + private NormalizedSelection buildSelection(Selection selection) { + if (selection instanceof Field field) { + return assertNotNull(fields.get(field)); + } + if (selection instanceof InlineFragment inline) { + return NormalizedSelectionScope.newNormalizedSelectionScope().source(inline) + .typeCondition(inline.getTypeCondition() == null ? null : inline.getTypeCondition().getName()) + .selectionSetId(selectionSet(inline.getSelectionSet())).build(); + } + FragmentSpread spread = (FragmentSpread) selection; + FragmentDefinition fragment = assertNotNull(context.getFragment(spread.getName())); + return NormalizedSelectionScope.newNormalizedSelectionScope().source(spread) + .typeCondition(fragment.getTypeCondition().getName()).fragmentDefinition(fragment) + .selectionSetId(selectionSet(fragment.getSelectionSet())).build(); + } +} diff --git a/src/main/java/graphql/validation/OperationValidator.java b/src/main/java/graphql/validation/OperationValidator.java index 906db31a1c..beeb93bda5 100644 --- a/src/main/java/graphql/validation/OperationValidator.java +++ b/src/main/java/graphql/validation/OperationValidator.java @@ -13,8 +13,8 @@ import graphql.execution.TypeFromAST; import graphql.execution.ValuesResolver; import graphql.i18n.I18nMsg; -import graphql.introspection.Introspection; import graphql.introspection.Introspection.DirectiveLocation; +import graphql.introspection.Introspection; import graphql.language.Argument; import graphql.language.ArrayValue; import graphql.language.AstComparator; @@ -77,7 +77,6 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; - import java.util.List; import java.util.Locale; import java.util.Map; @@ -85,6 +84,7 @@ import java.util.Set; import java.util.function.Predicate; +import static graphql.language.OperationDefinition.Operation.SUBSCRIPTION; import static graphql.schema.GraphQLTypeUtil.isEnum; import static graphql.schema.GraphQLTypeUtil.isInput; import static graphql.schema.GraphQLTypeUtil.isLeaf; @@ -96,7 +96,6 @@ import static graphql.schema.GraphQLTypeUtil.simplePrint; import static graphql.schema.GraphQLTypeUtil.unwrapAll; import static graphql.schema.GraphQLTypeUtil.unwrapOne; - import static graphql.validation.ValidationError.newValidationError; import static graphql.validation.ValidationErrorType.BadValueForDefaultArg; import static graphql.validation.ValidationErrorType.DuplicateArgumentNames; @@ -118,12 +117,13 @@ import static graphql.validation.ValidationErrorType.NonExecutableDefinition; import static graphql.validation.ValidationErrorType.NonInputTypeOnVariable; import static graphql.validation.ValidationErrorType.NullValueForNonNullArgument; -import static graphql.validation.ValidationErrorType.SubselectionNotAllowed; -import static graphql.validation.ValidationErrorType.SubselectionRequired; import static graphql.validation.ValidationErrorType.SubscriptionIntrospectionRootField; import static graphql.validation.ValidationErrorType.SubscriptionMultipleRootFields; +import static graphql.validation.ValidationErrorType.SubselectionNotAllowed; +import static graphql.validation.ValidationErrorType.SubselectionRequired; import static graphql.validation.ValidationErrorType.UndefinedFragment; import static graphql.validation.ValidationErrorType.UndefinedVariable; +import static graphql.validation.ValidationErrorType.UniqueObjectFieldName; import static graphql.validation.ValidationErrorType.UnknownArgument; import static graphql.validation.ValidationErrorType.UnknownDirective; import static graphql.validation.ValidationErrorType.UnknownOperation; @@ -134,8 +134,6 @@ import static graphql.validation.ValidationErrorType.VariableTypeMismatch; import static graphql.validation.ValidationErrorType.WrongType; import static java.lang.System.arraycopy; -import static graphql.language.OperationDefinition.Operation.SUBSCRIPTION; -import static graphql.validation.ValidationErrorType.UniqueObjectFieldName; /** * Validates the document and its operations with one iterative traversal. @@ -258,8 +256,14 @@ public class OperationValidator { // A current operation means fragment traversal and operation-scoped rules are active private final boolean allRulesEnabled; + private final @Nullable NormalizedDocumentBuilder normalizedDocumentBuilder; public OperationValidator(ValidationContext validationContext, ValidationErrorCollector errorCollector, Predicate rulePredicate) { + this(validationContext, errorCollector, rulePredicate, null); + } + + public OperationValidator(ValidationContext validationContext, ValidationErrorCollector errorCollector, Predicate rulePredicate, @Nullable NormalizedDocumentBuilder normalizedDocumentBuilder) { + this.normalizedDocumentBuilder = normalizedDocumentBuilder; this.validationContext = validationContext; this.errorCollector = errorCollector; this.validationUtil = new ValidationUtil(); @@ -367,6 +371,9 @@ private boolean isRuleEnabled(OperationValidationRule rule) { private void enterTraversal(Node node, List ancestors) { if (node instanceof SelectionSet) { parentTypeStack.add(resolveSelectionSetParent(ancestors)); + if (normalizedDocumentBuilder != null) { + normalizedDocumentBuilder.selectionSet((SelectionSet) node); + } } else if (node instanceof Field) { enterField((Field) node); } else if (node instanceof Directive) { @@ -390,6 +397,9 @@ private void enterField(Field field) { ? null : getFieldDefinition(parentType, field.getName()); fieldDefinitionStack.add(fieldDefinition); + if (normalizedDocumentBuilder != null && parentType != null && fieldDefinition != null) { + normalizedDocumentBuilder.field(field, parentType); + } enterName(field.getName()); } diff --git a/src/main/java/graphql/validation/Validator.java b/src/main/java/graphql/validation/Validator.java index fec89773c2..ef6973f5f6 100644 --- a/src/main/java/graphql/validation/Validator.java +++ b/src/main/java/graphql/validation/Validator.java @@ -5,6 +5,7 @@ import graphql.Internal; import graphql.i18n.I18n; import graphql.language.Document; +import graphql.normalized.NormalizedDocument; import graphql.schema.GraphQLSchema; import org.jspecify.annotations.Nullable; @@ -47,11 +48,17 @@ public List validateDocument(GraphQLSchema schema, Document doc } public List validateDocument(GraphQLSchema schema, Document document, Predicate rulePredicate, Locale locale, QueryComplexityLimits limits, @Nullable GraphQLContext graphQLContext) { + return validateDocumentWithResult(schema, document, rulePredicate, locale, limits, graphQLContext).errors(); + } + + public DocumentValidationResult validateDocumentWithResult(GraphQLSchema schema, Document document, Predicate rulePredicate, Locale locale, @Nullable QueryComplexityLimits limits, @Nullable GraphQLContext graphQLContext) { I18n i18n = I18n.i18n(I18n.BundleType.Validation, locale); ValidationContext validationContext = new ValidationContext(schema, document, i18n, limits, graphQLContext); ValidationErrorCollector validationErrorCollector = new ValidationErrorCollector(MAX_VALIDATION_ERRORS); - OperationValidator operationValidator = new OperationValidator(validationContext, validationErrorCollector, rulePredicate); + NormalizedDocumentBuilder normalizedDocumentBuilder = graphQLContext != null && graphQLContext.getBoolean(NormalizedDocument.ENABLED) + ? new NormalizedDocumentBuilder(validationContext) : null; + OperationValidator operationValidator = new OperationValidator(validationContext, validationErrorCollector, rulePredicate, normalizedDocumentBuilder); try { operationValidator.validate(); @@ -65,6 +72,8 @@ public List validateDocument(GraphQLSchema schema, Document doc .build()); } - return validationErrorCollector.getErrors(); + List errors = validationErrorCollector.getErrors(); + NormalizedDocument normalizedDocument = errors.isEmpty() && normalizedDocumentBuilder != null ? normalizedDocumentBuilder.build() : null; + return new DocumentValidationResult(errors, normalizedDocument); } } diff --git a/src/test/groovy/graphql/TypeResolverExecutionTest.groovy b/src/test/groovy/graphql/TypeResolverExecutionTest.groovy index b19cf59a15..a4364a725e 100644 --- a/src/test/groovy/graphql/TypeResolverExecutionTest.groovy +++ b/src/test/groovy/graphql/TypeResolverExecutionTest.groovy @@ -549,7 +549,7 @@ class TypeResolverExecutionTest extends Specification { } ''' - def er = graphQL.execute(query) + def er = graphQL.execute { it.query(query).graphQLContext([(graphql.normalized.NormalizedDocument.ENABLED): true]) } then: er.errors.isEmpty() @@ -574,7 +574,7 @@ class TypeResolverExecutionTest extends Specification { } ''' - er = graphQL.execute(query) + er = graphQL.execute { it.query(query).graphQLContext([(graphql.normalized.NormalizedDocument.ENABLED): true]) } then: er.errors.isEmpty() diff --git a/src/test/groovy/graphql/execution/NormalizedValuesTest.groovy b/src/test/groovy/graphql/execution/NormalizedValuesTest.groovy new file mode 100644 index 0000000000..b5f89495db --- /dev/null +++ b/src/test/groovy/graphql/execution/NormalizedValuesTest.groovy @@ -0,0 +1,115 @@ +package graphql.execution + +import graphql.AssertException +import graphql.GraphQLContext +import graphql.TestUtil +import graphql.language.AstPrinter +import graphql.language.Field +import graphql.language.OperationDefinition +import graphql.language.StringValue +import graphql.parser.Parser +import graphql.schema.InputValueWithState +import graphql.schema.visibility.DefaultGraphqlFieldVisibility +import spock.lang.Specification + +class NormalizedValuesTest extends Specification { + def schema = TestUtil.schema(''' + enum Color { RED BLUE } + input Input { id: ID ids: [ID!] nested: Input color: Color } + type Query { f(input: Input ids: [ID!] id: ID! fallback: ID optional: Int nil: ID): String } + ''') + def context = GraphQLContext.getDefault() + + def "normalized variables preserve nested type information missing values and explicit nulls"() { + given: + def operation = operation('''query($input: Input, $ids: [ID!], $id: ID!, $fallback: ID = "default", $absent: Int, $nil: ID) { + f(input: $input, ids: $ids, id: $id, fallback: $fallback, optional: $absent, nil: $nil) + }''') + def raw = RawVariables.of([input: [id: 7, ids: [1, 2], nested: [id: null], color: 'RED'], ids: 9, id: 123, nil: null]) + + when: + def variables = ValuesResolver.getNormalizedVariableValues(schema, operation.variableDefinitions, raw, context, Locale.ENGLISH).toMap() + def field = operation.selectionSet.selections[0] as Field + def arguments = ValuesResolver.getNormalizedArgumentValues(schema.queryType.getFieldDefinition('f').arguments, field.arguments, variables) + + then: + variables.keySet() == ['input', 'ids', 'id', 'fallback', 'nil'] as Set + variables.input.typeName == 'Input' + variables.input.value.id.typeName == 'ID' + variables.input.value.id.value.value == '7' + variables.input.value.ids.typeName == '[ID!]' + variables.input.value.ids.value*.value == ['1', '2'] + variables.input.value.nested.value.id.value == null + variables.input.value.color.value.name == 'RED' + variables.ids.value*.value == ['9'] + variables.id.typeName == 'ID!' + variables.id.value.value == '123' + variables.fallback.value.value == 'default' + variables.nil.value == null + arguments.keySet() == ['input', 'ids', 'id', 'fallback', 'nil'] as Set + arguments.input.value == variables.input.value + } + + def "normalized argument literals retain enum and list structure and omit absent nested variables"() { + given: + def operation = operation('''query($absent: ID) { + f(input: {id: $absent, ids: [3, 4], nested: {id: null}, color: BLUE}, ids: 5, id: 6) + }''') + def field = operation.selectionSet.selections[0] as Field + + when: + def arguments = ValuesResolver.getNormalizedArgumentValues(schema.queryType.getFieldDefinition('f').arguments, field.arguments, [:]) + + then: + arguments.input.value.keySet() == ['ids', 'nested', 'color'] as Set + arguments.input.value.ids.value*.value == [3, 4] + arguments.input.value.nested.value.id.value == null + arguments.input.value.color.value.name == 'BLUE' + arguments.ids.value*.value == [5] + arguments.id.typeName == 'ID!' + arguments.id.value.value == 6 + } + + def "external input objects convert back to literals including singleton lists enum values and nulls"() { + given: + def external = [id: 7, ids: [8, 9], nested: [id: null], color: 'BLUE'] + def type = schema.getType('Input') + + when: + def literal = ValuesResolver.valueToLiteral(DefaultGraphqlFieldVisibility.DEFAULT_FIELD_VISIBILITY, + InputValueWithState.newExternalValue(external), type, context, Locale.ENGLISH) + def internal = ValuesResolver.externalValueToInternalValue(DefaultGraphqlFieldVisibility.DEFAULT_FIELD_VISIBILITY, + external, type, context, Locale.ENGLISH) + + then: + AstPrinter.printAstCompact(literal) == '{id:"7",ids:["8","9"],nested:{id:null},color:BLUE}' + internal == [id: '7', ids: ['8', '9'], nested: [id: null], color: 'BLUE'] + } + + def "normalized non-null variables must already be valid"() { + given: + def operation = operation('query($id: ID!) { f(id: $id) }') + + when: + ValuesResolver.getNormalizedVariableValues(schema, operation.variableDefinitions, RawVariables.of(raw), context, Locale.ENGLISH) + + then: + thrown(AssertException) + + where: + raw << [[:], [id: null]] + } + + def "ID literal conversion accepts numeric IDs and UUID values"() { + expect: + graphql.Scalars.GraphQLID.coercing.valueToLiteral(123) instanceof StringValue + graphql.Scalars.GraphQLID.coercing.valueToLiteral(123).value == '123' + + def uuid = UUID.fromString('a2608c81-9eaa-49bd-8b12-5640636f0c04') + graphql.Scalars.GraphQLID.coercing.valueToLiteral(uuid, context, Locale.ENGLISH).value == uuid.toString() + } + + private static OperationDefinition operation(String query) { + Parser.parse(query).getDefinitionsOfType(OperationDefinition).first() + } +} diff --git a/src/test/groovy/graphql/execution/directives/OperationDirectivesResolverTest.groovy b/src/test/groovy/graphql/execution/directives/OperationDirectivesResolverTest.groovy index 9f5de2632c..a9ebb63f59 100644 --- a/src/test/groovy/graphql/execution/directives/OperationDirectivesResolverTest.groovy +++ b/src/test/groovy/graphql/execution/directives/OperationDirectivesResolverTest.groovy @@ -158,13 +158,6 @@ class OperationDirectivesResolverTest extends Specification { commonIntegrationAsserts(resolveDirectives) - when: - def normalizedOperation = executionContext.getNormalizedQueryTree().get() - def enoResolveDirectives = normalizedOperation.getOperationDirectives() - - then: - commonIntegrationAsserts(enoResolveDirectives) - when: def allOperationDirectives = executionContext.getAllOperationDirectives() diff --git a/src/test/groovy/graphql/execution/directives/QueryDirectivesIntegrationTest.groovy b/src/test/groovy/graphql/execution/directives/QueryDirectivesIntegrationTest.groovy index 60c82e3b62..a7ebeb1827 100644 --- a/src/test/groovy/graphql/execution/directives/QueryDirectivesIntegrationTest.groovy +++ b/src/test/groovy/graphql/execution/directives/QueryDirectivesIntegrationTest.groovy @@ -2,12 +2,9 @@ package graphql.execution.directives import graphql.GraphQL import graphql.TestUtil -import graphql.execution.RawVariables import graphql.language.IntValue -import graphql.normalized.ExecutableNormalizedOperationFactory import graphql.normalized.NormalizedInputValue import graphql.schema.DataFetcher -import graphql.schema.FieldCoordinates import graphql.schema.GraphQLDirective import graphql.schema.GraphQLSchema import spock.lang.Specification @@ -171,21 +168,16 @@ class QueryDirectivesIntegrationTest extends Specification { joinArgs(immediate) == "cached(forMillis:10)" } - def "can capture directive argument values inside ENO path"() { - def query = TestUtil.parseQuery(pathologicalQuery) + def "can capture normalized directive argument values during execution"() { when: - def eno = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - schema, query, "Books", RawVariables.emptyVariables()) - + def result = execute(pathologicalQuery) then: - def booksENF = eno.getTopLevelFields()[0] - booksENF != null - def bookQueryDirectives = eno.getQueryDirectives(booksENF) - bookQueryDirectives.immediateAppliedDirectivesByName.isEmpty() - - def reviewField = eno.getCoordinatesToNormalizedFields().get(FieldCoordinates.coordinates("Book", "review")) - def reviewQueryDirectives = eno.getQueryDirectives(reviewField[0]) + result.errors.empty + def reviewQueryDirectives = capturedDirectives["review"] + reviewQueryDirectives.immediateAppliedDirectivesByField.size() == 3 + reviewQueryDirectives.immediateDirectivesByField.size() == 3 + reviewQueryDirectives.immediateAppliedDirectivesByField.values()*.size() == [2, 1, 2] def reviewImmediateDirectivesMap = reviewQueryDirectives.immediateAppliedDirectivesByName def argInputValues = simplifiedInputValuesWithState(reviewImmediateDirectivesMap) argInputValues == [ diff --git a/src/test/groovy/graphql/introspection/GoodFaithIntrospectionTest.groovy b/src/test/groovy/graphql/introspection/GoodFaithIntrospectionTest.groovy index 1f45ea8a69..fc56c586c9 100644 --- a/src/test/groovy/graphql/introspection/GoodFaithIntrospectionTest.groovy +++ b/src/test/groovy/graphql/introspection/GoodFaithIntrospectionTest.groovy @@ -4,9 +4,6 @@ import graphql.ExecutionInput import graphql.ExecutionResult import graphql.ParseAndValidate import graphql.TestUtil -import graphql.execution.CoercedVariables -import graphql.language.Document -import graphql.normalized.ExecutableNormalizedOperationFactory import graphql.validation.OperationValidationRule import graphql.validation.QueryComplexityLimits import spock.lang.Specification @@ -25,18 +22,6 @@ class GoodFaithIntrospectionTest extends Specification { QueryComplexityLimits.setDefaultLimits(originalLimits) } - def "standard introspection query is inside limits just in general"() { - - when: - Document document = TestUtil.toDocument(IntrospectionQuery.INTROSPECTION_QUERY) - def eno = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation(graphql.getGraphQLSchema(), document, - "IntrospectionQuery", CoercedVariables.emptyVariables()) - - then: - eno.getOperationFieldCount() < QueryComplexityLimits.DEFAULT_MAX_INTROSPECTION_MERGED_FIELD_COUNT // currently 189 - eno.getOperationDepth() < QueryComplexityLimits.DEFAULT_MAX_INTROSPECTION_DEPTH // currently 13 - } - def "test asking for introspection in good faith"() { when: diff --git a/src/test/groovy/graphql/introspection/GoodFaithMergedFieldsTest.groovy b/src/test/groovy/graphql/introspection/GoodFaithMergedFieldsTest.groovy index dfcf111b18..009b733cd4 100644 --- a/src/test/groovy/graphql/introspection/GoodFaithMergedFieldsTest.groovy +++ b/src/test/groovy/graphql/introspection/GoodFaithMergedFieldsTest.groovy @@ -3,8 +3,6 @@ package graphql.introspection import graphql.ExecutionInput import graphql.GraphQL import graphql.TestUtil -import graphql.execution.CoercedVariables -import graphql.normalized.ExecutableNormalizedOperationFactory import graphql.parser.Parser import graphql.validation.GoodFaithIntrospectionExceeded import graphql.validation.OperationValidationRule @@ -262,15 +260,11 @@ class GoodFaithMergedFieldsTest extends Specification { type B implements I { name: String child: B extra: String } union U = A | B ''') - def base = "{ __type(name: \"Query\") { name } $selection } $fragments" - def eno = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation(abstractSchema, Parser.parse(base), - null, CoercedVariables.emptyVariables()) def padding = (1..(500 - mergedFieldCount)).collect { "p$it: normalField" }.join(' ') def atLimit = "{ __type(name: \"Query\") { name } $padding $selection } $fragments" def aboveLimit = "{ __type(name: \"Query\") { name } extra: normalField $padding $selection } $fragments" expect: - eno.operationFieldCount == normalizationFieldCount new Validator().validateDocument(abstractSchema, Parser.parse(atLimit), Locale.ENGLISH).empty when: @@ -280,16 +274,16 @@ class GoodFaithMergedFieldsTest extends Specification { thrown(GoodFaithIntrospectionExceeded) where: - selection | fragments | mergedFieldCount | normalizationFieldCount - 'node { name name }' | '' | 4 | 4 - 'node { ...on I { name } ...on A { name } }' | '' | 4 | 5 - 'node { ...on A { name } ...on B { name } }' | '' | 5 | 5 - 'union { ...on A { name } ...on B { name } }' | '' | 5 | 5 - 'node { ...on A { ...on I { name } } }' | '' | 4 | 4 - 'node { ...on A { ...F } ...on B { ...F } }' | 'fragment F on I { name }' | 4 | 4 - 'node { ...on A { ...on I { child { ...on I { name } ...on B { extra } } } } }' | '' | 6 | 5 - 'node { child { name } ...on A { child { name extra } } }' | '' | 6 | 8 - 'node { ...F } alias: node { ...F }' | 'fragment F on I { name }' | 6 | 6 + selection | fragments | mergedFieldCount + 'node { name name }' | '' | 4 + 'node { ...on I { name } ...on A { name } }' | '' | 4 + 'node { ...on A { name } ...on B { name } }' | '' | 5 + 'union { ...on A { name } ...on B { name } }' | '' | 5 + 'node { ...on A { ...on I { name } } }' | '' | 4 + 'node { ...on A { ...F } ...on B { ...F } }' | 'fragment F on I { name }' | 4 + 'node { ...on A { ...on I { child { ...on I { name } ...on B { extra } } } } }' | '' | 6 + 'node { child { name } ...on A { child { name extra } } }' | '' | 6 + 'node { ...F } alias: node { ...F }' | 'fragment F on I { name }' | 6 } def "Good Faith counts fragments already checked by another operation"() { diff --git a/src/test/groovy/graphql/language/AstReconstructionTest.groovy b/src/test/groovy/graphql/language/AstReconstructionTest.groovy new file mode 100644 index 0000000000..931a7faee0 --- /dev/null +++ b/src/test/groovy/graphql/language/AstReconstructionTest.groovy @@ -0,0 +1,44 @@ +package graphql.language + +import graphql.parser.Parser +import spock.lang.Specification + +class AstReconstructionTest extends Specification { + def "generic child replacement preserves executable document values types and locations"() { + given: + def document = Parser.parse('''query Q($values: [[Int!]!]!, $flag: Boolean = false) { + f(int: 1, float: 1.5, string: "text", enum: RED, null: null, bool: true, variable: $flag, + list: [1, null], object: {value: 2}) + ... @include(if: $flag) { a } + ... on T { b } + }''') + + when: + def rebuilt = rebuild(document) + + then: + AstPrinter.printAst(rebuilt) == AstPrinter.printAst(document) + rebuilt.sourceLocation == document.sourceLocation + def originalType = document.getDefinitionsOfType(OperationDefinition)[0].variableDefinitions[0].type + def rebuiltType = rebuilt.getDefinitionsOfType(OperationDefinition)[0].variableDefinitions[0].type + !rebuiltType.is(originalType) + graphql.schema.idl.TypeUtil.simplePrint(rebuiltType) == '[[Int!]!]!' + graphql.schema.idl.TypeUtil.isWrapped(rebuiltType) + } + + def "sorting keeps untyped inline scopes distinct from typed scopes"() { + given: + def document = Parser.parse('{ ... on Z { z } ... @include(if: true) { a } ... on A { b } }') + + when: + def sorted = new AstSorter().sort(document) + + then: + sorted.getDefinitionsOfType(OperationDefinition)[0].selectionSet.selections*.typeCondition*.name == [null, 'A', 'Z'] + } + + private static Node rebuild(Node node) { + def children = node.namedChildren.children.collectEntries { name, nodes -> [(name): nodes.collect { rebuild(it) }] } + node.withNewChildren(NodeChildrenContainer.newNodeChildrenContainer(children).build()) + } +} diff --git a/src/test/groovy/graphql/normalized/ExecutableNormalizedFieldTest.groovy b/src/test/groovy/graphql/normalized/ExecutableNormalizedFieldTest.groovy deleted file mode 100644 index 870f4d48a3..0000000000 --- a/src/test/groovy/graphql/normalized/ExecutableNormalizedFieldTest.groovy +++ /dev/null @@ -1,143 +0,0 @@ -package graphql.normalized - -import graphql.TestUtil -import graphql.execution.CoercedVariables -import graphql.language.Document -import graphql.schema.GraphQLSchema -import spock.lang.Specification - -class ExecutableNormalizedFieldTest extends Specification { - - def "can get children of object type"() { - - String schema = """ - type Query{ - pets: [Pet] - } - interface Pet { - id: ID - name : String! - } - type Cat implements Pet{ - id: ID - name : String! - meow : String - } - type Dog implements Pet{ - id: ID - name : String! - woof : String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - pets { - id - name - ... on Dog { - woof - } - ... on Cat { - meow - } - } - } - - """ - Document document = TestUtil.parseQuery(query) - - def normalizedOperation = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - - def pets = normalizedOperation.getTopLevelFields()[0] - def allChildren = pets.getChildren() - def dogFields = pets.getChildren("Dog") - - expect: - allChildren.collect { it.name } == ["id", "name", "woof", "meow"] - dogFields.collect { it.name } == ["id", "name", "woof"] - } - - def "forEachFieldDefinition respects custom GraphqlFieldVisibility"() { - // This test verifies that ExecutableNormalizedField.forEachFieldDefinition() uses - // GraphqlFieldVisibility to look up fields. This is important for federated subgraphs - // where the supergraph may have fields that don't exist in the local schema, but - // a custom visibility can provide placeholder field definitions. - String schema = """ - type Query{ - pet: Pet - } - type Pet { - id: ID - name: String - } - """ - - // Create a custom visibility that provides a "virtual" field that doesn't exist on the type - def customVisibility = new graphql.schema.visibility.GraphqlFieldVisibility() { - @Override - List getFieldDefinitions(graphql.schema.GraphQLFieldsContainer fieldsContainer) { - def fields = new ArrayList<>(fieldsContainer.getFieldDefinitions()) - // Add a virtual "age" field for Pet type - if (fieldsContainer.name == "Pet") { - fields.add(graphql.schema.GraphQLFieldDefinition.newFieldDefinition() - .name("age") - .type(graphql.Scalars.GraphQLInt) - .build()) - } - return fields - } - - @Override - graphql.schema.GraphQLFieldDefinition getFieldDefinition(graphql.schema.GraphQLFieldsContainer fieldsContainer, String fieldName) { - // First check if the field exists on the type - def field = fieldsContainer.getFieldDefinition(fieldName) - if (field != null) { - return field - } - // Provide virtual "age" field for Pet type - if (fieldsContainer.name == "Pet" && fieldName == "age") { - return graphql.schema.GraphQLFieldDefinition.newFieldDefinition() - .name("age") - .type(graphql.Scalars.GraphQLInt) - .build() - } - return null - } - } - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - // Rebuild schema with custom visibility - def codeRegistry = graphql.schema.GraphQLCodeRegistry.newCodeRegistry(graphQLSchema.getCodeRegistry()) - .fieldVisibility(customVisibility) - .build() - graphQLSchema = graphQLSchema.transform { builder -> builder.codeRegistry(codeRegistry) } - - // Query that includes the "virtual" age field that exists only through visibility - String query = """ - { - pet { - id - name - age - } - } - """ - Document document = TestUtil.parseQuery(query) - - when: - // This should succeed because the visibility provides the "age" field - def normalizedOperation = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation( - graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def pet = normalizedOperation.getTopLevelFields()[0] - def fieldNames = pet.getChildren().collect { it.name } - - then: - // The age field should be found via the custom visibility - fieldNames.contains("age") - fieldNames.containsAll(["id", "name", "age"]) - } - -} diff --git a/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationFactoryDeferTest.groovy b/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationFactoryDeferTest.groovy deleted file mode 100644 index 5f3333168d..0000000000 --- a/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationFactoryDeferTest.groovy +++ /dev/null @@ -1,1329 +0,0 @@ -package graphql.normalized - -import graphql.AssertException -import graphql.ExecutionInput -import graphql.GraphQL -import graphql.TestUtil -import graphql.execution.RawVariables -import graphql.language.Document -import graphql.schema.GraphQLSchema -import graphql.util.TraversalControl -import graphql.util.Traverser -import graphql.util.TraverserContext -import graphql.util.TraverserVisitorStub -import spock.lang.Specification - -class ExecutableNormalizedOperationFactoryDeferTest extends Specification { - String schema = """ - directive @defer(if: Boolean, label: String) on FRAGMENT_SPREAD | INLINE_FRAGMENT - - type Query { - dog: Dog - animal: Animal - mammal: Mammal - } - - interface LivingThing { - age: Int - } - - interface Animal implements LivingThing { - name: String - age: Int - } - - type Dog implements Animal & LivingThing { - name: String - age: Int - breed: String - owner: Person - } - - type Cat implements Animal & LivingThing { - name: String - age: Int - breed: String - color: String - siblings: [Cat] - } - - type Fish implements Animal & LivingThing { - name: String - age: Int - } - - type Person { - firstname: String - lastname: String - bestFriend: Person - } - - union Mammal = Dog | Cat - """ - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - def "defer on a single field via inline fragment without type"() { - given: - - String query = ''' - query q { - dog { - name - ... @defer(label: "breed-defer") { - breed - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name', - 'Dog.breed defer{[label=breed-defer;types=[Dog]]}', - ] - } - - def "fragment on interface field with no type"() { - given: - - String query = ''' - query q { - animal { - ... @defer { - name - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.animal', - "[Cat, Dog, Fish].name defer{[label=null;types=[Cat, Dog, Fish]]}", - ] - } - - def "fragments on non-conditional fields"() { - given: - - String query = ''' - query q { - animal { - ... on Cat @defer { - name - } - ... on Dog @defer { - name - } - ... on Animal @defer { - name - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.animal', - "[Cat, Dog, Fish].name defer{[label=null;types=[Cat]],[label=null;types=[Dog]],[label=null;types=[Cat, Dog, Fish]]}", - ] - } - - def "fragments on subset of non-conditional fields"() { - given: - - String query = ''' - query q { - animal { - ... on Cat @defer { - name - } - ... on Dog @defer { - name - } - ... on Fish { - name - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.animal', - "[Cat, Dog, Fish].name defer{[label=null;types=[Cat]],[label=null;types=[Dog]]}", - ] - } - - def "field on multiple defer declarations is associated with "() { - given: - String query = ''' - query q { - dog { - ... @defer { - name - age - } - ... @defer { - age - } - } - } - ''' - Map variables = [:] - - when: - def executableNormalizedOperation = createExecutableNormalizedOperations(query, variables); - - List printedTree = printTreeWithIncrementalExecutionDetails(executableNormalizedOperation) - - then: - - def nameField = findField(executableNormalizedOperation, "Dog", "name") - def ageField = findField(executableNormalizedOperation, "Dog", "age") - - nameField.deferredExecutions.size() == 1 - ageField.deferredExecutions.size() == 2 - - // age field is associated with 2 defer executions, one of then is shared with "name" the other isn't - ageField.deferredExecutions.any { - it == nameField.deferredExecutions[0] - } - - ageField.deferredExecutions.any { - it != nameField.deferredExecutions[0] - } - - printedTree == ['Query.dog', - "Dog.name defer{[label=null;types=[Dog]]}", - "Dog.age defer{[label=null;types=[Dog]],[label=null;types=[Dog]]}", - ] - } - - def "fragment on interface"() { - given: - - String query = ''' - query q { - animal { - ... on Animal @defer { - name - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.animal', - '[Cat, Dog, Fish].name defer{[label=null;types=[Cat, Dog, Fish]]}', - ] - } - - def "fragment on distant interface"() { - given: - - String query = ''' - query q { - animal { - ... on LivingThing @defer { - age - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.animal', - '[Cat, Dog, Fish].age defer{[label=null;types=[Cat, Dog, Fish]]}', - ] - } - - def "fragment on union"() { - given: - - String query = ''' - query q { - mammal { - ... on Dog @defer { - name - breed - } - ... on Cat @defer { - name - breed - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.mammal', - '[Dog, Cat].name defer{[label=null;types=[Cat]],[label=null;types=[Dog]]}', - 'Dog.breed defer{[label=null;types=[Dog]]}', - 'Cat.breed defer{[label=null;types=[Cat]]}', - ] - } - - def "fragments on interface"() { - given: - - String query = ''' - query q { - animal { - ... on Animal @defer { - name - } - ... on Animal @defer { - age - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.animal', - '[Cat, Dog, Fish].name defer{[label=null;types=[Cat, Dog, Fish]]}', - '[Cat, Dog, Fish].age defer{[label=null;types=[Cat, Dog, Fish]]}', - ] - } - - def "defer on a subselection of non-conditional fields"() { - given: - - String query = ''' - query q { - animal { - ... on Cat @defer { - name - } - ... on Dog { - name - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.animal', - '[Cat, Dog].name defer{[label=null;types=[Cat]]}', - ] - } - - def "fragments on conditional fields"() { - given: - - String query = ''' - query q { - animal { - ... on Cat @defer { - breed - } - ... on Dog @defer { - breed - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.animal', - 'Cat.breed defer{[label=null;types=[Cat]]}', - 'Dog.breed defer{[label=null;types=[Dog]]}' - ] - } - - def "defer on a single field via inline fragment with type"() { - given: - - String query = ''' - query q { - dog { - name - ... on Dog @defer(label: "breed-defer") { - breed - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name', - 'Dog.breed defer{[label=breed-defer;types=[Dog]]}', - ] - } - - def "1 defer on 2 fields"() { - given: - String query = ''' - query q { - animal { - ... @defer { - name - } - - ... on Dog @defer { - name - breed - } - - ... on Cat @defer { - name - breed - } - } - } - ''' - - Map variables = [:] - - when: - def executableNormalizedOperation = createExecutableNormalizedOperations(query, variables); - - List printedTree = printTreeWithIncrementalExecutionDetails(executableNormalizedOperation) - - then: "should result in the same instance of defer block" - def nameField = findField(executableNormalizedOperation,"[Cat, Dog, Fish]","name") - def dogBreedField = findField(executableNormalizedOperation, "Dog", "breed") - def catBreedField = findField(executableNormalizedOperation, "Cat", "breed") - - nameField.deferredExecutions.size() == 3 - dogBreedField.deferredExecutions.size() == 1 - catBreedField.deferredExecutions.size() == 1 - - // nameField should share a defer block with each of the other fields - nameField.deferredExecutions.any { - it == dogBreedField.deferredExecutions[0] - } - nameField.deferredExecutions.any { - it == catBreedField.deferredExecutions[0] - } - // also, nameField should have a defer block that is not shared with any other field - nameField.deferredExecutions.any { - it != dogBreedField.deferredExecutions[0] && - it != catBreedField.deferredExecutions[0] - } - - printedTree == ['Query.animal', - '[Cat, Dog, Fish].name defer{[label=null;types=[Cat]],[label=null;types=[Dog]],[label=null;types=[Cat, Dog, Fish]]}', - 'Dog.breed defer{[label=null;types=[Dog]]}', - 'Cat.breed defer{[label=null;types=[Cat]]}', - ] - } - - def "2 defers on 2 fields"() { - given: - - String query = ''' - query q { - dog { - ... @defer{ - name - } - ... @defer{ - breed - } - } - } - ''' - - Map variables = [:] - - when: - def executableNormalizedOperation = createExecutableNormalizedOperations(query, variables); - - List printedTree = printTreeWithIncrementalExecutionDetails(executableNormalizedOperation) - - then: "should result in 2 different instances of defer" - def nameField = findField(executableNormalizedOperation, "Dog", "name") - def breedField = findField(executableNormalizedOperation, "Dog", "breed") - - nameField.deferredExecutions.size() == 1 - breedField.deferredExecutions.size() == 1 - - // different label instances - nameField.deferredExecutions[0] != breedField.deferredExecutions[0] - - printedTree == ['Query.dog', - 'Dog.name defer{[label=null;types=[Dog]]}', - 'Dog.breed defer{[label=null;types=[Dog]]}', - ] - } - - def "defer on a fragment definition"() { - given: - - String query = ''' - query q { - dog { - ... DogFrag @defer(label: "breed-defer") - } - } - - fragment DogFrag on Dog { - name - breed - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name defer{[label=breed-defer;types=[Dog]]}', - 'Dog.breed defer{[label=breed-defer;types=[Dog]]}', - ] - } - - def "shared deferred selection is collected once through multiple fragments - label #label inline #inlineFragment"() { - given: - String directive = label == null ? '@defer' : "@defer(label: \"$label\")" - String deferredSelection = inlineFragment - ? "... $directive { firstname lastname }" - : "...OwnerData $directive" - String dataFragment = inlineFragment ? '' : ''' - fragment OwnerData on Person { - firstname - lastname - } - ''' - String query = """ - query q { - dog { - name - ...Sidebar - ...Details - } - } - fragment Sidebar on Dog { - ...OwnerField - } - fragment Details on Dog { - ...OwnerField - } - fragment OwnerField on Dog { - owner { - $deferredSelection - } - } - $dataFragment - """ - - when: - def operation = createExecutableNormalizedOperations(query, [:]) - - then: - def firstname = findField(operation, 'Person', 'firstname') - def lastname = findField(operation, 'Person', 'lastname') - firstname.deferredExecutions.size() == 1 - firstname.deferredExecutions == lastname.deferredExecutions - firstname.deferredExecutions.first().label == label - firstname.deferredExecutions.first().possibleTypes*.name == ['Person'] - printTreeWithIncrementalExecutionDetails(operation) == [ - 'Query.dog', - 'Dog.name', - 'Dog.owner', - "Person.firstname defer{[label=$label;types=[Person]]}", - "Person.lastname defer{[label=$label;types=[Person]]}", - ] - - where: - label | inlineFragment - 'OwnerField$defer$OwnerData' | false - null | false - 'owner-data' | true - null | true - } - - def "shared defer is reused when distinct parent AST fields merge"() { - given: - String query = ''' - query q { - dog { owner { ...PersonFields } } - dog { owner { ...PersonFields } } - } - fragment PersonFields on Person { - ...PersonData @defer(label: "person-data") - } - fragment PersonData on Person { - firstname - lastname - } - ''' - - when: - def operation = createExecutableNormalizedOperations(query, [:]) - - then: - operation.topLevelFields*.fieldName == ['dog'] - def dog = operation.topLevelFields[0] - dog.children*.fieldName == ['owner'] - def fields = dog.children[0].children - fields*.fieldName == ['firstname', 'lastname'] - fields[0].deferredExecutions.size() == 1 - fields[0].deferredExecutions == fields[1].deferredExecutions - fields[0].deferredExecutions.first().label == 'person-data' - fields[0].deferredExecutions.first().possibleTypes*.name == ['Person'] - } - - def "shared defer has separate execution objects for different root aliases"() { - given: - String query = ''' - query q { - first: dog { ...DogFields } - second: dog { ...DogFields } - } - fragment DogFields on Dog { - ...DogData @defer(label: "dog-data") - } - fragment DogData on Dog { - name - age - } - ''' - - when: - def operation = createExecutableNormalizedOperations(query, [:]) - - then: - operation.topLevelFields*.resultKey == ['first', 'second'] - def firstFields = operation.topLevelFields[0].children - def secondFields = operation.topLevelFields[1].children - firstFields*.fieldName == ['name', 'age'] - secondFields*.fieldName == ['name', 'age'] - firstFields[0].deferredExecutions.size() == 1 - secondFields[0].deferredExecutions.size() == 1 - firstFields[0].deferredExecutions == firstFields[1].deferredExecutions - secondFields[0].deferredExecutions == secondFields[1].deferredExecutions - def firstExecution = firstFields[0].deferredExecutions.first() - def secondExecution = secondFields[0].deferredExecutions.first() - firstExecution.label == 'dog-data' - secondExecution.label == 'dog-data' - !firstExecution.is(secondExecution) - } - - def "shared defer has separate execution objects at different nesting depths"() { - given: - String query = ''' - query q { - dog { - owner { - ...PersonFields - bestFriend { ...PersonFields } - } - } - } - fragment PersonFields on Person { - ...PersonData @defer(label: "person-data") - } - fragment PersonData on Person { - firstname - lastname - } - ''' - - when: - def operation = createExecutableNormalizedOperations(query, [:]) - - then: - def ownerFields = operation.topLevelFields[0].children[0].children - ownerFields*.fieldName == ['firstname', 'lastname', 'bestFriend'] - def friendFields = ownerFields[2].children - friendFields*.fieldName == ['firstname', 'lastname'] - ownerFields[0].deferredExecutions.size() == 1 - friendFields[0].deferredExecutions.size() == 1 - ownerFields[0].deferredExecutions == ownerFields[1].deferredExecutions - friendFields[0].deferredExecutions == friendFields[1].deferredExecutions - def ownerExecution = ownerFields[0].deferredExecutions.first() - def friendExecution = friendFields[0].deferredExecutions.first() - ownerExecution.label == 'person-data' - friendExecution.label == 'person-data' - !ownerExecution.is(friendExecution) - } - - def "distinct defers selecting the same fragment remain separate - #expectedLabels"() { - given: - String query = """ - query q { - dog { - ...DogData $firstDirective - ...DogData $secondDirective - } - } - fragment DogData on Dog { - name - age - } - """ - - when: - def operation = createExecutableNormalizedOperations(query, [:]) - - then: - def nameExecutions = findField(operation, 'Dog', 'name').deferredExecutions.toList() - def ageExecutions = findField(operation, 'Dog', 'age').deferredExecutions.toList() - nameExecutions*.label == expectedLabels - ageExecutions*.label == expectedLabels - !nameExecutions[0].is(nameExecutions[1]) - nameExecutions[0].is(ageExecutions[0]) - nameExecutions[1].is(ageExecutions[1]) - - where: - firstDirective | secondDirective | expectedLabels - '@defer(label: "first")' | '@defer(label: "second")' | ['first', 'second'] - '@defer' | '@defer' | [null, null] - } - - def "shared defer accumulates type coverage across #firstType then #secondType"() { - given: - String query = """ - query q { - animal { - ... on $firstType { ...AnimalFields } - ... on $secondType { ...AnimalFields } - } - } - fragment AnimalFields on Animal { - ...AnimalData @defer(label: "animal-data") - } - fragment AnimalData on Animal { - name - age - } - """ - - when: - def operation = createExecutableNormalizedOperations(query, [:]) - - then: - def fields = operation.topLevelFields[0].children - fields*.fieldName == ['name', 'age'] - fields[0].objectTypeNames.toList().sort() == expectedTypes - fields[1].objectTypeNames.toList().sort() == expectedTypes - fields[0].deferredExecutions.size() == 1 - fields[0].deferredExecutions == fields[1].deferredExecutions - def execution = fields[0].deferredExecutions.first() - execution.label == 'animal-data' - execution.possibleTypes*.name.sort() == expectedTypes - - where: - firstType | secondType | expectedTypes - 'Dog' | 'Cat' | ['Cat', 'Dog'] - 'Cat' | 'Dog' | ['Cat', 'Dog'] - 'Dog' | 'Animal' | ['Cat', 'Dog', 'Fish'] - 'Animal' | 'Dog' | ['Cat', 'Dog', 'Fish'] - 'Animal' | 'Mammal' | ['Cat', 'Dog', 'Fish'] - 'Mammal' | 'Animal' | ['Cat', 'Dog', 'Fish'] - } - - def "shared fragment merges eager Dog and deferred Cat selections - reversed #reversed"() { - given: - String dogSelection = '... on Dog { ...Shared }' - String catSelection = '... on Cat { ...Shared @defer(label: "cat-data") }' - String selections = reversed ? "$catSelection $dogSelection" : "$dogSelection $catSelection" - String query = """ - query q { - animal { - $selections - } - } - fragment Shared on Animal { - name - } - """ - - when: - def operation = createExecutableNormalizedOperations(query, [:]) - - then: - def fields = operation.topLevelFields[0].children - fields.size() == 1 - fields[0].objectTypeNames.toList().sort() == ['Cat', 'Dog'] - fields[0].deferredExecutions.size() == 1 - fields[0].fieldName == 'name' - fields[0].deferredExecutions.first().label == 'cat-data' - fields[0].deferredExecutions.first().possibleTypes*.name == ['Cat'] - - where: - reversed << [false, true] - } - - def "shared defer respects conditional collection - enabled #enabled skipDog #skipDog"() { - given: - String query = ''' - query q($enabled: Boolean!, $skipDog: Boolean!) { - animal { - ... on Dog { ...AnimalFields @skip(if: $skipDog) } - ... on Cat { ...AnimalFields } - } - } - fragment AnimalFields on Animal { - ...AnimalData @defer(if: $enabled, label: "animal-data") - } - fragment AnimalData on Animal { - name - age - } - ''' - def expectedTypes = skipDog ? ['Cat'] : ['Cat', 'Dog'] - - when: - def operation = createExecutableNormalizedOperations(query, [enabled: enabled, skipDog: skipDog]) - - then: - def fields = operation.topLevelFields[0].children - fields*.fieldName == ['name', 'age'] - fields[0].objectTypeNames.toList().sort() == expectedTypes - fields[1].objectTypeNames.toList().sort() == expectedTypes - fields[0].deferredExecutions == fields[1].deferredExecutions - fields[0].deferredExecutions*.label == (enabled ? ['animal-data'] : []) - fields[0].deferredExecutions.collect { it.possibleTypes*.name.sort() } == (enabled ? [expectedTypes] : []) - - where: - enabled | skipDog - true | false - true | true - false | false - false | true - } - - def "field merging preserves shared defer identity across common and type specific fields"() { - given: - String query = ''' - query q { - animal { - ...DogFields - ...DogFields - ...CatFields - ...CatFields - } - } - fragment DogFields on Dog { - ...DogData @defer(label: "dog-data") - } - fragment DogData on Dog { - name - breed - } - fragment CatFields on Cat { - ...CatData @defer(label: "cat-data") - } - fragment CatData on Cat { - name - breed - } - ''' - - when: - def operation = createExecutableNormalizedOperations(query, [:]) - - then: - operation.topLevelFields[0].children*.fieldName == ['name', 'breed', 'breed'] - def name = operation.topLevelFields[0].children[0] - name.objectTypeNames.toList().sort() == ['Cat', 'Dog'] - def dogBreed = findField(operation, 'Dog', 'breed') - def catBreed = findField(operation, 'Cat', 'breed') - dogBreed.deferredExecutions.size() == 1 - catBreed.deferredExecutions.size() == 1 - def dogExecution = dogBreed.deferredExecutions.first() - def catExecution = catBreed.deferredExecutions.first() - dogExecution.label == 'dog-data' - catExecution.label == 'cat-data' - dogExecution.possibleTypes*.name == ['Dog'] - catExecution.possibleTypes*.name == ['Cat'] - name.deferredExecutions == ([dogExecution, catExecution] as Set) - !dogExecution.is(catExecution) - } - - def "shared defer keeps type coverage separate between parent fields"() { - given: - String query = ''' - query q { - dog { ...AnimalFields } - animal { ...AnimalFields } - } - fragment AnimalFields on Animal { - ...AnimalData @defer(label: "animal-data") - } - fragment AnimalData on Animal { - name - age - } - ''' - - when: - def operation = createExecutableNormalizedOperations(query, [:]) - - then: - operation.topLevelFields*.fieldName == ['dog', 'animal'] - def dogFields = operation.topLevelFields[0].children - def animalFields = operation.topLevelFields[1].children - dogFields*.fieldName == ['name', 'age'] - animalFields*.fieldName == ['name', 'age'] - dogFields[0].deferredExecutions.size() == 1 - animalFields[0].deferredExecutions.size() == 1 - dogFields[0].deferredExecutions == dogFields[1].deferredExecutions - animalFields[0].deferredExecutions == animalFields[1].deferredExecutions - def dogExecution = dogFields[0].deferredExecutions.first() - def animalExecution = animalFields[0].deferredExecutions.first() - dogExecution.label == 'animal-data' - animalExecution.label == 'animal-data' - dogExecution.possibleTypes*.name == ['Dog'] - animalExecution.possibleTypes*.name.sort() == ['Cat', 'Dog', 'Fish'] - !dogExecution.is(animalExecution) - } - - def "duplicate deferred fragment spreads with the same label are rejected"() { - given: - String query = ''' - query q { - dog { - ...DogData @defer(label: "DogField$defer$DogData") - ...DogData @defer(label: "DogField$defer$DogData") - } - } - - fragment DogData on Dog { - name - breed - } - ''' - - when: - createExecutableNormalizedOperations(query, [:]) - - then: - def exception = thrown(AssertException) - exception.message == 'Internal error: should never happen: Duplicated @defer labels are not allowed: [DogField$defer$DogData]' - } - - def "multiple defer on same field with different labels"() { - given: - - String query = ''' - query q { - dog { - ... @defer(label: "name-defer") { - name - } - - ... @defer(label: "another-name-defer") { - name - } - } - } - - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name defer{[label=another-name-defer;types=[Dog]],[label=name-defer;types=[Dog]]}' - ] - } - - def "multiple fields and a single defer"() { - given: - - String query = ''' - query q { - dog { - ... @defer(label: "name-defer") { - name - } - - ... { - name - } - } - } - - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name defer{[label=name-defer;types=[Dog]]}', - ] - } - - def "multiple fields and a single defer - no label"() { - given: - - String query = ''' - query q { - dog { - ... @defer { - name - } - - ... { - name - } - } - } - - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name defer{[label=null;types=[Dog]]}', - ] - } - - def "multiple fields and multiple defers - no label"() { - given: - - String query = ''' - query q { - dog { - ... @defer { - name - } - ... @defer { - name - } - } - } - - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name defer{[label=null;types=[Dog]],[label=null;types=[Dog]]}', - ] - } - - def "nested defers - no label"() { - given: - - String query = ''' - query q { - dog { - ... @defer { - name - owner { - firstname - ... @defer { - lastname - } - } - } - } - } - - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name defer{[label=null;types=[Dog]]}', - 'Dog.owner defer{[label=null;types=[Dog]]}', - 'Person.firstname', - 'Person.lastname defer{[label=null;types=[Person]]}', - ] - } - - def "nested defers - with labels"() { - given: - - String query = ''' - query q { - dog { - ... @defer(label:"dog-defer") { - name - owner { - firstname - ... @defer(label: "lastname-defer") { - lastname - } - } - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name defer{[label=dog-defer;types=[Dog]]}', - 'Dog.owner defer{[label=dog-defer;types=[Dog]]}', - 'Person.firstname', - 'Person.lastname defer{[label=lastname-defer;types=[Person]]}', - ] - } - - def "nested defers - with named spreads"() { - given: - - String query = ''' - query q { - animal { - name - ... on Dog @defer(label:"dog-defer") { - owner { - firstname - ... @defer(label: "lastname-defer") { - lastname - } - } - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.animal', - '[Cat, Dog, Fish].name', - 'Dog.owner defer{[label=dog-defer;types=[Dog]]}', - 'Person.firstname', - 'Person.lastname defer{[label=lastname-defer;types=[Person]]}', - ] - } - - def "nesting defer blocks that would always result in no data are ignored"() { - given: - - String query = ''' - query q { - dog { - ... @defer(label: "one") { - ... @defer(label: "two") { - ... @defer(label: "three") { - name - } - } - } - } - } - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name defer{[label=three;types=[Dog]]}', - ] - } - - def "'if' argument is respected"() { - given: - - String query = ''' - query q { - dog { - ... @defer(if: false, label: "name-defer") { - name - } - - ... @defer(if: true, label: "another-name-defer") { - name - } - } - } - - ''' - - Map variables = [:] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name defer{[label=another-name-defer;types=[Dog]]}', - ] - } - - def "'if' argument is respected when value is passed through variable"() { - given: - - String query = ''' - query q($if1: Boolean, $if2: Boolean) { - dog { - ... @defer(if: $if1, label: "name-defer") { - name - } - - ... @defer(if: $if2, label: "another-name-defer") { - name - } - } - } - - ''' - - Map variables = [if1: false, if2: true] - - when: - List printedTree = executeQueryAndPrintTree(query, variables) - - then: - printedTree == ['Query.dog', - 'Dog.name defer{[label=another-name-defer;types=[Dog]]}', - ] - } - - private ExecutableNormalizedOperation createExecutableNormalizedOperations(String query, Map variables) { - assertValidQuery(graphQLSchema, query, variables) - Document document = TestUtil.parseQuery(query) - ExecutableNormalizedOperationFactory dependencyGraph = new ExecutableNormalizedOperationFactory() - - return dependencyGraph.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.of(variables), - ExecutableNormalizedOperationFactory.Options.defaultOptions().deferSupport(true), - ) - } - - private List executeQueryAndPrintTree(String query, Map variables) { - assertValidQuery(graphQLSchema, query, variables) - Document document = TestUtil.parseQuery(query) - ExecutableNormalizedOperationFactory dependencyGraph = new ExecutableNormalizedOperationFactory() - - def tree = dependencyGraph.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.of(variables), - ExecutableNormalizedOperationFactory.Options.defaultOptions().deferSupport(true), - ) - return printTreeWithIncrementalExecutionDetails(tree) - } - - private List printTreeWithIncrementalExecutionDetails(ExecutableNormalizedOperation queryExecutionTree) { - def result = [] - Traverser traverser = Traverser.depthFirst({ it.getChildren() }) - - traverser.traverse(queryExecutionTree.getTopLevelFields(), new TraverserVisitorStub() { - @Override - TraversalControl enter(TraverserContext context) { - ExecutableNormalizedField queryExecutionField = context.thisNode() - result << queryExecutionField.printDetails() + printDeferExecutionDetails(queryExecutionField) - return TraversalControl.CONTINUE - } - - String printDeferExecutionDetails(ExecutableNormalizedField field) { - def deferExecutions = field.deferredExecutions - if (deferExecutions == null || deferExecutions.isEmpty()) { - return "" - } - - def deferLabels = new ArrayList<>(deferExecutions) - .sort { it.label } - .sort { it.possibleTypes.collect {it.name} } - .collect { "[label=${it.label};types=${it.possibleTypes.collect{it.name}.sort()}]" } - .join(",") - - return " defer{${deferLabels}}" - } - }) - - result - } - - private static void assertValidQuery(GraphQLSchema graphQLSchema, String query, Map variables = [:]) { - GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build() - def ei = ExecutionInput.newExecutionInput(query).variables(variables).build() - assert graphQL.execute(ei).errors.size() == 0 - } - - private static ExecutableNormalizedField findField(ExecutableNormalizedOperation operation, String objectTypeNames, String fieldName) { - return operation.normalizedFieldToMergedField - .collect { it.key } - .find { it.fieldName == fieldName - && it.objectTypeNamesToString() == objectTypeNames} - } -} diff --git a/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationFactoryTest.groovy b/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationFactoryTest.groovy deleted file mode 100644 index 7463031d49..0000000000 --- a/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationFactoryTest.groovy +++ /dev/null @@ -1,3306 +0,0 @@ -package graphql.normalized - -import graphql.ExecutionInput -import graphql.GraphQL -import graphql.TestUtil -import graphql.execution.AbortExecutionException -import graphql.execution.CoercedVariables -import graphql.execution.MergedField -import graphql.execution.RawVariables -import graphql.execution.directives.QueryAppliedDirective -import graphql.introspection.IntrospectionQuery -import graphql.language.Document -import graphql.language.Field -import graphql.language.FragmentDefinition -import graphql.language.OperationDefinition -import graphql.schema.GraphQLDirective -import graphql.schema.GraphQLSchema -import graphql.schema.GraphQLTypeUtil -import graphql.util.TraversalControl -import graphql.util.Traverser -import graphql.util.TraverserContext -import graphql.util.TraverserVisitorStub -import graphql.validation.QueryComplexityLimits -import spock.lang.Specification - -import java.util.stream.Collectors -import java.util.stream.IntStream - -import static graphql.TestUtil.schema -import static graphql.language.AstPrinter.printAst -import static graphql.parser.Parser.parseValue -import static graphql.schema.FieldCoordinates.coordinates - -class ExecutableNormalizedOperationFactoryTest extends Specification { - static boolean deferSupport - - def setup() { - // Disable validation complexity limits so ENO limits can be tested - QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.NONE) - } - - def cleanup() { - QueryComplexityLimits.setDefaultLimits(QueryComplexityLimits.DEFAULT) - } - - def "test"() { - String schema = """ -type Query{ - animal: Animal -} -interface Animal { - name: String - friends: [Friend] -} - -union Pet = Dog | Cat - -type Friend { - name: String - isBirdOwner: Boolean - isCatOwner: Boolean - pets: [Pet] -} - -type Bird implements Animal { - name: String - friends: [Friend] -} - -type Cat implements Animal{ - name: String - friends: [Friend] - breed: String -} - -type Dog implements Animal{ - name: String - breed: String - friends: [Friend] -} - - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - animal{ - name - otherName: name - ... on Animal { - name - } - ... on Cat { - name - friends { - ... on Friend { - isCatOwner - pets { - ... on Dog { - name - } - } - } - } - } - ... on Bird { - friends { - isBirdOwner - } - friends { - name - pets { - ... on Cat { - breed - } - } - } - } - ... on Dog { - name - } - }} - - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == ['-Query.animal: Animal', - '--[Bird, Cat, Dog].name: String', - '--otherName: [Bird, Cat, Dog].name: String', - '--Cat.friends: [Friend]', - '---Friend.isCatOwner: Boolean', - '---Friend.pets: [Pet]', - '----Dog.name: String', - '--Bird.friends: [Friend]', - '---Friend.isBirdOwner: Boolean', - '---Friend.name: String', - '---Friend.pets: [Pet]', - '----Cat.breed: String' - ] - } - - def "test2"() { - String schema = """ - type Query{ - a: A - } - interface A { - b: B - } - type A1 implements A { - b: B - } - type A2 implements A{ - b: B - } - interface B { - leaf: String - } - type B1 implements B { - leaf: String - } - type B2 implements B { - leaf: String - } - - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - a { - ... on A { - myAlias: b { leaf } - } - ... on A1 { - b { - ... on B1 { - leaf - } - ... on B2 { - leaf - } - } - } - ... on A1 { - b { - ... on B1 { - leaf - } - } - } - ... on A2 { - b { - ... on B2 { - leaf - } - } - } - } - } - - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == ['-Query.a: A', - '--myAlias: [A1, A2].b: B', - '---[B1, B2].leaf: String', - '--A1.b: B', - '---[B1, B2].leaf: String', - '--A2.b: B', - '---B2.leaf: String' - ] - - - } - - def "test3"() { - String schema = """ - type Query{ - a: [A] - object: Object - } - type Object { - someValue: String - } - interface A { - b: B - } - type A1 implements A { - b: B - } - type A2 implements A{ - b: B - } - interface B { - leaf: String - } - type B1 implements B { - leaf: String - } - type B2 implements B { - leaf: String - } - - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - object{someValue} - a { - ... on A1 { - b { - ... on B { - leaf - } - ... on B1 { - leaf - } - ... on B2 { - ... on B { - leaf - } - leaf - leaf - ... on B2 { - leaf - } - } - } - } - } - } - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == ['-Query.object: Object', - '--Object.someValue: String', - '-Query.a: [A]', - '--A1.b: B', - '---[B1, B2].leaf: String' - ] - - } - - def "test impossible type condition"() { - - String schema = """ - type Query{ - pets: [Pet] - } - interface Pet { - name: String - } - type Cat implements Pet { - name: String - } - type Dog implements Pet{ - name: String - } - union CatOrDog = Cat | Dog - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - pets { - ... on Dog { - ... on CatOrDog { - ... on Cat{ - name - } - } - } - } - } - - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTree(tree) - - expect: - printedTree == ['Query.pets'] - - } - - def "query with unions and __typename"() { - - String schema = """ - type Query{ - pets: [CatOrDog] - } - type Cat { - catName: String - } - type Dog { - dogName: String - } - union CatOrDog = Cat | Dog - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - pets { - __typename - ... on Cat { - catName - } - ... on Dog { - dogName - } - } - } - - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTree(tree) - - expect: - printedTree == ['Query.pets', - '[Cat, Dog].__typename', - 'Cat.catName', - 'Dog.dogName'] - - } - - def "query with interface"() { - - String schema = """ - type Query{ - pets: [Pet] - } - interface Pet { - id: ID - } - type Cat implements Pet{ - id: ID - catName: String - } - type Dog implements Pet{ - id: ID - dogName: String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - pets { - id - ... on Cat { - catName - } - ... on Dog { - dogName - } - } - } - - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTree(tree) - - expect: - printedTree == ['Query.pets', - '[Cat, Dog].id', - 'Cat.catName', - 'Dog.dogName'] - - } - - def "test5"() { - String schema = """ - type Query{ - a: [A] - } - interface A { - b: String - } - type A1 implements A { - b: String - } - type A2 implements A{ - b: String - otherField: A - } - type A3 implements A { - b: String - } - - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - - def query = """ - { - a { - b - ... on A1 { - b - } - ... on A2 { - b - otherField { - ... on A2 { - b - } - ... on A3 { - b - } - } - - } - } - } - - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == ['-Query.a: [A]', - '--[A1, A2, A3].b: String', - '--A2.otherField: A', - '---[A2, A3].b: String' - ] - - } - - def "test6"() { - String schema = """ - type Query { - issues: [Issue] - } - - type Issue { - id: ID - author: User - } - type User { - name: String - createdIssues: [Issue] - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - def query = """{ issues { - author { - name - ... on User { - createdIssues { - id - } - } - } - }} - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTree(tree) - - expect: - printedTree == ['Query.issues', - 'Issue.author', - 'User.name', - 'User.createdIssues', - 'Issue.id'] - - } - - def "test7"() { - String schema = """ - type Query { - issues: [Issue] - } - - type Issue { - authors: [User] - } - type User { - name: String - friends: [User] - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - def query = """{ issues { - authors { - friends { - friends { - name - } - } - } - }} - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTree(tree) - - expect: - printedTree == ['Query.issues', - 'Issue.authors', - 'User.friends', - 'User.friends', - 'User.name'] - - } - - def "parses operation name"() { - String schema = """ - type Query { - issues: [Issue] - } - - type Issue { - authors: [User] - } - type User { - name: String - friends: [User] - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - def query = """query X_28 { issues { - authors { - friends { - friends { - name - } - } - } - }} - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTree(tree) - - expect: - tree.operation == OperationDefinition.Operation.QUERY - tree.operationName == "X_28" - printedTree == ['Query.issues', - 'Issue.authors', - 'User.friends', - 'User.friends', - 'User.name'] - - } - - def "query with fragment definition"() { - def graphQLSchema = TestUtil.schema(""" - type Query{ - foo: Foo - } - type Foo { - subFoo: String - moreFoos: Foo - } - """) - def query = """ - {foo { ...fooData moreFoos { ...fooData }}} fragment fooData on Foo { subFoo } - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTree(tree) - - expect: - printedTree == ['Query.foo', - 'Foo.subFoo', - 'Foo.moreFoos', - 'Foo.subFoo'] - } - - def "query with fragment and type condition"() { - def graphQLSchema = TestUtil.schema(""" - type Query { - pet(qualifier : String) : Pet - } - interface Pet { - name(nameArg : String) : String - } - - type Dog implements Pet { - name(nameArg : String) : String - } - - type Bird implements Pet { - name(nameArg : String) : String - } - - type Cat implements Pet { - name(nameArg : String) : String - } - """) - def query = """ - { - pet { - name - ... on Dog { - name - } - ... CatFrag - } - } - - fragment CatFrag on Cat { - name - } - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == ['-Query.pet: Pet', - '--[Bird, Cat, Dog].name: String' - ] - } - - def "query with fragment and type condition merged together 2"() { - def graphQLSchema = TestUtil.schema(""" - type Query { - pet : Pet - } - interface Pet { - name : String - } - - type Dog implements Pet { - name : String - } - - type Bird implements Pet { - name : String - } - - type Cat implements Pet { - name : String - } - """) - def query = """ - { - pet { - name - ... on Dog { - name - } - ... CatFrag - } - } - - fragment CatFrag on Cat { - name - } - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == ['-Query.pet: Pet', - '--[Bird, Cat, Dog].name: String' - ] - } - - - def "query with interface in between"() { - def graphQLSchema = schema(""" - type Query { - pets: [Pet] - } - interface Pet { - name: String - friends: [Human] - } - type Human { - name: String - } - type Cat implements Pet { - name: String - friends: [Human] - } - type Dog implements Pet { - name: String - friends: [Human] - } - """) - def query = """ - { pets { friends {name} } } - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTree(tree) - - expect: - printedTree == ['Query.pets', - '[Cat, Dog].friends', - 'Human.name'] - } - - def "test interface fields with different output types (covariance) on the implementations"() { - def graphQLSchema = schema(""" - interface Animal { - parent: Animal - name: String - } - type Cat implements Animal { - name: String - parent: Cat - } - type Dog implements Animal { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Query { - animal: Animal - } - """) - - def query = """ - { - animal { - parent { - name - } - } - } - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == [ - "-Query.animal: Animal", - "--[Cat, Dog].parent: Cat, Dog", - "---[Cat, Dog].name: String", - ] - } - - def "__typename in unions get merged"() { - def graphQLSchema = schema(""" - - type Cat { - name: String - } - type Dog { - name: String - } - union CatOrDog = Cat | Dog - type Query { - animal: CatOrDog - } - """) - - def query = """ - { - animal { - ... on Cat {__typename} - ... on Dog {__typename} - } - } - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == [ - "-Query.animal: CatOrDog", - "--[Cat, Dog].__typename: String!", - ] - } - - def "test union fields with different output types (covariance) on the implementations"() { - def graphQLSchema = schema(""" - - interface Animal { - parent: CatOrDog - name: String - } - type Cat implements Animal{ - name: String - parent: Cat - } - type Dog implements Animal { - name: String - parent: Dog - isGoodBoy: Boolean - } - union CatOrDog = Cat | Dog - type Query { - animal: Animal - } - """) - - def query = """ - { - animal { - parent { - ... on Cat {name __typename } - ... on Dog {name __typename } - } - } - } - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == [ - "-Query.animal: Animal", - "--[Cat, Dog].parent: Cat, Dog", - "---[Cat, Dog].name: String", - "---[Cat, Dog].__typename: String!" - ] - } - - List printTree(ExecutableNormalizedOperation queryExecutionTree) { - def result = [] - Traverser traverser = Traverser.depthFirst({ it.getChildren() }) - traverser.traverse(queryExecutionTree.getTopLevelFields(), new TraverserVisitorStub() { - @Override - TraversalControl enter(TraverserContext context) { - ExecutableNormalizedField queryExecutionField = context.thisNode() - result << queryExecutionField.printDetails() - return TraversalControl.CONTINUE - } - }) - result - } - - List printTreeAndDirectives(ExecutableNormalizedOperation queryExecutionTree) { - def result = [] - Traverser traverser = Traverser.depthFirst({ it.getChildren() }) - traverser.traverse(queryExecutionTree.getTopLevelFields(), new TraverserVisitorStub() { - @Override - TraversalControl enter(TraverserContext context) { - ExecutableNormalizedField queryExecutionField = context.thisNode() - def queryDirectives = queryExecutionTree.getQueryDirectives(queryExecutionField) - - def fieldDetails = queryExecutionField.printDetails() - if (queryDirectives != null) { - def appliedDirectivesByName = queryDirectives.getImmediateAppliedDirectivesByName() - if (!appliedDirectivesByName.isEmpty()) { - fieldDetails += " " + printDirectives(appliedDirectivesByName) - } - } - result << fieldDetails - return TraversalControl.CONTINUE - } - - String printDirectives(Map> stringListMap) { - String s = stringListMap.collect { entry -> - entry.value.collect { - " @" + it.name + "(" + it.getArguments().collect { - it.name + " : " + '"' + it.value + '"' - }.join(",") + ")" - }.join(' ') - }.join(" ") - return s - } - }) - result - } - - static List printTreeWithLevelInfo(ExecutableNormalizedOperation queryExecutionTree, GraphQLSchema schema) { - def result = [] - Traverser traverser = Traverser.depthFirst({ it.getChildren() }) - traverser.traverse(queryExecutionTree.getTopLevelFields(), new TraverserVisitorStub() { - @Override - TraversalControl enter(TraverserContext context) { - ExecutableNormalizedField queryExecutionField = context.thisNode() - String prefix = "" - for (int i = 1; i <= queryExecutionField.getLevel(); i++) { - prefix += "-" - } - - def possibleOutputTypes = new LinkedHashSet() - for (fieldDef in queryExecutionField.getFieldDefinitions(schema)) { - possibleOutputTypes.add(GraphQLTypeUtil.simplePrint(fieldDef.type)) - } - - result << (prefix + queryExecutionField.printDetails() + ": " + possibleOutputTypes.join(", ")) - return TraversalControl.CONTINUE - } - }) - result - } - - def "field to normalized field is build"() { - def graphQLSchema = TestUtil.schema(""" - type Query{ - foo: Foo - } - type Foo { - subFoo: String - moreFoos: Foo - } - """) - def query = """ - {foo { ...fooData moreFoos { ...fooData }}} fragment fooData on Foo { subFoo } - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - def subFooField = (document.getDefinitions()[1] as FragmentDefinition).getSelectionSet().getSelections()[0] as Field - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def fieldToNormalizedField = tree.getFieldToNormalizedField() - - expect: - fieldToNormalizedField.keys().size() == 4 - fieldToNormalizedField.get(subFooField).size() == 2 - fieldToNormalizedField.get(subFooField)[0].level == 2 - fieldToNormalizedField.get(subFooField)[1].level == 3 - } - - def "normalized fields map with interfaces "() { - - String schema = """ - type Query{ - pets: [Pet] - } - interface Pet { - id: ID - } - type Cat implements Pet{ - id: ID - } - type Dog implements Pet{ - id: ID - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - pets { - id - } - } - - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - def petsField = (document.getDefinitions()[0] as OperationDefinition).getSelectionSet().getSelections()[0] as Field - def idField = petsField.getSelectionSet().getSelections()[0] as Field - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def fieldToNormalizedField = tree.getFieldToNormalizedField() - - - expect: - fieldToNormalizedField.size() == 2 - fieldToNormalizedField.get(petsField).size() == 1 - fieldToNormalizedField.get(petsField)[0].printDetails() == "Query.pets" - fieldToNormalizedField.get(idField).size() == 1 - fieldToNormalizedField.get(idField)[0].printDetails() == "[Cat, Dog].id" - - - } - - def "query with introspection fields"() { - String schema = """ - type Query{ - foo: String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - __typename - alias: __typename - __schema { queryType { name } } - __type(name: "Query") {name} - ...F - } - fragment F on Query { - __typename - alias: __typename - __schema { queryType { name } } - __type(name: "Query") {name} - } - - - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - def selections = (document.getDefinitions()[0] as OperationDefinition).getSelectionSet().getSelections() - def typeNameField = selections[0] as Field - def aliasedTypeName = selections[1] as Field - def schemaField = selections[2] as Field - def typeField = selections[3] as Field - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def fieldToNormalizedField = tree.getFieldToNormalizedField() - - expect: - fieldToNormalizedField.size() == 14 - fieldToNormalizedField.get(typeNameField)[0].objectTypeNamesToString() == "Query" - fieldToNormalizedField.get(typeNameField)[0].getFieldDefinitions(graphQLSchema) == [graphQLSchema.getIntrospectionTypenameFieldDefinition()] - fieldToNormalizedField.get(aliasedTypeName)[0].alias == "alias" - fieldToNormalizedField.get(aliasedTypeName)[0].getFieldDefinitions(graphQLSchema) == [graphQLSchema.getIntrospectionTypenameFieldDefinition()] - - fieldToNormalizedField.get(schemaField)[0].objectTypeNamesToString() == "Query" - fieldToNormalizedField.get(schemaField)[0].getFieldDefinitions(graphQLSchema) == [graphQLSchema.getIntrospectionSchemaFieldDefinition()] - - fieldToNormalizedField.get(typeField)[0].objectTypeNamesToString() == "Query" - fieldToNormalizedField.get(typeField)[0].getFieldDefinitions(graphQLSchema) == [graphQLSchema.getIntrospectionTypeFieldDefinition()] - - } - - def "fragment is used multiple times with different parents"() { - String schema = """ - type Query{ - pet: Pet - } - interface Pet { - name: String - } - type Dog implements Pet { - name: String - } - type Cat implements Pet { - name: String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - pet { - ... on Dog { - ...F - } - ... on Cat { - ...F - } - } - } - fragment F on Pet { - name - } - - - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == ['-Query.pet: Pet', - '--[Dog, Cat].name: String'] - } - - def "same result key but different field"() { - String schema = """ - type Query{ - pet: Pet - } - interface Pet { - name: String - } - type Dog implements Pet { - name: String - otherField: String - } - type Cat implements Pet { - name: String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - pet { - ... on Dog { - name: otherField - } - ... on Cat { - name - } - } - } - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTree(tree) - - expect: - printedTree == ['Query.pet', - 'name: Dog.otherField', - 'Cat.name'] - } - - def "normalized field to MergedField is build"() { - given: - def graphQLSchema = TestUtil.schema(""" - type Query{ - foo: Foo - } - type Foo { - subFoo: String - moreFoos: Foo - } - """) - def query = """ - {foo { ...fooData moreFoos { ...fooData }}} fragment fooData on Foo { subFoo } - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def normalizedFieldToMergedField = tree.getNormalizedFieldToMergedField() - Traverser traverser = Traverser.depthFirst({ it.getChildren() }) - List result = new ArrayList<>() - when: - traverser.traverse(tree.getTopLevelFields(), new TraverserVisitorStub() { - @Override - TraversalControl enter(TraverserContext context) { - ExecutableNormalizedField normalizedField = context.thisNode() - result.add(normalizedFieldToMergedField[normalizedField]) - return TraversalControl.CONTINUE - } - }) - - then: - result.size() == 4 - result.collect { it.getResultKey() } == ['foo', 'subFoo', 'moreFoos', 'subFoo'] - } - - def "coordinates to NormalizedField is build"() { - given: - def graphQLSchema = TestUtil.schema(""" - type Query{ - foo: Foo - } - type Foo { - subFoo: String - moreFoos: Foo - } - """) - def query = """ - {foo { ...fooData moreFoos { ...fooData }}} fragment fooData on Foo { subFoo } - """ - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - when: - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def coordinatesToNormalizedFields = tree.coordinatesToNormalizedFields - - then: - coordinatesToNormalizedFields.size() == 4 - coordinatesToNormalizedFields.get(coordinates("Query", "foo")).size() == 1 - coordinatesToNormalizedFields.get(coordinates("Foo", "moreFoos")).size() == 1 - coordinatesToNormalizedFields.get(coordinates("Foo", "subFoo")).size() == 2 - } - - def "handles mutations"() { - String schema = """ -type Query{ - animal: Animal -} - -type Mutation { - createAnimal: Query -} - -type Subscription { - subscribeToAnimal: Query -} - -interface Animal { - name: String - friends: [Friend] -} - -union Pet = Dog | Cat - -type Friend { - name: String - isBirdOwner: Boolean - isCatOwner: Boolean - pets: [Pet] -} - -type Bird implements Animal { - name: String - friends: [Friend] -} - -type Cat implements Animal{ - name: String - friends: [Friend] - breed: String -} - -type Dog implements Animal{ - name: String - breed: String - friends: [Friend] -} - -schema { - query: Query - mutation: Mutation - subscription: Subscription -} - - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String mutation = """ - mutation TestMutation{ - createAnimal { - animal { - name - otherName: name - ... on Cat { - name - friends { - ... on Friend { - isCatOwner - } - } - } - ... on Bird { - friends { - isBirdOwner - } - friends { - name - } - } - ... on Dog { - name - } - } - } - } - """ - - assertValidQuery(graphQLSchema, mutation) - - Document document = TestUtil.parseQuery(mutation) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == ['-Mutation.createAnimal: Query', - '--Query.animal: Animal', - '---[Bird, Cat, Dog].name: String', - '---otherName: [Bird, Cat, Dog].name: String', - '---Cat.friends: [Friend]', - '----Friend.isCatOwner: Boolean', - '---Bird.friends: [Friend]', - '----Friend.isBirdOwner: Boolean', - '----Friend.name: String'] - } - - private void assertValidQuery(GraphQLSchema graphQLSchema, String query, Map variables = [:]) { - GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build() - def ei = ExecutionInput.newExecutionInput(query).variables(variables).build() - assert graphQL.execute(ei).errors.size() == 0 - } - - def "normalized arguments"() { - given: - String schema = """ - type Query{ - dog(id:ID): Dog - } - type Dog { - name: String - search(arg1: Input1, arg2: Input1, arg3: Input1): Boolean - } - input Input1 { - foo: String - input2: Input2 - } - input Input2 { - bar: Int - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - query(\$var1: Input2, \$var2: Input1){dog(id: "123"){ - search(arg1: {foo: "foo", input2: {bar: 123}}, arg2: {foo: "foo", input2: \$var1}, arg3: \$var2) - }} - """ - - assertValidQuery(graphQLSchema, query) - Document document = TestUtil.parseQuery(query) - - def variables = [ - var1: [bar: 123], - var2: [foo: "foo", input2: [bar: 123]] - ] - // the normalized arg value should be the same regardless of how the value was provided - def expectedNormalizedArgValue = [foo: new NormalizedInputValue("String", parseValue('"foo"')), input2: new NormalizedInputValue("Input2", [bar: new NormalizedInputValue("Int", parseValue("123"))])] - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.of(variables)) - def topLevelField = tree.getTopLevelFields().get(0) - def secondField = topLevelField.getChildren().get(0) - def arg1 = secondField.getNormalizedArgument("arg1") - def arg2 = secondField.getNormalizedArgument("arg2") - def arg3 = secondField.getNormalizedArgument("arg3") - - then: - topLevelField.getNormalizedArgument("id").getTypeName() == "ID" - printAst(topLevelField.getNormalizedArgument("id").getValue()) == '"123"' - - arg1.getTypeName() == "Input1" - arg1.getValue() == expectedNormalizedArgValue - arg2.getTypeName() == "Input1" - arg2.value == expectedNormalizedArgValue - arg3.getTypeName() == "Input1" - arg3.value == expectedNormalizedArgValue - } - - def "arguments with absent variable values inside input objects"() { - given: - def schema = """ - type Query { - hello(arg: Arg, otherArg: String = "otherValue"): String - } - input Arg { - ids: [ID] = ["defaultId"] - } - """ - def graphQLSchema = TestUtil.schema(schema) - - def query = """ - query myQuery(\$varIds: [ID], \$otherVar: String) { - hello(arg: {ids: \$varIds}, otherArg: \$otherVar) - } - """ - - assertValidQuery(graphQLSchema, query) - def document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.emptyVariables()) - - then: - def topLevelField = tree.getTopLevelFields().get(0) - - def arg = topLevelField.getNormalizedArgument("arg") - arg == new NormalizedInputValue("Arg", [:]) - !topLevelField.normalizedArguments.containsKey("otherArg") - - topLevelField.resolvedArguments.get("arg") == [ids: ["defaultId"]] - topLevelField.resolvedArguments.get("otherArg") == "otherValue" - } - - def "arguments with null variable values"() { - given: - def schema = """ - type Query { - hello(arg: Arg, otherArg: String = "otherValue"): String - } - input Arg { - ids: [ID] = ["defaultId"] - } - """ - def graphQLSchema = TestUtil.schema(schema) - - def query = """ - query nadel_2_MyService_myQuery(\$varIds: [ID], \$otherVar: String) { - hello(arg: {ids: \$varIds}, otherArg: \$otherVar) - } - """ - - assertValidQuery(graphQLSchema, query) - def document = TestUtil.parseQuery(query) - - def variables = [ - varIds : null, - otherVar: null, - ] - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.of(variables)) - - then: - def topLevelField = tree.getTopLevelFields().get(0) - def arg = topLevelField.getNormalizedArgument("arg") - def otherArg = topLevelField.getNormalizedArgument("otherArg") - - arg == new NormalizedInputValue( - "Arg", - [ - ids: new NormalizedInputValue( - "[ID]", - null, - ), - ] - ) - otherArg == new NormalizedInputValue("String", null) - - topLevelField.resolvedArguments.get("arg") == [ids: null] - topLevelField.resolvedArguments.get("otherArg") == null - } - - def "normalized arguments with lists"() { - given: - String schema = """ - type Query{ - search(arg1:[ID!], arg2:[[Input1]], arg3: [Input1]): Boolean - } - input Input1 { - foo: String - input2: Input2 - } - input Input2 { - bar: Int - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = ''' - query($var1: [Input1], $var2: ID!){ - search(arg1:["1",$var2], arg2: [[{foo: "foo1", input2: {bar: 123}},{foo: "foo2", input2: {bar: 456}}]], arg3: $var1) - } - ''' - - def variables = [ - var1: [[foo: "foo3", input2: [bar: 789]]], - var2: "2", - ] - assertValidQuery(graphQLSchema, query, variables) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.of(variables)) - def topLevelField = tree.getTopLevelFields().get(0) - def arg1 = topLevelField.getNormalizedArgument("arg1") - def arg2 = topLevelField.getNormalizedArgument("arg2") - def arg3 = topLevelField.getNormalizedArgument("arg3") - - then: - arg1.typeName == "[ID!]" - arg1.value.collect { printAst(it) } == ['"1"', '"2"'] - arg2.typeName == "[[Input1]]" - arg2.value == [[ - [foo: new NormalizedInputValue("String", parseValue('"foo1"')), input2: new NormalizedInputValue("Input2", [bar: new NormalizedInputValue("Int", parseValue("123"))])], - [foo: new NormalizedInputValue("String", parseValue('"foo2"')), input2: new NormalizedInputValue("Input2", [bar: new NormalizedInputValue("Int", parseValue("456"))])] - ]] - - arg3.getTypeName() == "[Input1]" - arg3.value == [ - [foo: new NormalizedInputValue("String", parseValue('"foo3"')), input2: new NormalizedInputValue("Input2", [bar: new NormalizedInputValue("Int", parseValue("789"))])], - ] - - - } - - def "normalized arguments with lists 2"() { - given: - String schema = """ - type Query{ - search(arg1:[[Input1]] ,arg2:[[ID!]!]): Boolean - } - input Input1 { - foo: String - input2: Input2 - } - input Input2 { - bar: Int - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = ''' - query($var1: [Input1], $var2: [ID!]!){ - search(arg1: [$var1],arg2:[["1"],$var2] ) - } - ''' - - def variables = [ - var1: [[foo: "foo1", input2: [bar: 123]]], - var2: "2" - ] - assertValidQuery(graphQLSchema, query, variables) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.of(variables)) - def topLevelField = tree.getTopLevelFields().get(0) - def arg1 = topLevelField.getNormalizedArgument("arg1") - def arg2 = topLevelField.getNormalizedArgument("arg2") - - then: - arg1.typeName == "[[Input1]]" - arg1.value == [[ - [foo: new NormalizedInputValue("String", parseValue('"foo1"')), input2: new NormalizedInputValue("Input2", [bar: new NormalizedInputValue("Int", parseValue("123"))])], - ]] - arg2.typeName == "[[ID!]!]" - arg2.value.collect { outer -> outer.collect { printAst(it) } } == [['"1"'], ['"2"']] - } - - - def "recursive schema with a lot of objects"() { - given: - String schema = """ - type Query{ - foo: Foo - } - interface Foo { - field: Foo - id: ID - } - type O1 implements Foo { - field: Foo - id: ID - } - type O2 implements Foo { - field: Foo - id: ID - } - type O3 implements Foo { - field: Foo - id: ID - } - type O4 implements Foo { - field: Foo - id: ID - } - type O5 implements Foo { - field: Foo - id: ID - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = ''' - {foo{field{id}}foo{field{id}}} - ''' - assertValidQuery(graphQLSchema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.emptyVariables()) - - then: - tree.normalizedFieldToMergedField.size() == 3 - tree.fieldToNormalizedField.size() == 6 - println String.join("\n", printTree(tree)) - /** - * NF{Query.foo} -> NF{"O1...O5".field,} -> NF{O1...O5.id}*/ - } - - def "diverged fields"() { - given: - String schema = """ - type Query { - pets: Pet - } - interface Pet { - name: String - } - type Cat implements Pet { - name: String - catValue: Int - catFriend(arg: String): CatFriend - } - type CatFriend { - catFriendName: String - } - type Dog implements Pet { - name: String - dogValue: Float - dogFriend: DogFriend - } - type DogFriend { - dogFriendName: String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = ''' - {pets { - ... on Cat { - friend: catFriend(arg: "hello") { - catFriendName - }} - ... on Cat { - friend: catFriend(arg: "hello") { - catFriendName - }} - ... on Dog { - friend: dogFriend { - dogFriendName - }} - }} - ''' - assertValidQuery(graphQLSchema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - then: - // the two friend fields are not in on ENF - printedTree == ['-Query.pets: Pet', - '--friend: Cat.catFriend: CatFriend', - '---CatFriend.catFriendName: String', - '--friend: Dog.dogFriend: DogFriend', - '---DogFriend.dogFriendName: String'] - - tree.normalizedFieldToMergedField.size() == 5 - tree.fieldToNormalizedField.size() == 7 - } - - def "diverged fields 2"() { - given: - String schema = """ - type Query { - pets: Pet - } - interface Pet { - name(arg:String): String - } - type Cat implements Pet { - name(arg: String): String - } - - type Dog implements Pet { - name(arg: String): String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = ''' - {pets { - ... on Cat { - name(arg: "foo") - } - ... on Dog { - name(arg: "fooOther") - } - }} - ''' - assertValidQuery(graphQLSchema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - then: - /** - * the two name fields are not merged, because they are backed by different fields with different arguments - * If the arguments are the same, it would be one ENF. - */ - printedTree == ['-Query.pets: Pet', - '--Cat.name: String', - '--Dog.name: String' - ] - } - - - def "diverging fields with the same parent type on deeper level"() { - given: - def schema = schema(''' - type Query { - pets: [Pet] - } - interface Pet { - name: String - breed: String - friends: [Pet] - } - type Dog implements Pet { - name: String - dogBreed: String - breed: String - friends: [Pet] - - } - type Cat implements Pet { - catBreed: String - breed: String - name : String - friends: [Pet] - - } - ''') - /** - * Here F1 and F2 are allowed to diverge (backed by different field definitions) because the parent fields have - * different concrete parent: P1 has Dog, P2 has Cat. - */ - def query = ''' - { - pets { - ... on Dog { - friends { #P1 - name - ... on Dog { - breed: dogBreed #F1 - } - } - } - ... on Cat { - friends { #P2 - catFriendsName: name - ... on Dog { - breed #F2 - } - } - } - ... on Pet { - friends { - name - } - } - } - } - ''' - assertValidQuery(schema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, schema) - - then: - printedTree == ['-Query.pets: [Pet]', - '--Dog.friends: [Pet]', - '---[Cat, Dog].name: String', - '---breed: Dog.dogBreed: String', - '--Cat.friends: [Pet]', - '---catFriendsName: [Cat, Dog].name: String', - '---Dog.breed: String', - '---[Cat, Dog].name: String' - ] - } - - def "subselection different with different concrete parents"() { - given: - def schema = schema(''' - type Query { - pets: [Pet] - } - interface Pet { - name: String - breed: String - friends: [Pet] - } - type Dog implements Pet { - name: String - dogBreed: String - breed: String - friends: [Pet] - - } - type Cat implements Pet { - catBreed: String - breed: String - name : String - friends: [Pet] - - } - ''') - def query = ''' - { - pets { - ... on Dog { - friends { #P1 - name - } - } - ... on Cat { - friends { - otherName: name - } - } - friends { - breed - } - } - } - ''' - assertValidQuery(schema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, schema) - - then: - printedTree == ['-Query.pets: [Pet]', - '--Dog.friends: [Pet]', - '---[Cat, Dog].name: String', - '---[Cat, Dog].breed: String', - '--Cat.friends: [Pet]', - '---otherName: [Cat, Dog].name: String', - '---[Cat, Dog].breed: String', - ] - } - - - def "diverging non-composite fields"() { - given: - def schema = schema(''' - type Query { - pets: [Pet] - } - interface Pet { - name: String - breed: String - friends: [Pet] - } - type Dog implements Pet { - name: String - dogBreed: String - breed: String - friends: [Pet] - - } - type Cat implements Pet { - catBreed: String - breed: String - name : String - friends: [Pet] - - } - ''') - def query = ''' - { - pets { - ... on Dog { - breed: dogBreed - } - ... on Cat { - breed: catBreed - } - } - } - ''' - assertValidQuery(schema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, schema) - - then: - printedTree == ['-Query.pets: [Pet]', - '--breed: Dog.dogBreed: String', - '--breed: Cat.catBreed: String' - ] - } - - def "different children for different Interfaces"() { - given: - def schema = schema(''' - type Query { - pets: [Pet] - } - interface Pet { - name: String - breed: String - friends: [Pet] - } - - interface Mammal implements Pet { - name: String - breed: String - friends: [Pet] - } - type Turtle implements Pet { - name: String - breed: String - friends: [Pet] - } - type Dog implements Mammal & Pet { - name: String - dogBreed: String - breed: String - friends: [Pet] - } - type Cat implements Mammal & Pet { - catBreed: String - breed: String - name : String - friends: [Pet] - } - ''') - def query = ''' - { - pets { - ... on Cat { - friends { - catFriendName: name - } - } - ... on Dog { - friends { - dogFriendName: name - } - } - ... on Mammal { - friends { - name - } - } - ... on Pet { - friends { - breed - } - } - } - } - ''' - assertValidQuery(schema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, schema) - - then: - printedTree == ['-Query.pets: [Pet]', - '--Cat.friends: [Pet]', - '---catFriendName: [Cat, Dog, Turtle].name: String', - '---[Cat, Dog, Turtle].name: String', - '---[Cat, Dog, Turtle].breed: String', - '--Dog.friends: [Pet]', - '---dogFriendName: [Cat, Dog, Turtle].name: String', - '---[Cat, Dog, Turtle].name: String', - '---[Cat, Dog, Turtle].breed: String', - '--Turtle.friends: [Pet]', - '---[Cat, Dog, Turtle].breed: String' - ] - } - - def "diverging fields with Union as parent type"() { - given: - def schema = schema(''' - type Query { - pets: [DogOrCat] - } - type Dog { - name: String - dogBreed: String - breed: String - friends: [DogOrCat] - } - type Cat { - catBreed: String - breed: String - name : String - friends: [DogOrCat] - } - union DogOrCat = Dog | Cat - ''') - def query = ''' - { - pets { - ... on Dog { - friends { #P1 - ... on Dog { - breed: dogBreed #F1 - } - } - } - ... on Cat { - friends { #P2 - ... on Dog { - breed #F2 - } - } - } - } - } - ''' - assertValidQuery(schema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, schema) - - then: - printedTree == ['-Query.pets: [DogOrCat]', - '--Dog.friends: [DogOrCat]', - '---breed: Dog.dogBreed: String', - '--Cat.friends: [DogOrCat]', - '---Dog.breed: String' - ] - } - - def "union fields are not merged"() { - given: - def schema = schema(''' - type Query { - pets: [DogOrCat] - } - type Dog { - name: String - } - type Cat { - name: String - } - union DogOrCat = Dog | Cat - ''') - def query = ''' - { - pets { - ... on Dog { - name - } - ... on Cat { - name - } - } - } - ''' - assertValidQuery(schema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, schema) - - then: - printedTree == ['-Query.pets: [DogOrCat]', - '--Dog.name: String', - '--Cat.name: String' - ] - } - - def "union fields which are shared in an interface are merged"() { - given: - def schema = schema(''' - type Query { - pets: [DogOrCat] - } - interface Pet { - name: String - } - type Dog implements Pet{ - name: String - } - type Cat implements Pet{ - name: String - } - union DogOrCat = Dog | Cat - ''') - def query = ''' - { - pets { - ... on Dog { - name - } - ... on Cat { - name - } - } - } - ''' - assertValidQuery(schema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, schema) - - then: - printedTree == ['-Query.pets: [DogOrCat]', - '--[Dog, Cat].name: String' - ] - } - - def "fields which don't come from a shared interface are not merged"() { - given: - def schema = schema(''' - type Query { - pets: [Pet] - } - interface Pet { - name: String - } - type Dog implements Pet{ - name: String - breed: String - } - - type Cat implements Pet{ - name: String - breed: String - } - ''') - def query = ''' - { - pets { - ... on Dog { - breed - } - ... on Cat { - breed - } - }} - ''' - assertValidQuery(schema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, schema) - - then: - printedTree == ['-Query.pets: [Pet]', - '--Dog.breed: String', - '--Cat.breed: String' - ] - } - - def "fields are merged together on multiple level"() { - given: - def schema = schema(''' - type Query { - pets: [Pet] - } - interface Pet { - name: String - breed: String - friends: [Pet] - } - type Dog implements Pet { - name: String - dogBreed: String - breed: String - friends: [Pet] - - } - type Cat implements Pet { - catBreed: String - breed: String - name : String - friends: [Pet] - - } - - ''') - def query = ''' - { - pets { - ... on Dog { - friends { - ... on Dog { - friends { - name - } - } - ... on Cat { - friends { - name - } - } - } - } - ... on Cat { - friends { - ... on Dog { - friends { - name - } - } - ... on Cat { - friends { - name - } - } - } - } - } - } - ''' - assertValidQuery(schema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, schema) - - then: - printedTree == ['-Query.pets: [Pet]', - '--[Dog, Cat].friends: [Pet]', - '---[Dog, Cat].friends: [Pet]', - '----[Cat, Dog].name: String' - ] - } - - def "fields are not merged together because of different arguments on deeper level"() { - given: - def schema = schema(''' - type Query { - pets: [Pet] - } - interface Pet { - name(arg:String): String - breed: String - friends: [Pet] - } - type Dog implements Pet { - name(arg:String): String - dogBreed: String - breed: String - friends: [Pet] - - } - type Cat implements Pet { - catBreed: String - breed: String - name(arg:String) : String - friends: [Pet] - - } - - ''') - def query = ''' - { - pets { - ... on Dog { - friends { - ... on Dog { - friends { - name - } - } - ... on Cat { - friends { - name - } - } - } - } - ... on Cat { - friends { - ... on Dog { - friends { - name - } - } - ... on Cat { - friends { - name(arg: "not-be-merged") - } - } - } - } - } - } - ''' - assertValidQuery(schema, query) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, schema) - - then: - printedTree == ['-Query.pets: [Pet]', - '--Dog.friends: [Pet]', - '---[Dog, Cat].friends: [Pet]', - '----[Cat, Dog].name: String', - '--Cat.friends: [Pet]', - '---Dog.friends: [Pet]', - '----[Cat, Dog].name: String', - '---Cat.friends: [Pet]', - '----[Cat, Dog].name: String' - ] - } - - - def "skip/include is respected"() { - given: - String schema = """ - type Query { - pets: Pet - } - interface Pet { - name: String - } - type Cat implements Pet { - name: String - } - type Dog implements Pet { - name: String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = ''' - query($true: Boolean!,$false: Boolean!){pets { - ... on Cat { - cat_not: name @skip(if:true) - cat_not: name @skip(if:$true) - cat_yes_1: name @include(if:true) - cat_yes_2: name @skip(if:$false) - } - ... on Dog @include(if:$true) { - dog_no: name @include(if:false) - dog_no: name @include(if:$false) - dog_yes_1: name @include(if:$true) - dog_yes_2: name @skip(if:$false) - } - ... on Pet @skip(if:$true) { - not: name - } - ... on Pet @skip(if:$false) { - pet_name: name - } - }} - ''' - def variables = ["true": Boolean.TRUE, "false": Boolean.FALSE] - assertValidQuery(graphQLSchema, query, variables) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.of(variables)) - println String.join("\n", printTree(tree)) - def printedTree = printTree(tree) - - - then: - printedTree == ['Query.pets', - 'cat_yes_1: Cat.name', - 'cat_yes_2: Cat.name', - 'dog_yes_1: Dog.name', - 'dog_yes_2: Dog.name', - 'pet_name: [Cat, Dog].name', - ] - } - - - def "query directives are captured is respected"() { - given: - String schema = """ - directive @fieldDirective(target : String!) on FIELD - directive @fieldXDirective(target : String!) on FIELD - - type Query { - pets: Pet - } - interface Pet { - name: String - } - type Cat implements Pet { - name: String - } - type Dog implements Pet { - name: String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = ''' - query q { - pets { - ... on Cat { - cName : name @fieldDirective(target : "Cat.name") - } - ... on Dog { - dName : name @fieldDirective(target : "Dog.name") @fieldXDirective(target : "Dog.name") - } - ... on Pet { - pName : name @fieldDirective(target : "Pet.name") - } - }} - ''' - - def variables = [:] - assertValidQuery(graphQLSchema, query, variables) - Document document = TestUtil.parseQuery(query) - - when: - def tree = localCreateExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.of(variables)) - def printedTree = printTreeAndDirectives(tree) - - then: - printedTree == ['Query.pets', - 'cName: Cat.name @fieldDirective(target : "Cat.name")', - 'dName: Dog.name @fieldDirective(target : "Dog.name") @fieldXDirective(target : "Dog.name")', - 'pName: [Cat, Dog].name @fieldDirective(target : "Pet.name")', - ] - } - - def "missing argument"() { - given: - String schema = """ - type Query { - hello(arg: String): String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = '''{hello} ''' - assertValidQuery(graphQLSchema, query) - Document document = TestUtil.parseQuery(query) - when: - def tree = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables(graphQLSchema, document, null, RawVariables.emptyVariables()) - println String.join("\n", printTree(tree)) - def printedTree = printTree(tree) - - - then: - printedTree == ['Query.hello'] - tree.getTopLevelFields().get(0).getNormalizedArguments().isEmpty() - } - - def "reused field via fragments"() { - String schema = """ - type Query { - pet: Pet - } - type Pet { - owner: Person - emergencyContact: Person - } - type Person { - name: String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ -{ pet { - owner { ...personName } - emergencyContact { ...personName } -}} -fragment personName on Person { - name -} - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == ['-Query.pet: Pet', - '--Pet.owner: Person', - '---Person.name: String', - '--Pet.emergencyContact: Person', - '---Person.name: String' - ] - - } - - - def "test interface fields with three different output types (covariance) on the implementations"() { - def graphQLSchema = schema(""" - interface Animal { - parent: Animal - name: String - } - type Cat implements Animal { - name: String - parent: Cat - } - type Dog implements Animal { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Bird implements Animal { - name: String - parent: Bird - } - type Query { - animal: Animal - } - """) - - def query = """ - { - animal { - parent { - name - } - } - } - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == [ - "-Query.animal: Animal", - "--[Bird, Cat, Dog].parent: Bird, Cat, Dog", - "---[Bird, Cat, Dog].name: String", - ] - } - - def "covariants with union fields"() { - def graphQLSchema = schema(""" - type Query { - animal: Animal - } - interface Animal { - parent: DogOrCat - name: String - } - type Cat implements Animal { - name: String - parent: Cat - } - type Dog implements Animal { - name: String - parent: Dog - isGoodBoy: Boolean - } - union DogOrCat = Dog | Cat - """) - - def query = """ - { - animal { - parent { - __typename - } - } - } - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - - def tree = localCreateExecutableNormalizedOperation(graphQLSchema, document, null, CoercedVariables.emptyVariables()) - def printedTree = printTreeWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == [ - "-Query.animal: Animal", - "--[Cat, Dog].parent: Cat, Dog", - "---[Cat, Dog].__typename: String!", - ] - } - - def "query cannot exceed max depth"() { - String schema = """ - type Query { - animal: Animal - } - interface Animal { - name: String - friends: [Animal] - } - type Bird implements Animal { - name: String - friends: [Animal] - } - type Cat implements Animal { - name: String - friends: [Animal] - breed: String - } - type Dog implements Animal { - name: String - breed: String - friends: [Animal] - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - // We generate two less fields than the given depth - // One is due to the top level field - // One is due to the leaf selection - def animalSubselection = IntStream.rangeClosed(1, queryDepth - 2) - .mapToObj { - "" - } - .reduce("CHILD") { acc, value -> - acc.replace("CHILD", "friends { CHILD }") - } - .replace("CHILD", "name") - - // Note: there is a total of 51 fields here - String query = """ - { - animal { - $animalSubselection - } - } - """ - - def limit = 50 - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - when: - Exception exception - try { - ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables(), - ExecutableNormalizedOperationFactory.Options.defaultOptions().maxChildrenDepth(limit)) - } catch (Exception e) { - exception = e - } - - then: - if (queryDepth > limit) { - assert exception != null - assert exception.message.contains("depth exceeded") - assert exception.message.contains("> 50") - } else { - assert exception == null - } - - where: - _ | queryDepth - _ | 49 - _ | 50 - _ | 51 - } - - def "big query is fine as long as depth is under limit"() { - String schema = """ - type Query { - animal: Animal - } - interface Animal { - name: String - friends: [Friend] - } - union Pet = Dog | Cat - type Friend { - name: String - isBirdOwner: Boolean - isCatOwner: Boolean - pets: [Pet] - } - type Bird implements Animal { - name: String - friends: [Friend] - } - type Cat implements Animal { - name: String - friends: [Friend] - breed: String - } - type Dog implements Animal { - name: String - breed: String - friends: [Friend] - } - """ - - def garbageFields = IntStream.range(0, 1000) - .mapToObj { - """test_$it: friends { name }""" - } - .collect(Collectors.joining("\n")) - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - animal { - name - otherName: name - ... on Animal { - name - } - ... on Cat { - name - friends { - ... on Friend { - isCatOwner - pets { - ... on Dog { - name - } - } - } - } - } - ... on Bird { - friends { - isBirdOwner - } - friends { - name - pets { - ... on Cat { - breed - } - } - } - } - ... on Dog { - name - } - $garbageFields - } - } - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - when: - def result = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables(), - ExecutableNormalizedOperationFactory.Options.defaultOptions().maxChildrenDepth(5)) - - then: - noExceptionThrown() - } - - def "big query exceeding fields count"() { - String schema = """ - type Query { - animal: Animal - } - interface Animal { - name: String - friends: [Friend] - } - union Pet = Dog | Cat - type Friend { - name: String - isBirdOwner: Boolean - isCatOwner: Boolean - pets: [Pet] - } - type Bird implements Animal { - name: String - friends: [Friend] - } - type Cat implements Animal { - name: String - friends: [Friend] - breed: String - } - type Dog implements Animal { - name: String - breed: String - friends: [Friend] - } - """ - - def garbageFields = IntStream.range(0, 1000) - .mapToObj { - """test_$it: friends { name }""" - } - .collect(Collectors.joining("\n")) - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - animal { - name - otherName: name - ... on Animal { - name - } - ... on Cat { - name - friends { - ... on Friend { - isCatOwner - pets { - ... on Dog { - name - } - } - } - } - } - ... on Bird { - friends { - isBirdOwner - } - friends { - name - pets { - ... on Cat { - breed - } - } - } - } - ... on Dog { - name - } - $garbageFields - } - } - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - when: - def result = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables(), - ExecutableNormalizedOperationFactory.Options.defaultOptions().maxFieldsCount(2013)) - - then: - def e = thrown(AbortExecutionException) - e.message == "Maximum field count exceeded. 2014 > 2013" - } - - def "small query exceeding fields count"() { - String schema = """ - type Query { - hello: String - } - """ - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ {hello a1: hello}""" - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - when: - def result = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables(), - ExecutableNormalizedOperationFactory.Options.defaultOptions().maxFieldsCount(1)) - - then: - def e = thrown(AbortExecutionException) - e.message == "Maximum field count exceeded. 2 > 1" - - - } - - def "query not exceeding fields count"() { - String schema = """ - type Query { - dogs: [Dog] - } - type Dog { - name: String - breed: String - } - """ - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ {dogs{name breed }}""" - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - when: - def result = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables(), - ExecutableNormalizedOperationFactory.Options.defaultOptions().maxFieldsCount(3)) - - then: - notThrown(AbortExecutionException) - - - } - - def "query with meta fields exceeding fields count"() { - String schema = """ - type Query { - hello: String - } - """ - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = IntrospectionQuery.INTROSPECTION_QUERY - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - when: - def result = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables(), - ExecutableNormalizedOperationFactory.Options.defaultOptions().maxFieldsCount(188)) - println result.normalizedFieldToMergedField.size() - - then: - def e = thrown(AbortExecutionException) - e.message == "Maximum field count exceeded. 189 > 188" - } - - def "can capture depth and field count"() { - String schema = """ - type Query { - foo: Foo - } - - type Foo { - stop : String - bar : Bar - } - - type Bar { - stop : String - foo : Foo - } - """ - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = "{ foo { bar { foo { bar { foo { stop bar { stop }}}}}}}" - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - when: - def result = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables() - ) - - then: - result.getOperationDepth() == 7 - result.getOperationFieldCount() == 8 - } - - def "factory has a default max node count"() { - String schema = """ - type Query { - foo: Foo - } - type Foo { - foo: Foo - name: String - } - """ - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = "{ foo { ...F1}} " - int fragmentCount = 12 - for (int i = 1; i < fragmentCount; i++) { - query += """ - fragment F$i on Foo { - foo { ...F${i + 1} } - a: foo{ ...F${i + 1} } - b: foo{ ...F${i + 1} } - } - """ - } - query += """ - fragment F$fragmentCount on Foo{ - name - } - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - - when: - def result = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables() - ) - then: - def e = thrown(AbortExecutionException) - e.message == "Maximum field count exceeded. 100001 > 100000" - } - - def "default max fields can be changed "() { - String schema = """ - type Query { - foo: Foo - } - type Foo { - foo: Foo - name: String - } - """ - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = "{foo{foo{name}}} " - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - ExecutableNormalizedOperationFactory.Options.setDefaultOptions(ExecutableNormalizedOperationFactory.Options.defaultOptions().maxFieldsCount(2)) - - when: - def result = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables() - ) - then: - def e = thrown(AbortExecutionException) - e.message == "Maximum field count exceeded. 3 > 2" - cleanup: - ExecutableNormalizedOperationFactory.Options.setDefaultOptions(ExecutableNormalizedOperationFactory.Options.defaultOptions().maxFieldsCount(ExecutableNormalizedOperationFactory.Options.DEFAULT_MAX_FIELDS_COUNT)) - } - - def "fragments used multiple times and directives on it"() { - String schema = """ - type Query { - foo: String - } - """ - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = "{...F1 ...F1 } fragment F1 on Query { foo @include(if: true) } " - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - when: - def operation = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables() - ) - def rootField = operation.topLevelFields[0] - def directives = operation.getQueryDirectives(rootField) - def byName = directives.getImmediateDirectivesByName(); - then: - byName.size() == 1 - byName["include"].size() == 1 - byName["include"][0] instanceof GraphQLDirective - } - - def "fragments used multiple times and directives on it deeper"() { - String schema = """ - type Query { - foo: Foo - } - type Foo { - hello: String - } - """ - - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = "{foo{...F1 ...F1 } } fragment F1 on Foo { hello @include(if: true) hello @include(if:true) } " - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - when: - def operation = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - null, - RawVariables.emptyVariables() - ) - def enf = operation.topLevelFields[0].children[0] - def directives = operation.getQueryDirectives(enf) - def byName = directives.getImmediateDirectivesByName(); - then: - byName.size() == 1 - byName["include"].size() == 2 - byName["include"][0] instanceof GraphQLDirective - byName["include"][1] instanceof GraphQLDirective - byName["include"][0] != byName["include"][1] - } - - - private static ExecutableNormalizedOperation localCreateExecutableNormalizedOperation( - GraphQLSchema graphQLSchema, - Document document, - String operationName, - CoercedVariables coercedVariableValues - ) { - - def options = ExecutableNormalizedOperationFactory.Options.defaultOptions().deferSupport(deferSupport) - - return ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation(graphQLSchema, document, operationName, coercedVariableValues, options) - } - - private static ExecutableNormalizedOperation localCreateExecutableNormalizedOperationWithRawVariables( - GraphQLSchema graphQLSchema, - Document document, - String operationName, - RawVariables rawVariables - ) { - - def options = ExecutableNormalizedOperationFactory.Options.defaultOptions().deferSupport(deferSupport) - - return ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables( - graphQLSchema, - document, - operationName, - rawVariables, - options - ) - } -} - -class ExecutableNormalizedOperationFactoryTestWithDeferSupport extends ExecutableNormalizedOperationFactoryTest { - static { - deferSupport = true - } -} - -class ExecutableNormalizedOperationFactoryTestNoDeferSupport extends ExecutableNormalizedOperationFactoryTest { - static { - deferSupport = false - } -} diff --git a/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerDeferTest.groovy b/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerDeferTest.groovy deleted file mode 100644 index a56e337959..0000000000 --- a/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerDeferTest.groovy +++ /dev/null @@ -1,652 +0,0 @@ -package graphql.normalized - - -import graphql.GraphQL -import graphql.TestUtil -import graphql.execution.RawVariables -import graphql.language.AstPrinter -import graphql.language.AstSorter -import graphql.language.Document -import graphql.schema.GraphQLSchema -import graphql.schema.idl.RuntimeWiring -import graphql.schema.idl.TestLiveMockedWiringFactory -import graphql.schema.scalars.JsonScalar -import spock.lang.Specification - -import static graphql.ExecutionInput.newExecutionInput -import static graphql.language.OperationDefinition.Operation.QUERY -import static graphql.normalized.ExecutableNormalizedOperationToAstCompiler.compileToDocumentWithDeferSupport - -class ExecutableNormalizedOperationToAstCompilerDeferTest extends Specification { - VariablePredicate noVariables = new VariablePredicate() { - @Override - boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, String argName, NormalizedInputValue normalizedInputValue) { - return false - } - } - - String sdl = """ - directive @defer(if: Boolean, label: String) on FRAGMENT_SPREAD | INLINE_FRAGMENT - - type Query { - dog: Dog - animal: Animal - } - - interface Animal { - name: String - } - - type Dog implements Animal { - name: String - breed: String - owner: Person - } - - type Cat implements Animal { - name: String - breed: String - color: String - siblings: [Cat] - } - - type Fish implements Animal { - name: String - } - - type Person { - firstname: String - lastname: String - bestFriend: Person - } - """ - - def "simple defer"() { - String query = """ - query q { - dog { - name - ... @defer(label: "breed-defer") { - breed - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - dog { - name - ... @defer(label: "breed-defer") { - breed - } - } -} -''' - } - - def "simple defer with named spread"() { - String query = """ - query q { - dog { - name - ... on Dog @defer(label: "breed-defer") { - breed - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - dog { - name - ... @defer(label: "breed-defer") { - breed - } - } -} -''' - } - - def "multiple labels on the same field"() { - String query = """ - query q { - dog { - name - ... @defer(label: "breed-defer") { - breed - } - ... @defer(label: "breed-defer-2") { - breed - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - dog { - name - ... @defer(label: "breed-defer") { - breed - } - ... @defer(label: "breed-defer-2") { - breed - } - } -} -''' - } - - def "multiple defers without label on the same field"() { - String query = """ - query q { - dog { - name - ... @defer { - breed - } - ... @defer { - breed - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - dog { - name - ... @defer { - breed - } - ... @defer { - breed - } - } -} -''' - } - - def "field with and without defer"() { - String query = """ - query q { - dog { - ... @defer { - breed - } - ... { - breed - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - dog { - ... @defer { - breed - } - } -} -''' - } - - def "defer on type spread"() { - String query = """ - query q { - animal { - ... on Dog @defer { - breed - } - ... on Dog { - name - } - ... on Dog @defer(label: "owner-defer") { - owner { - firstname - } - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - animal { - ... on Dog @defer { - breed - } - ... on Dog { - name - } - ... on Dog @defer(label: "owner-defer") { - owner { - firstname - } - } - } -} -''' - } - - def "2 fragments on non-conditional fields"() { - String query = """ - query q { - animal { - ... on Cat @defer { - name - } - ... on Animal @defer { - name - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - animal { - ... @defer { - name - } - ... @defer { - name - } - } -} -''' - } - - def "2 fragments on conditional fields"() { - String query = """ - query q { - animal { - ... on Cat @defer { - breed - } - ... on Dog @defer { - breed - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - animal { - ... on Cat @defer { - breed - } - ... on Dog @defer { - breed - } - } -} -''' - } - - def "2 fragments on conditional fields with different labels"() { - String query = """ - query q { - animal { - ... on Cat @defer(label: "cat-defer") { - breed - } - ... on Dog @defer(label: "dog-defer") { - breed - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - animal { - ... on Cat @defer(label: "cat-defer") { - breed - } - ... on Dog @defer(label: "dog-defer") { - breed - } - } -} -''' - } - - def "fragments on conditional fields with different labels and repeating types"() { - String query = """ - query q { - animal { - ... on Cat @defer(label: "cat-defer-1") { - breed - } - ... on Cat @defer(label: "cat-defer-2") { - breed - } - ... on Dog @defer(label: "dog-defer") { - breed - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - animal { - ... on Cat @defer(label: "cat-defer-1") { - breed - } - ... on Cat @defer(label: "cat-defer-2") { - breed - } - ... on Dog @defer(label: "dog-defer") { - breed - } - } -} -''' - } - - def "nested defer"() { - String query = """ - query q { - animal { - ... on Cat @defer { - name - } - ... on Animal @defer { - name - ... on Dog @defer { - owner { - firstname - ... @defer { - lastname - } - ... @defer { - bestFriend { - firstname - ... @defer { - lastname - } - } - } - } - } - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - animal { - ... @defer { - name - } - ... @defer { - name - } - ... on Dog @defer { - owner { - firstname - ... @defer { - lastname - } - ... @defer { - bestFriend { - firstname - ... @defer { - lastname - } - } - } - } - } - } -} -''' - } - - def "multiple defers at the same level are preserved"() { - String query = """ - query q { - dog { - ... @defer { - name - } - ... @defer { - breed - } - ... @defer { - owner { - firstname - } - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - dog { - ... @defer { - name - } - ... @defer { - breed - } - ... @defer { - owner { - firstname - } - } - } -} -''' - } - - def "shared deferred selection compiles to one multi field fragment - #directive"() { - given: - String query = """ - query q { - dog { - name - ...Sidebar - ...Details - } - } - fragment Sidebar on Dog { - ...OwnerField - } - fragment Details on Dog { - ...OwnerField - } - fragment OwnerField on Dog { - owner { - ...OwnerData $directive - } - } - fragment OwnerData on Person { - firstname - lastname - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - - then: - printed == """{ - dog { - name - owner { - ... $directive { - firstname - lastname - } - } - } -} -""" - - where: - directive << ['@defer(label: "owner-data")', '@defer'] - } - - def "distinct defers of the same fragment compile separately - #firstDirective #secondDirective"() { - given: - String query = """ - query q { - dog { - ...DogData $firstDirective - ...DogData $secondDirective - } - } - fragment DogData on Dog { - name - breed - } - """ - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - - then: - printed == """{ - dog { - ... $firstDirective { - breed - name - } - ... $secondDirective { - breed - name - } - } -} -""" - - where: - firstDirective | secondDirective - '@defer(label: "first")' | '@defer(label: "second")' - '@defer' | '@defer' - } - - def "shared defer compiles once after accumulating narrow and broad type coverage"() { - given: - String query = ''' - query q { - animal { - ... on Dog { ...AnimalFields } - ... on Animal { ...AnimalFields } - } - } - fragment AnimalFields on Animal { - ...AnimalData @defer(label: "animal-data") - } - fragment AnimalData on Animal { - name - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def tree = createNormalizedTree(schema, query) - - when: - def result = compileToDocumentWithDeferSupport(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - - then: - printed == '''{ - animal { - ... @defer(label: "animal-data") { - name - } - } -} -''' - } - - private ExecutableNormalizedOperation createNormalizedTree(GraphQLSchema schema, String query, Map variables = [:]) { - assertValidQuery(schema, query, variables) - Document originalDocument = TestUtil.parseQuery(query) - - ExecutableNormalizedOperationFactory dependencyGraph = new ExecutableNormalizedOperationFactory() - def options = ExecutableNormalizedOperationFactory.Options.defaultOptions().deferSupport(true) - return dependencyGraph.createExecutableNormalizedOperationWithRawVariables( - schema, - originalDocument, - null, - RawVariables.of(variables), - options - ) - } - - private void assertValidQuery(GraphQLSchema graphQLSchema, String query, Map variables = [:]) { - GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build() - assert graphQL.execute(newExecutionInput().query(query).variables(variables)).errors.isEmpty() - } - - GraphQLSchema mkSchema(String sdl) { - def wiringFactory = new TestLiveMockedWiringFactory([JsonScalar.JSON_SCALAR]) - def runtimeWiring = RuntimeWiring.newRuntimeWiring() - .wiringFactory(wiringFactory).build() - TestUtil.schema(sdl, runtimeWiring) - } -} diff --git a/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerDirectivesTest.groovy b/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerDirectivesTest.groovy deleted file mode 100644 index b7928b4aed..0000000000 --- a/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerDirectivesTest.groovy +++ /dev/null @@ -1,194 +0,0 @@ -package graphql.normalized - -import graphql.schema.GraphQLSchema - -import static graphql.language.OperationDefinition.Operation.QUERY - -/** - * Test related to ENO and directives - */ -class ExecutableNormalizedOperationToAstCompilerDirectivesTest extends ENOToAstCompilerTestBase { - def bookSDL = ''' - directive @timeout(afterMillis : Int) on FIELD | FRAGMENT_DEFINITION | FRAGMENT_SPREAD | INLINE_FRAGMENT | QUERY - - directive @cached(forMillis : Int) on FIELD | FRAGMENT_DEFINITION | FRAGMENT_SPREAD | INLINE_FRAGMENT | QUERY - - directive @importance(place : String) on FIELD | FRAGMENT_DEFINITION | FRAGMENT_SPREAD | INLINE_FRAGMENT | QUERY - - type Query { - books(searchString : String) : [Book] - } - - type Book { - id : ID - title : String - review : String - } - ''' - - def "can extract variables or inline values for directives on the query"() { - def sdl = ''' - type Query { - foo(fooArg : String) : Foo - } - - type Foo { - bar(barArg : String) : String - } - - directive @optIn(to : [String!]!) repeatable on FIELD - ''' - - def query = ''' - query named($fooArgVar : String, $barArgVar : String, $skipVar : Boolean!, $optVar : [String!]!) { - foo(fooArg : $fooArgVar) @skip(if : $skipVar) { - bar(barArg : $barArgVar) @optIn(to : ["optToX"]) @optIn(to : $optVar) - } - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def eno = createNormalizedTree(schema, query, - [fooArgVar: "fooArgVar", barArgVar: "barArgVar", skipVar: false, optVar: ["optToY"]]) - - when: - def result = localCompileToDocument(schema, QUERY, "named", - eno.getTopLevelFields(), eno.getNormalizedFieldToQueryDirectives(), - allVariables) - def document = result.document - def vars = result.variables - def ast = printDoc(document) - - then: - vars == [v0: "barArgVar", v1: ["optToX"], v2: ["optToY"], v3: "fooArgVar", v4: false] - // - // the below is what ir currently produces but its WRONG - // fix up when the other tests starts to work - // - ast == '''query named($v0: String, $v1: [String!]!, $v2: [String!]!, $v3: String, $v4: Boolean!) { - foo(fooArg: $v3) @skip(if: $v4) { - bar(barArg: $v0) @optIn(to: $v1) @optIn(to: $v2) - } -} -''' - - - when: "it has no variables" - - - result = localCompileToDocument(schema, QUERY, "named", - eno.getTopLevelFields(), eno.getNormalizedFieldToQueryDirectives(), - noVariables) - document = result.document - vars = result.variables - ast = printDoc(document) - - then: - vars == [:] - ast == '''query named { - foo(fooArg: "fooArgVar") @skip(if: false) { - bar(barArg: "barArgVar") @optIn(to: ["optToX"]) @optIn(to: ["optToY"]) - } -} -''' - - } - - def "can handle quite a pathological fragment query as expected"() { - - def pathologicalQuery = ''' - fragment Details on Book @timeout(afterMillis: 25) @cached(forMillis : 25) @importance(place:"FragDef") { - title - review @timeout(afterMillis: 5) @cached(forMillis : 5) - ...InnerDetails @timeout(afterMillis: 26) - } - - fragment InnerDetails on Book @timeout(afterMillis: 27) { - review @timeout(afterMillis: 28) - } - - query Books @timeout(afterMillis: 30) @importance(place:"Operation") { - books(searchString: "monkey") { - id - ...Details @timeout(afterMillis: 20) - ...on Book @timeout(afterMillis: 15) { - review @timeout(afterMillis: 10) @cached(forMillis : 10) - } - } - } - ''' - - GraphQLSchema schema = mkSchema(bookSDL) - def eno = createNormalizedTree(schema, pathologicalQuery, [:]) - - when: - def result = localCompileToDocument(schema, QUERY, "Books", - eno.getTopLevelFields(), eno.getNormalizedFieldToQueryDirectives(), - allVariables) - def document = result.document - def vars = result.variables - def ast = printDoc(document) - - then: - vars == [v0:5, v1:5, v2:28, v3:10, v4:10, v5:"monkey"] - ast == '''query Books($v0: Int, $v1: Int, $v2: Int, $v3: Int, $v4: Int, $v5: String) { - books(searchString: $v5) { - id - review @cached(forMillis: $v1) @cached(forMillis: $v4) @timeout(afterMillis: $v0) @timeout(afterMillis: $v2) @timeout(afterMillis: $v3) - title - } -} -''' - - - when: "it has no variables" - - - result = localCompileToDocument(schema, QUERY, "Books", - eno.getTopLevelFields(), eno.getNormalizedFieldToQueryDirectives(), - noVariables) - document = result.document - vars = result.variables - ast = printDoc(document) - - then: - vars == [:] - ast == '''query Books { - books(searchString: "monkey") { - id - review @cached(forMillis: 5) @cached(forMillis: 10) @timeout(afterMillis: 5) @timeout(afterMillis: 28) @timeout(afterMillis: 10) - title - } -} -''' - - } - - def "merged fields with the same field will capture all directives"() { - def query = ''' - query Books { - books(searchString: "monkey") { - review @timeout(afterMillis: 10) @cached(forMillis : 10) - review @timeout(afterMillis: 100) @cached(forMillis : 100) - } - } - ''' - - GraphQLSchema schema = mkSchema(bookSDL) - def eno = createNormalizedTree(schema, query, [:]) - - when: - def result = localCompileToDocument(schema, QUERY, "Books", - eno.getTopLevelFields(), eno.getNormalizedFieldToQueryDirectives(), - noVariables) - def document = result.document - def ast = printDoc(document) - - then: - ast == '''query Books { - books(searchString: "monkey") { - review @cached(forMillis: 10) @cached(forMillis: 100) @timeout(afterMillis: 10) @timeout(afterMillis: 100) - } -} -''' - } -} diff --git a/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerTest.groovy b/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerTest.groovy deleted file mode 100644 index 8f4a0851ac..0000000000 --- a/src/test/groovy/graphql/normalized/ExecutableNormalizedOperationToAstCompilerTest.groovy +++ /dev/null @@ -1,2288 +0,0 @@ -package graphql.normalized - -import graphql.GraphQL -import graphql.TestUtil -import graphql.execution.RawVariables -import graphql.execution.directives.QueryAppliedDirective -import graphql.execution.directives.QueryDirectives -import graphql.language.AstPrinter -import graphql.language.AstSorter -import graphql.language.Document -import graphql.language.Field -import graphql.language.IntValue -import graphql.language.OperationDefinition -import graphql.language.StringValue -import graphql.parser.Parser -import graphql.schema.GraphQLSchema -import graphql.schema.idl.RuntimeWiring -import graphql.schema.idl.TestLiveMockedWiringFactory -import graphql.schema.scalars.JsonScalar -import spock.lang.Specification - -import static graphql.ExecutionInput.newExecutionInput -import static graphql.language.OperationDefinition.Operation.MUTATION -import static graphql.language.OperationDefinition.Operation.QUERY -import static graphql.language.OperationDefinition.Operation.SUBSCRIPTION -import static graphql.normalized.ExecutableNormalizedOperationToAstCompiler.compileToDocument -import static graphql.normalized.ExecutableNormalizedOperationToAstCompiler.compileToDocumentWithDeferSupport - -abstract class ENOToAstCompilerTestBase extends Specification { - static boolean deferSupport - - VariablePredicate noVariables = new VariablePredicate() { - - @Override - boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, QueryAppliedDirective queryAppliedDirective, String argName, NormalizedInputValue normalizedInputValue) { - return false - } - - @Override - boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, String argName, NormalizedInputValue normalizedInputValue) { - return false - } - } - - VariablePredicate jsonVariables = new VariablePredicate() { - @Override - boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, String argName, NormalizedInputValue normalizedInputValue) { - "JSON" == normalizedInputValue.unwrappedTypeName && normalizedInputValue.value != null - } - - @Override - boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, QueryAppliedDirective queryAppliedDirective, String argName, NormalizedInputValue normalizedInputValue) { - "JSON" == normalizedInputValue.unwrappedTypeName && normalizedInputValue.value != null - } - } - - VariablePredicate allVariables = new VariablePredicate() { - @Override - boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, String argName, NormalizedInputValue normalizedInputValue) { - return true - } - - @Override - boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, QueryAppliedDirective queryAppliedDirective, String argName, NormalizedInputValue normalizedInputValue) { - return true - } - } - - - static ExecutableNormalizedOperation createNormalizedTree(GraphQLSchema schema, String query, Map variables = [:]) { - assertValidQuery(schema, query, variables) - Document originalDocument = TestUtil.parseQuery(query) - - def options = ExecutableNormalizedOperationFactory.Options.defaultOptions().deferSupport(deferSupport) - return ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables(schema, originalDocument, null, RawVariables.of(variables), options) - } - - static List createNormalizedFields(GraphQLSchema schema, String query, Map variables = [:]) { - return createNormalizedTree(schema, query, variables).getTopLevelFields() - } - - static void assertValidQuery(GraphQLSchema graphQLSchema, String query, Map variables = [:]) { - GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build() - assert graphQL.execute(newExecutionInput().query(query).variables(variables)).errors.isEmpty() - } - - static GraphQLSchema mkSchema(String sdl) { - def wiringFactory = new TestLiveMockedWiringFactory([JsonScalar.JSON_SCALAR]) - def runtimeWiring = RuntimeWiring.newRuntimeWiring() - .wiringFactory(wiringFactory).build() - TestUtil.schema(sdl, runtimeWiring) - } - - static ExecutableNormalizedOperationToAstCompiler.CompilerResult localCompileToDocument( - GraphQLSchema schema, - OperationDefinition.Operation operationKind, - String operationName, - List topLevelFields, - VariablePredicate variablePredicate - ) { - return localCompileToDocument(schema, operationKind, operationName, topLevelFields, Map.of(), variablePredicate); - } - - static ExecutableNormalizedOperationToAstCompiler.CompilerResult localCompileToDocument( - GraphQLSchema schema, - OperationDefinition.Operation operationKind, - String operationName, - List topLevelFields, - Map normalizedFieldToQueryDirectives, - VariablePredicate variablePredicate - ) { - if (deferSupport) { - return compileToDocumentWithDeferSupport(schema, operationKind, operationName, topLevelFields, normalizedFieldToQueryDirectives, variablePredicate) - } - return compileToDocument(schema, operationKind, operationName, topLevelFields, normalizedFieldToQueryDirectives, variablePredicate) - } - - static Document sortDoc(Document doc) { - return new AstSorter().sort(doc) - } - - static printDoc(Document doc) { - return AstPrinter.printAst(sortDoc(doc)) - } -} - -/** - * Test code in here - helps in the base class - */ -abstract class ExecutableNormalizedOperationToAstCompilerTest extends ENOToAstCompilerTestBase { - - def "test pet interfaces"() { - String sdl = """ - type Query { - animal: Animal - } - interface Animal { - name: String - friends: [Friend] - } - - union Pet = Dog | Cat - - type Friend { - name: String - isBirdOwner: Boolean - isCatOwner: Boolean - pets: [Pet] - } - - type Bird implements Animal { - name: String - friends: [Friend] - } - - type Cat implements Animal { - name: String - friends: [Friend] - breed: String - mood: String - } - - type Dog implements Animal { - name: String - breed: String - friends: [Friend] - } - """ - - String query = """ - { - animal { - name - otherName: name - ... on Animal { - name - } - ... on Cat { - name - mood - friends { - ... on Friend { - isCatOwner - pets { - ... on Dog { - name - } - } - } - } - } - ... on Bird { - friends { - isBirdOwner - } - friends { - name - pets { - ... on Cat { - breed - } - } - } - } - ... on Dog { - name - breed - } - } - } - """ - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def printed = printDoc(result.document) - then: - printed == '''{ - animal { - name - otherName: name - ... on Bird { - friends { - isBirdOwner - name - pets { - ... on Cat { - breed - } - } - } - } - ... on Cat { - friends { - isCatOwner - pets { - ... on Dog { - name - } - } - } - mood - } - ... on Dog { - breed - } - } -} -''' - } - - def "test interface fields with different output types on the implementations"() { - def schema = TestUtil.schema(""" - interface Animal { - parent: Animal - name: String - } - type Cat implements Animal { - name: String - parent: Cat - } - type Dog implements Animal { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Query { - animal: Animal - } - """) - - String query = """ - { - animal { - parent { - name - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - printed == """{ - animal { - parent { - name - } - } -} -""" - } - - def "test interface fields with different output types on the implementations 2"() { - def schema = TestUtil.schema(""" - interface Animal { - parent: Animal - name: String - } - type Cat implements Animal { - name: String - parent: Cat - } - type Dog implements Animal { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Query { - animal: Animal - } - """) - - String query = """ - { - animal { - parent { - name - ... on Dog { - isGoodBoy - } - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - // printTreeWithLevelInfo(tree, schema).forEach { println it } - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - printed == """{ - animal { - parent { - name - ... on Dog { - isGoodBoy - } - } - } -} -""" - } - - def "test interface fields with different output types on the implementations 3"() { - // Tests we don't consider File as a possible option for parent on animals - def schema = TestUtil.schema(""" - interface Node { - parent: Node - } - type File implements Node { - name: ID - parent: File - } - interface Animal implements Node { - parent: Animal - name: String - } - type Cat implements Animal & Node { - name: String - parent: Cat - } - type Dog implements Animal & Node { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Query { - animal: Animal - file: File - } - """) - - String query = """ - { - animal { - parent { - name - ... on Dog { - isGoodBoy - } - ... on Node { - parent { - ... on Cat { - name - } - ... on Dog { - name - } - } - } - } - } - file { - name - ... on File { - parent { - name - } - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - // printTreeWithLevelInfo(tree, schema).forEach { println it } - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - printed == """{ - animal { - parent { - name - parent { - name - } - ... on Dog { - isGoodBoy - } - } - } - file { - name - parent { - name - } - } -} -""" - } - - def "test interface fields with different output types on the implementations 4"() { - // Tests we don't consider File as a possible option for parent on animals - def schema = TestUtil.schema(""" - interface Node { - parent: Node - } - type File implements Node { - name: String - parent: File - } - interface Animal implements Node { - parent: Animal - name: String - } - type Cat implements Animal & Node { - name: String - parent: Cat - } - type Dog implements Animal & Node { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Query { - animal: Animal - file: File - } - """) - - String query = """ - { - animal { - parent { - name - ... on Dog { - isGoodBoy - } - ...F1 - } - } - file { - name - ... on File { - ...F1 - parent { - name - } - } - } - } - fragment F1 on Node { - parent { - ... on Cat { - name - } - ... on Dog { - name - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - // printTreeWithLevelInfo(tree, schema).forEach { println it } - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - printed == """{ - animal { - parent { - name - parent { - name - } - ... on Dog { - isGoodBoy - } - } - } - file { - name - parent { - name - } - } -} -""" - } - - def "test named fragments on interface fields with different output types on implementations"() { - // Tests we don't consider File as a possible option for parent on animals - def schema = TestUtil.schema(""" - interface Node { - parent: Node - } - type File implements Node { - name: String - parent: File - } - interface Animal implements Node { - parent: Animal - name: String - } - type Cat implements Animal & Node { - name: String - parent: Cat - } - type Dog implements Animal & Node { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Query { - animal: Animal - file: File - } - """) - - String query = """ - { - animal { - parent { - name - ... on Dog { - isGoodBoy - } - ... on Node { - ...ParentName - } - } - } - file { - name - ... on File { - ...ParentName - } - } - } - - fragment ParentName on Node { - parent { - ... on Cat { - name - } - ... on Animal { - animal: name - } - ... on File { - name - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - // printTreeWithLevelInfo(tree, schema).forEach { println it } - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - printed == """{ - animal { - parent { - name - parent { - animal: name - ... on Cat { - name - } - } - ... on Dog { - isGoodBoy - } - } - } - file { - name - parent { - name - } - } -} -""" - } - - def "test unions always insert fragments for its subselections"() { - def schema = TestUtil.schema(""" - union Animal = Cat | Dog - type Cat { - name: String - parent: Cat - } - type Dog { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Query { - animal: Animal - } - """) - - String query = """ - { - animal { - ... on Cat { - __typename - name - } - ... on Dog { - name - } - ... on Dog { - isGoodBoy - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - // printTreeWithLevelInfo(tree, schema).forEach { println it } - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - printed == """{ - animal { - ... on Cat { - __typename - name - } - ... on Dog { - isGoodBoy - name - } - } -} -""" - } - - def "test typename in union when placed outside of fragments"() { - def schema = TestUtil.schema(""" - union Animal = Cat | Dog - type Cat { - name: String - parent: Cat - } - type Dog { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Query { - animal: Animal - } - """) - - String query = """ - { - animal { - __typename - ... on Cat { - name - } - ... on Dog { - name - } - ... on Dog { - isGoodBoy - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - // printTreeWithLevelInfo(tree, schema).forEach { println it } - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - printed == """{ - animal { - __typename - ... on Cat { - name - } - ... on Dog { - isGoodBoy - name - } - } -} -""" - } - - def "test typename in union when placed inside fragments but on all types conditions"() { - def schema = TestUtil.schema(""" - union Animal = Cat | Dog - type Cat { - name: String - parent: Cat - } - type Dog { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Query { - animal: Animal - } - """) - - String query = """ - { - animal { - ... on Cat { - __typename - name - } - ... on Dog { - __typename - name - } - ... on Dog { - isGoodBoy - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - // printTreeWithLevelInfo(tree, schema).forEach { println it } - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - // Perhaps the typename should be hoisted out of the fragments, but the impl currently generates - // -Query.animal: Animal - // --Cat.__typename: String! - // --Dog.__typename: String! - // --Cat.name: String - // --Dog.name: String - // --Dog.isGoodBoy: Boolean - printed == """{ - animal { - __typename - ... on Cat { - name - } - ... on Dog { - isGoodBoy - name - } - } -} -""" - } - - def "test print field for isGoodBoy when parent is changed to type Dog"() { - def schema = TestUtil.schema(""" - interface Animal { - parent: Animal - name: String - } - type Cat implements Animal { - name: String - parent: Cat - } - type Dog implements Animal { - name: String - parent: Dog - isGoodBoy: Boolean - } - type Query { - animal: Animal - } - """) - - String query = """ - { - animal { - ... on Dog { - parent { - isGoodBoy - } - } - ... on Animal { - parent { - name - } - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - // printTreeWithLevelInfo(tree, schema).forEach { println it } - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - // Note: the name field is spread across both fragments - printed == """{ - animal { - ... on Cat { - parent { - name - } - } - ... on Dog { - parent { - isGoodBoy - name - } - } - } -} -""" - } - - def "test non conditional fields from interfaces are not surrounded by fragments"() { - def schema = TestUtil.schema(""" - interface Animal { - parent: Animal - name: String - age: Int - location: String - } - type Cat implements Animal { - name: String - parent: Cat - age: Int - location: String - } - type Possum implements Animal { - name: String - parent: Animal - age: Int - location: String - } - type Rodent implements Animal { - name: String - parent: Animal - age: Int - location: String - } - type Deer implements Animal { - name: String - parent: Animal - age: Int - location: String - } - type Dog implements Animal { - name: String - parent: Dog - age: Int - location: String - isGoodBoy: Boolean - } - type Query { - animal: Animal - } - """) - - String query = """ - { - animal { - __typename - name - age - location - parent { - name - location - ... on Dog { - __typename - age - isGoodBoy - } - grandparent: parent { - name - age - ... on Cat { - catAge: age - } - } - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - // printTreeWithLevelInfo(tree, schema).forEach { println it } - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - // Ensure that age location name etc are not surrounded by fragments unnecessarily - printed == """{ - animal { - __typename - age - location - name - parent { - location - name - grandparent: parent { - age - name - ... on Cat { - catAge: age - } - } - ... on Dog { - __typename - age - isGoodBoy - } - } - } -} -""" - } - - def "test non conditional fields from interfaces are not surrounded by fragments 2"() { - def schema = TestUtil.schema(""" - type Issue { - fields: IssueField - } - interface IssueField { - id: ID! - fieldId: Int - fieldName: String - label: String! - } - type DateIssueField implements IssueField { - id: ID! - fieldId: Int - fieldName: String - label: String! - date: String - } - type OptionsIssueField implements IssueField { - id: ID! - fieldId: Int - fieldName: String - label: String! - } - type SpecialIssueField implements IssueField { - id: ID! - fieldId: Int - fieldName: String - label: String! - specialType: String - } - type Query { - issue: Issue - } - """) - - // This query also includes unnecessary fragments for fields that are already defined without fragments - String query = """ - { - issue { - fields { - __typename - id - fieldId - fieldName - label - ... on IssueField { - fieldId - } - ... on DateIssueField { - date - } - ... on SpecialIssueField { - id - fieldId - specialType - } - } - } - } - """ - - def tree = createNormalizedTree(schema, query) - // printTreeWithLevelInfo(tree, schema).forEach { println it } - - when: - def result = localCompileToDocument(schema, QUERY, null, tree.topLevelFields, noVariables) - def printed = printDoc(result.document) - - then: - // Ensure that __typename id fieldId fieldName etc. are not surrounded by fragments unnecessarily - printed == """{ - issue { - fields { - __typename - fieldId - fieldName - id - label - ... on DateIssueField { - date - } - ... on SpecialIssueField { - specialType - } - } - } -} -""" - } - - def "test a combination of plain objects and interfaces"() { - def sdl = ''' - type Query { - foo(arg: I): Foo - } - type Foo { - bar(arg: I): Bar - } - type Bar { - baz : Baz - } - interface Baz { - boo : String - } - type ABaz implements Baz { - boo : String - a : String - } - type BBaz implements Baz { - boo : String - b : String - } - input I { - arg1: String - } - ''' - def query = '''query { - foo(arg: {arg1 : "fooArg"}) { - bar(arg: {arg1 : "barArg"}) { - baz { - ... on ABaz { - boo - a - } - } - } - } -} - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - documentPrinted == '''{ - foo(arg: {arg1 : "fooArg"}) { - bar(arg: {arg1 : "barArg"}) { - baz { - ... on ABaz { - a - boo - } - } - } - } -} -''' - } - - def "test arguments"() { - def sdl = ''' - type Query { - foo1(arg: String): String - foo2(a: Int, b: Boolean, c: Float): String - } - ''' - def query = ''' { - foo1(arg: "hello") - foo2(a: 123, b: true, c: 123.45) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - documentPrinted == '''{ - foo1(arg: "hello") - foo2(a: 123, b: true, c: 123.45) -} -''' - } - - def "sets operation name"() { - def sdl = ''' - type Query { - foo1(arg: String): String - foo2(a: Int,b: Boolean, c: Float): String - } - ''' - def query = ''' { - foo1(arg: "hello") - foo2(a: 123, b: true, c: 123.45) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, "My_Op23", fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - documentPrinted == '''query My_Op23 { - foo1(arg: "hello") - foo2(a: 123, b: true, c: 123.45) -} -''' - } - - def "test input object arguments"() { - def sdl = ''' - type Query { - foo1(arg: I): String - } - input I { - arg1: String - arg2: Int - arg3: ID - arg4: Boolean - arg5: Float - nested: I - } - ''' - def query = '''{ - foo1(arg: { - arg1: "Hello" - arg2: 123 - arg3: "IDID" - arg4: false - arg5: 123.123 - nested: { - arg1: "Hello2" - arg2: 1234 - arg3: "IDID1" - arg4: null - arg5: null - } - }) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - documentPrinted == '''{ - foo1(arg: {arg1 : "Hello", arg2 : 123, arg3 : "IDID", arg4 : false, arg5 : 123.123, nested : {arg1 : "Hello2", arg2 : 1234, arg3 : "IDID1", arg4 : null, arg5 : null}}) -} -''' - } - - - def "test input object arguments 2"() { - def sdl = ''' - type Query { - foo1(arg: Outer): String - } - input Outer { - a : Inner - } - input Inner { - b : InnerInner - } - input InnerInner { - c : Int - d : String - } - ''' - def query = '''query something($v : Int){ - foo1(arg: { a : { b : { c :$v, d :"ast" }}}) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query, ["v": 123]) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, allVariables) - def documentPrinted = printDoc(result.document) - - then: - fields[0].normalizedArguments["arg"].value["a"].value["b"].value["c"].value.isEqualTo(IntValue.of(123)) - fields[0].normalizedArguments["arg"].value["a"].value["b"].value["d"].value.isEqualTo(StringValue.of("ast")) - documentPrinted.trim() == '''query ($v0: Outer) { - foo1(arg: $v0) -}''' - } - - def "test mutations"() { - def sdl = ''' - type Query { - foo1(arg: I): String - } - type Mutation { - foo1(arg: I): String - } - input I { - arg1: String - } - ''' - def query = '''mutation { - foo1(arg: { - arg1: "Mutation" - }) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - documentPrinted == '''mutation { - foo1(arg: {arg1 : "Mutation"}) -} -''' - } - - def "test subscriptions"() { - def sdl = ''' - type Query { - foo1(arg: I): String - } - type Subscription { - foo1(arg: I): String - } - input I { - arg1: String - } - ''' - def query = '''subscription { - foo1(arg: { - arg1: "Subscription" - }) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, SUBSCRIPTION, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - documentPrinted == '''subscription { - foo1(arg: {arg1 : "Subscription"}) -} -''' - } - - - def "test query directive"() { - def sdl = ''' - type Query { - foo1(arg: I): String - - } - type Subscription { - foo1(arg: I): DevOps - - } - input I { - arg1: String - } - - type DevOps{ - name: String - } - - directive @optIn(to : [String!]!) repeatable on FIELD - ''' - def query = '''subscription { - foo1 (arg: { - arg1: "Subscription" - }) @optIn(to: "foo") { - name @optIn(to: "devOps") - } - - - } - ''' - GraphQLSchema schema = mkSchema(sdl) - Document document = new Parser().parse(query) - ExecutableNormalizedOperation eno = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperationWithRawVariables(schema, document, null, RawVariables.emptyVariables()) - - - when: - def result = localCompileToDocument(schema, SUBSCRIPTION, null, eno.topLevelFields, eno.normalizedFieldToQueryDirectives, noVariables) - OperationDefinition operationDefinition = result.document.getDefinitionsOfType(OperationDefinition.class)[0] - def fooField = (Field) operationDefinition.selectionSet.children[0] - def nameField = (Field) fooField.selectionSet.children[0] - def documentPrinted = printDoc(result.document) - - then: - - fooField.directives.size() == 1 - nameField.directives.size() == 1 - documentPrinted == '''subscription { - foo1(arg: {arg1 : "Subscription"}) @optIn(to: ["foo"]) { - name @optIn(to: ["devOps"]) - } -} -''' - } - - def "test redundant inline fragments specified in original query"() { - def sdl = ''' - type Query { - foo1(arg: I): Foo - } - type Mutation { - foo1(arg: I): Foo - } - type Foo { - test: String - } - input I { - arg1: String - } - ''' - def query = '''mutation { - ... on Mutation { - foo1(arg: { - arg1: "Mutation" - }) { - ... on Foo { - test - } - } - } - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - documentPrinted == '''mutation { - foo1(arg: {arg1 : "Mutation"}) { - test - } -} -''' - } - - def "inserts inline fragment on interface types"() { - def sdl = ''' - type Query { - foo1(arg: I): Foo - } - type Mutation { - foo1(arg: I): Foo - } - interface Foo { - test: String - } - type AFoo implements Foo { - test: String - } - input I { - arg1: String - } - ''' - def query = '''query { - ... on Query { - foo1(arg: { - arg1: "Query" - }) { - ... on Foo { - test - } - } - } - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - then: - documentPrinted == '''{ - foo1(arg: {arg1 : "Query"}) { - test - } -} -''' - } - - def "introspection query can be printed __schema"() { - def sdl = ''' - type Query { - f: String - } - ''' - def query = ''' - query introspection_query { - __schema { - queryType { - fields(includeDeprecated: false) { - name - } - } - } - } - ''' - - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - then: - documentPrinted == '''{ - __schema { - queryType { - fields(includeDeprecated: false) { - name - } - } - } -} -''' - } - - def "introspection query can be printed __type"() { - def sdl = ''' - type Query { - f: String - } - ''' - def query = ''' - query introspection_query { - __type(name: "World") { - name - fields { - name - } - } - } - ''' - - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - then: - documentPrinted == '''{ - __type(name: "World") { - fields { - name - } - name - } -} -''' - } - - def "test is conditional when there is only one interface implementation"() { - def sdl = ''' - type Query { - foo1: Foo - } - interface Foo { - test: String - } - type AFoo implements Foo { - test: String - aFoo: String - } - ''' - def query = '''query { - ... on Query { - foo1 { - ... on Foo { - test - } - ... on AFoo { - aFoo - } - } - } - } - ''' - - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - then: - documentPrinted == '''{ - foo1 { - test - ... on AFoo { - aFoo - } - } -} -''' - } - - def "test is conditional when there is only one union implementation"() { - def sdl = ''' - type Query { - foo1: Foo - } - union Foo = AFoo - type AFoo { - test: String - aFoo: String - } - ''' - def query = '''{ - ... on Query { - foo1 { - ... on AFoo { - aFoo - } - } - } - } - ''' - - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - then: - documentPrinted == '''{ - foo1 { - ... on AFoo { - aFoo - } - } -} -''' - } - - def "handles concrete and abstract fields"() { - def sdl = ''' - type Query { - foo1(arg: I): Foo - } - type Mutation { - foo1(arg: I): Foo - } - interface Foo { - test: String - } - type AFoo implements Foo { - test: String - afoo: String - } - input I { - arg1: String - } - ''' - def query = '''query { - ... on Query { - foo1(arg: { - arg1: "Query" - }) { - test - ... on AFoo { - afoo - } - ... on AFoo { - __typename - } - } - } - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - then: - // Note: the typename field moves out of a fragment because AFoo is the only impl - documentPrinted == '''{ - foo1(arg: {arg1 : "Query"}) { - __typename - test - ... on AFoo { - afoo - } - } -} -''' - } - - def "handles typename outside fragment and inside fragment"() { - def sdl = ''' - type Query { - foo1(arg: I): Foo - } - type Mutation { - foo1(arg: I): Foo - } - interface Foo { - test: String - } - type AFoo implements Foo { - test: String - } - input I { - arg1: String - } - ''' - def query = '''query { - ... on Query { - foo1(arg: { - arg1: "Query" - }) { - __typename - test - ... on AFoo { - __typename - } - } - } - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - then: - // Note: the typename field moves out of a fragment because AFoo is the only impl - documentPrinted == '''{ - foo1(arg: {arg1 : "Query"}) { - __typename - test - } -} -''' - } - - def "handles typename inside fragment"() { - def sdl = ''' - type Query { - foo1(arg: I): Foo - } - type Mutation { - foo1(arg: I): Foo - } - interface Foo { - test: String - } - type AFoo implements Foo { - test: String - } - type BFoo implements Foo { - test: String - } - input I { - arg1: String - } - ''' - def query = '''{ - ... on Query { - foo1(arg: { - arg1: "Query" - }) { - test - ... on AFoo { - __typename - } - } - } - } - ''' - GraphQLSchema schema = TestUtil.schema(sdl) - def fields = createNormalizedFields(schema, query) - when: - def result = localCompileToDocument(schema, QUERY, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - then: - // Note: the typename field moves out of a fragment because AFoo is the only impl - documentPrinted == '''{ - foo1(arg: {arg1 : "Query"}) { - test - ... on AFoo { - __typename - } - } -} -''' - } - - def "test JSON when input is a variable"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg: JSON!): String - } - - scalar JSON - ''' - def query = '''mutation hello($var: JSON!) { - foo1(arg: $var) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - - def vars = [var: ["48x48": "hello"]] - def fields = createNormalizedFields(schema, query, vars) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, jsonVariables) - def documentPrinted = printDoc(result.document) - - then: - result.variables == [v0: ["48x48": "hello"]] - documentPrinted == '''mutation ($v0: JSON!) { - foo1(arg: $v0) -} -''' - } - - def "test JSON when input is a string variable"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg: JSON!): String - } - - scalar JSON - ''' - def query = '''mutation hello($var: JSON!) { - foo1(arg: $var) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - - def vars = [var: "hello there"] - def fields = createNormalizedFields(schema, query, vars) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, jsonVariables) - def documentPrinted = printDoc(result.document) - - then: - result.variables == [v0: "hello there"] - documentPrinted == '''mutation ($v0: JSON!) { - foo1(arg: $v0) -} -''' - } - - def "test JSON when input is an int variable"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg: JSON!): String - } - - scalar JSON - ''' - def query = '''mutation hello($var: JSON!) { - foo1(arg: $var) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - - def vars = [var: 1] - def fields = createNormalizedFields(schema, query, vars) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, jsonVariables) - def documentPrinted = printDoc(result.document) - - then: - result.variables == [v0: 1] - documentPrinted == '''mutation ($v0: JSON!) { - foo1(arg: $v0) -} -''' - } - - def "test JSON scalar when JSON arg is null"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg: JSON): String - } - - scalar JSON - ''' - def query = '''mutation { - foo1 - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - result.variables == [:] - documentPrinted == '''mutation { - foo1 -} -''' - } - - def "test JSON scalar when JSON arg is explicitly null"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg: JSON): String - } - - scalar JSON - ''' - def query = '''mutation { - foo1(arg: null) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - result.variables == [:] - documentPrinted == '''mutation { - foo1(arg: null) -} -''' - } - - def "test JSON scalar when input is inlined"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg: JSON!): String - } - - scalar JSON - ''' - def query = '''mutation { - foo1(arg: {one: "two", three: ["four", "five"]}) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, jsonVariables) - def documentPrinted = printDoc(result.document) - - then: - result.variables == [v0: [one: "two", three: ["four", "five"]]] - documentPrinted == '''mutation ($v0: JSON!) { - foo1(arg: $v0) -} -''' - } - - def "test JSON scalar when input is inlined, multiple JSON args"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg1: JSON!, arg2: [JSON!]): String - } - - scalar JSON - ''' - def query = '''mutation { - foo1(arg1: {one: "two", three: ["four", "five"]}, arg2: [{one: "two", three: ["four", "five"]}]) - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, jsonVariables) - def documentPrinted = printDoc(result.document) - - then: - result.variables.size() == 2 - result.variables['v0'] == [one: "two", three: ["four", "five"]] - result.variables['v1'] == [[one: "two", three: ["four", "five"]]] - documentPrinted == '''mutation ($v0: JSON!, $v1: [JSON!]) { - foo1(arg1: $v0, arg2: $v1) -} -''' - } - - def "test JSON scalar inside an input type"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg: InputWithJson): String - } - - input InputWithJson { - id: ID - json: JSON - } - scalar JSON - ''' - def query = '''mutation { - foo1(arg: {id: "ID-00", json: {name: "Zlatan", lastName: "Ibrahimoviç", clubs: ["MU", "Barsa", "Inter", "Milan"]}}) - } - ''' - - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, jsonVariables) - def documentPrinted = printDoc(result.document) - def vars = result.variables - - then: - vars.size() == 1 - vars['v0'] == [lastName: "Ibrahimoviç", name: "Zlatan", clubs: ["MU", "Barsa", "Inter", "Milan"]] - documentPrinted == '''mutation ($v0: JSON) { - foo1(arg: {id : "ID-00", json : $v0}) -} -''' - } - - def "test JSON scalar inside an input type, json value is explicitly null"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg: InputWithJson): String - } - - input InputWithJson { - id: ID - json: JSON - } - scalar JSON - ''' - def query = '''mutation { - foo1(arg: {id: "ID-00", json: null}) - } - ''' - - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - result.variables == [:] - documentPrinted == '''mutation { - foo1(arg: {id : "ID-00", json : null}) -} -''' - } - - def "test JSON scalar inside an input type, json value is null"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg: InputWithJson): String - } - - input InputWithJson { - id: ID - json: JSON - } - scalar JSON - ''' - def query = '''mutation { - foo1(arg: {id: "ID-00"}) - } - ''' - - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, noVariables) - def documentPrinted = printDoc(result.document) - - then: - result.variables == [:] - documentPrinted == '''mutation { - foo1(arg: {id : "ID-00"}) -} -''' - } - - def "test JSON scalar inside an input type, json key is illegal graphql input name"() { - def sdl = ''' - type Query { - foo: String - } - type Mutation { - foo1(arg: InputWithJson): String - } - - input InputWithJson { - id: ID - json: [JSON!] - } - scalar JSON - ''' - def query = '''mutation test($var: InputWithJson) { - foo1(arg: $var) - } - ''' - def variables = [var: [ - id : "ID-00", - json: [[name : "Zlatan", - lastName: "Ibrahimoviç", - clubs : ["MU", "Barsa", "Inter", "Milan", null], - "48x48" : "Zlatan_48x48.jpg", - "96x96" : null - ]] - ]] - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query, variables) - - when: - def result = localCompileToDocument(schema, MUTATION, null, fields, jsonVariables) - def documentPrinted = printDoc(result.document) - - then: - result.variables.size() == 1 - result.variables['v0'] == [[name : "Zlatan", - lastName: "Ibrahimoviç", - clubs : ["MU", "Barsa", "Inter", "Milan", null], - "48x48" : "Zlatan_48x48.jpg", - "96x96" : null - ]] - documentPrinted == '''mutation ($v0: [JSON!]) { - foo1(arg: {id : "ID-00", json : $v0}) -} -''' - } - - - def "test a combination of plain objects and interfaces with all variables and no variables"() { - def sdl = ''' - type Query { - listField1(arg: [Int]): String - listField2(arg: [I]): String - foo(arg: I): Foo - fooNonNull(arg: [I!]!): String - } - type Foo { - bar(arg: I): Bar - } - type Bar { - baz : Baz - } - interface Baz { - boo(arg: I) : String - } - type ABaz implements Baz { - boo(arg: I) : String - a : String - } - type BBaz implements Baz { - boo(arg: I) : String - b : String - } - input I { - arg1: String - arg2: [I] - } - ''' - def query = ''' - query whatEv { - listField1( arg : [1,2,3] ) - listField2( arg : [ {arg1 : "v1", arg2 : [ {arg1 : "v1.1"}] }, - {arg1 : "v2"}, - {arg1 : "v3"}] ) - - fooNonNull(arg: [{arg1 : "fooNonNullArg1"}, {arg1 : "fooNonNullArg2"}]) - - foo(arg: {arg1 : "fooArg"}) { - bar(arg: {arg1 : "barArg"}) { - baz { - ... on ABaz { - boo(arg : {arg1 : "barFragArg"}) - a - } - } - } - } - } - ''' - GraphQLSchema schema = mkSchema(sdl) - def fields = createNormalizedFields(schema, query) - - when: - def result = localCompileToDocument(schema, QUERY, "named", fields, allVariables) - def document = result.document - def vars = result.variables - def ast = printDoc(document) - - then: - - ast == '''query named($v0: [Int], $v1: [I], $v2: [I!]!, $v3: I, $v4: I, $v5: I) { - foo(arg: $v5) { - bar(arg: $v4) { - baz { - ... on ABaz { - a - boo(arg: $v3) - } - } - } - } - fooNonNull(arg: $v2) - listField1(arg: $v0) - listField2(arg: $v1) -} -''' - - vars == [v0: [1, 2, 3], - v1: [[arg1: "v1", arg2: [[arg1: "v1.1"]]], [arg1: "v2"], [arg1: "v3"]], - v2: [[arg1: "fooNonNullArg1"], [arg1: "fooNonNullArg2"]], - v3: [arg1: "barFragArg"], - v4: [arg1: "barArg"], - v5: [arg1: "fooArg"]] - - // - // Test the opposite - when we use no variables predicate everything should be inlined - // - when: "it has no variables" - - fields = createNormalizedFields(schema, query, [v0: [1, 2, 3], - v1: [[arg1: "v1", arg2: [[arg1: "v1.1"]]], [arg1: "v2"], [arg1: "v3"]], - v2: [[arg1: "fooNonNullArg1"], [arg1: "fooNonNullArg2"]], - v3: [arg1: "barFragArg"], - v4: [arg1: "barArg"], - v5: [arg1: "fooArg"]]) - - result = localCompileToDocument(schema, QUERY, "named", fields, noVariables) - document = result.document - vars = result.variables - ast = printDoc(document) - - then: "they should be inlined as values" - - // no vars created - vars == [:] - - // everything inlined - ast == '''query named { - foo(arg: {arg1 : "fooArg"}) { - bar(arg: {arg1 : "barArg"}) { - baz { - ... on ABaz { - a - boo(arg: {arg1 : "barFragArg"}) - } - } - } - } - fooNonNull(arg: [{arg1 : "fooNonNullArg1"}, {arg1 : "fooNonNullArg2"}]) - listField1(arg: [1, 2, 3]) - listField2(arg: [{arg1 : "v1", arg2 : [{arg1 : "v1.1"}]}, {arg1 : "v2"}, {arg1 : "v3"}]) -} -''' - } -} - -class ExecutableNormalizedOperationToAstCompilerTestWithDeferSupport extends ExecutableNormalizedOperationToAstCompilerTest { - static { - deferSupport = true - } -} - -class ExecutableNormalizedOperationToAstCompilerTestNoDeferSupport extends ExecutableNormalizedOperationToAstCompilerTest { - static { - deferSupport = false - } -} diff --git a/src/test/groovy/graphql/normalized/NormalizedDocumentTest.groovy b/src/test/groovy/graphql/normalized/NormalizedDocumentTest.groovy new file mode 100644 index 0000000000..170077f700 --- /dev/null +++ b/src/test/groovy/graphql/normalized/NormalizedDocumentTest.groovy @@ -0,0 +1,437 @@ +package graphql.normalized + +import graphql.ExecutionInput +import graphql.GraphQL +import graphql.GraphQLContext +import graphql.ParseAndValidate +import graphql.TestUtil +import graphql.execution.ExecutionContextBuilder +import graphql.execution.MergedField +import graphql.execution.conditional.ConditionalNodeDecision +import graphql.execution.preparsed.PreparsedDocumentEntry +import graphql.execution.preparsed.PreparsedDocumentProvider +import graphql.language.Field +import graphql.language.FragmentSpread +import graphql.schema.DataFetcher +import graphql.schema.DataFetchingFieldSelectionSetImpl +import graphql.validation.QueryComplexityLimits +import spock.lang.Specification + +import java.util.concurrent.CompletableFuture +import java.util.concurrent.atomic.AtomicInteger + +class NormalizedDocumentTest extends Specification { + def sdl = ''' + type Query { pet: Pet box: Box } + interface Pet { name: String child: Pet } + type Cat implements Pet { name: String child: Cat lives: Int } + type Dog implements Pet { name: String child: Dog nickname: String } + type Box { name: String count(value: Int = 42): Int child: Box } + ''' + def schema = TestUtil.schema(sdl) + + private static ExecutionInput input(String query, Map variables = [:], boolean enabled = true) { + ExecutionInput.newExecutionInput(query).variables(variables) + .graphQLContext([(NormalizedDocument.ENABLED): enabled]).build() + } + + private static executeOnSmallStack(GraphQL graphQL, ExecutionInput request) { + def future = new CompletableFuture() + def thread = new Thread(null, { + try { + future.complete(graphQL.execute(request)) + } catch (Throwable failure) { + future.completeExceptionally(failure) + } + } as Runnable, 'normalized-fragment-stack', 1024 * 1024) + thread.start() + future.get(30, java.util.concurrent.TimeUnit.SECONDS) + } + + private static runtimeSchema(String spec, Map> fetchers) { + def base = TestUtil.schema(spec) + def registry = graphql.schema.GraphQLCodeRegistry.newCodeRegistry(base.codeRegistry) + fetchers.each { type, fields -> + fields.each { name, fetcher -> registry.dataFetcher(graphql.schema.FieldCoordinates.coordinates(type, name), fetcher) } + } + base.transform { it.codeRegistry(registry.build()) } + } + + def "creation is opt-in and failures never expose a normalized document"() { + expect: + def result = ParseAndValidate.parseAndValidate(schema, input(query, [:], enabled)) + result.failure == invalid + (result.normalizedDocument != null) == created + + where: + query | enabled | invalid | created + '{ box { name } }' | false | false | false + '{ box { name } }' | true | false | true + '{ box { missing } }' | true | true | false + '{ box(unknown: {a: [1]}) { name } }' | true | true | false + '{ box { name ' | true | true | false + '{ box { ...F } } fragment F on Box { ...F }' | true | true | false + } + + def "one shared fragment body retains distinct references and symbolic conditions"() { + given: + def query = ''' + query A($first: Boolean!, $second: Boolean!) { + box { ...F @include(if: $first) ...F @include(if: $second) } + } + query B { box { ...F } } + fragment F on Box { x: count(value: 7) child { name } } + ''' + + when: + def result = ParseAndValidate.parseAndValidate(schema, input(query)) + def document = result.normalizedDocument + def box = document.fields.values().find { it.source.name == 'box' } + def scopes = document.selectionSets[box.selectionSetId].selections + + then: + result.errors.empty + document.operations*.source*.name == ['A', 'B'] + scopes.size() == 2 + scopes.every { it instanceof NormalizedSelectionScope } + scopes*.selectionSetId.unique().size() == 1 + scopes*.source*.getDirectives('include')*.first()*.arguments*.first()*.value*.name == ['first', 'second'] + scopes*.source.every { it instanceof FragmentSpread } + document.fields.size() == 5 + document.fields.values().find { it.source.alias == 'x' }.source.sourceLocation.line == 6 + document.fields.values().find { it.source.alias == 'x' }.parentTypeName == 'Box' + + when: + document.selectionSets.clear() + + then: + thrown(UnsupportedOperationException) + + when: + document.fields.clear() + + then: + thrown(UnsupportedOperationException) + } + + def "cached graph evaluates each execution's variables without storing resolved arguments"() { + given: + def captures = [] + def runtimeSchema = runtimeSchema(sdl, [Query: [box: { env -> + captures.add(env.selectionSet.immediateFields.collect { [it.resultKey, it.arguments] }) + null + } as DataFetcher]]) + def query = '''query($first: Boolean!, $second: Boolean!, $value: Int) { + box { ...F @include(if: $first) ...F @include(if: $second) } + } fragment F on Box { count(value: $value) }''' + PreparsedDocumentEntry cached + def validations = new AtomicInteger() + PreparsedDocumentProvider provider = { executionInput, compute -> + if (cached == null) { + validations.incrementAndGet() + cached = compute.apply(executionInput) + } + CompletableFuture.completedFuture(cached) + } + def graphQL = GraphQL.newGraphQL(runtimeSchema).preparsedDocumentProvider(provider).build() + + expect: + graphQL.execute(input(query, [first: false, second: true, value: 7])).errors.empty + graphQL.execute(input(query, [first: true, second: false, value: 9])).errors.empty + graphQL.execute(input(query, [first: false, second: false, value: 11])).errors.empty + validations.get() == 1 + cached.normalizedDocument != null + captures == [[['count', [value: 7]]], [['count', [value: 9]]], []] + } + + def "lookahead fails clearly without opt in or when a cache drops the graph"() { + given: + def runtimeSchema = runtimeSchema(sdl, [Query: [box: { env -> + env.selectionSet.immediateFields + null + } as DataFetcher]]) + PreparsedDocumentProvider provider = { executionInput, compute -> + def entry = compute.apply(executionInput) + CompletableFuture.completedFuture(dropGraph ? new PreparsedDocumentEntry(entry.document) : entry) + } + def graphQL = GraphQL.newGraphQL(runtimeSchema).preparsedDocumentProvider(provider).build() + + when: + def result = graphQL.execute(input('{ box { name } }', [:], enabled)) + + then: + result.errors.size() == 1 + result.errors[0].exception instanceof IllegalStateException + result.errors[0].message.contains('NormalizedDocument.ENABLED') + result.errors[0].message.contains('preparsed cache') + + where: + enabled | dropGraph + false | false + true | true + } + + def "every inspection including leaf and empty pattern requires the artifact"() { + given: + def context = ExecutionContextBuilder.newExecutionContextBuilder() + .executionId(graphql.execution.ExecutionId.generate()) + .graphQLSchema(schema).graphQLContext(GraphQLContext.getDefault()).build() + def selection = DataFetchingFieldSelectionSetImpl.newCollector(context, + MergedField.newMergedField(Field.newField('name').build()).build(), graphql.Scalars.GraphQLString, 1) + + when: + inspection(selection) + + then: + thrown(IllegalStateException) + + where: + inspection << [ + { it.immediateFields }, { it.fields }, { it.contains('') }, { it.getFields('') }, + { it.containsAnyOf('name') }, { it.containsAllOf('name') }, + { it.fieldsGroupedByResultKey }, { it.getFieldsGroupedByResultKey('name') } + ] + } + + def "concrete type variants are separate and children are collected on demand"() { + given: + def captured + def runtimeSchema = runtimeSchema(sdl, [Query: [pet: { env -> captured = env.selectionSet; null } as DataFetcher]]) + def graphQL = GraphQL.newGraphQL(runtimeSchema).build() + + when: + def result = graphQL.execute(input('''{ pet { + name + ... on Cat { label: name child { name } child { lives } } + ... on Dog { label: nickname child { nickname } } + } }''')) + + then: + result.errors.empty + captured.immediateFields*.fullyQualifiedName == ['Cat.name', 'Cat.name', 'Cat.child', 'Dog.name', 'Dog.nickname', 'Dog.child'] + captured.immediateFields*.resultKey == ['name', 'label', 'child', 'name', 'label', 'child'] + captured.immediateFields*.objectTypeNames == [['Cat'], ['Cat'], ['Cat'], ['Dog'], ['Dog'], ['Dog']] + captured.immediateFields.every { it.conditional && it.level == 2 && it.parentField == null } + def catChild = captured.immediateFields[2] + catChild.selectionSet.immediateFields*.fullyQualifiedName == ['Cat.name', 'Cat.lives'] + catChild.selectionSet.immediateFields.every { !it.conditional && it.level == 3 && it.parentField.is(catChild) } + captured.getFields('Cat.child/*')*.fullyQualifiedName == ['Cat.child/Cat.name', 'Cat.child/Cat.lives'] + captured.getFields('Dog.child/*')*.fullyQualifiedName == ['Dog.child/Dog.nickname'] + captured.getFieldsGroupedByResultKey('name')['name'].size() == 2 + } + + def "nested scope conditions combine and aliases retain first active order"() { + given: + def keys + def runtimeSchema = runtimeSchema(sdl, [Query: [box: { env -> keys = env.selectionSet.immediateFields*.resultKey; null } as DataFetcher]]) + def graphQL = GraphQL.newGraphQL(runtimeSchema).build() + def query = '''query($outer: Boolean!, $inner: Boolean!) { + box { + ... @include(if: $outer) { ...F @include(if: $inner) } + last: name + ...F + } + } fragment F on Box { first: name }''' + + expect: + graphQL.execute(input(query, [outer: outer, inner: inner])).errors.empty + keys == expected + + where: + outer | inner | expected + true | true | ['first', 'last'] + false | true | ['last', 'first'] + true | false | ['last', 'first'] + } + + def "custom conditional decisions are applied to scopes definitions and fields"() { + given: + def fields + def runtimeSchema = runtimeSchema(sdl + '\ndirective @hide on FIELD | FRAGMENT_SPREAD | FRAGMENT_DEFINITION | INLINE_FRAGMENT', + [Query: [box: { env -> fields = env.selectionSet.immediateFields*.name; null } as DataFetcher]]) + def graphQL = GraphQL.newGraphQL(runtimeSchema).build() + def query = '''{ box { name ...F @hide ...G ... @hide { count } child @hide { name } } } + fragment F on Box { count } + fragment G on Box @hide { child { name } }''' + def executionInput = input(query) + executionInput.graphQLContext.put(ConditionalNodeDecision, { env -> + env.directivesContainer.getDirectives('hide').empty + } as ConditionalNodeDecision) + + expect: + graphQL.execute(executionInput).errors.empty + fields == ['name'] + } + + def "preparsed entries survive serialization and reject mismatched documents"() { + given: + def result = ParseAndValidate.parseAndValidate(schema, input('{ box { name } }')) + def entry = new PreparsedDocumentEntry(result.document, result.errors, result.normalizedDocument) + def bytes = new ByteArrayOutputStream() + new ObjectOutputStream(bytes).withCloseable { it.writeObject(entry) } + + when: + def restored = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())).withCloseable { it.readObject() } + + then: + restored.document.is(restored.normalizedDocument.document) + restored.normalizedDocument.fields.size() == 2 + restored.normalizedDocument.fields.every { ast, field -> ast.is(field.source) } + + when: + new PreparsedDocumentEntry(TestUtil.parseQuery('{ box { name } }'), [], result.normalizedDocument) + + then: + thrown(graphql.AssertException) + } + + def "long fragment chains are collected iteratively and diamond references stay shared"() { + given: + def chain = (0..<1501).collect { index -> + "fragment F$index on Box { " + (index == 1500 ? 'name' : "...F${index + 1}") + ' }' + }.join('\n') + def captured + def runtimeSchema = runtimeSchema(sdl, [Query: [box: { env -> captured = env.selectionSet.immediateFields*.name; null } as DataFetcher]]) + def graphQL = GraphQL.newGraphQL(runtimeSchema).build() + + expect: + executeOnSmallStack(graphQL, input('{ box { ...F0 } }\n' + chain)).errors.empty + captured == ['name'] + + when: + def diamond = (0..<24).collect { index -> + "fragment F$index on Box { " + (index == 23 ? 'name' : "...F${index + 1} ...F${index + 1}") + ' }' + }.join('\n') + def request = input('{ box { ...F0 } }\n' + diamond) + request.graphQLContext.put(QueryComplexityLimits.KEY, QueryComplexityLimits.NONE) + def result = ParseAndValidate.parseAndValidate(runtimeSchema, request) + + then: + result.errors.empty + result.normalizedDocument.selectionSets.size() == 26 + result.normalizedDocument.fields.size() == 2 + graphQL.execute(request).errors.empty + captured == ['name'] + } + def "argument defaults follow each concrete definition and distinguish missing from null"() { + given: + def spec = """ + type Query { pet: Pet } + interface Pet { count(value: Int): Int } + type Cat implements Pet { count(value: Int = 1): Int } + type Dog implements Pet { count(value: Int = 2): Int } + """ + def captured + def runtime = runtimeSchema(spec, [Query: [pet: { env -> + captured = env.selectionSet.immediateFields.collectEntries { [(it.objectTypeNames[0]): it.arguments] } + null + } as DataFetcher]]) + def graphQL = GraphQL.newGraphQL(runtime).build() + + expect: + graphQL.execute(input('query($value: Int) { pet { count(value: $value) } }', variables)).errors.empty + captured == expected + + where: + variables | expected + [:] | [Cat: [value: 1], Dog: [value: 2]] + [value: null] | [Cat: [value: null], Dog: [value: null]] + [value: 7] | [Cat: [value: 7], Dog: [value: 7]] + } + + def "one cached artifact is safe across concurrent executions and disabled requests"() { + given: + def runtime = runtimeSchema(sdl, [Query: [box: { env -> + def selected = env.selectionSet.immediateFields + [count: selected.find { it.name == 'count' }.arguments.value, name: 'visible'] + } as DataFetcher]]) + def query = 'query($value: Int!, $visible: Boolean!) { box { count(value: $value) name @include(if: $visible) } }' + def prepared = ParseAndValidate.parseAndValidate(runtime, input(query)) + def entry = new PreparsedDocumentEntry(prepared.document, prepared.errors, prepared.normalizedDocument) + PreparsedDocumentProvider provider = { request, compute -> CompletableFuture.completedFuture(entry) } + def graphQL = GraphQL.newGraphQL(runtime).preparsedDocumentProvider(provider).build() + + when: + def pending = (1..20).collect { index -> + CompletableFuture.supplyAsync { + graphQL.execute(input(query, [value: index, visible: index % 2 == 0])) + } + } + def results = pending.collect { it.join() } + + then: + results.every { it.errors.empty } + results*.data*.box*.count == (1..20).toList() + results.withIndex().every { result, index -> result.data.box.containsKey('name') == ((index + 1) % 2 == 0) } + + when: + def disabled = graphQL.execute(input(query, [value: 1, visible: true], false)) + + then: + disabled.errors[0].exception instanceof IllegalStateException + } + + def "all operations are prepared and the selected operation supplies variable defaults"() { + given: + def observed + def runtime = runtimeSchema(sdl, [Query: [box: { env -> + observed = env.selectionSet.immediateFields*.arguments + null + } as DataFetcher]]) + def query = """ + query A(\$value: Int = 1) { box { ...F } } + query B(\$value: Int = 2) { box { ...F } } + fragment F on Box { count(value: \$value) } + """ + def graphQL = GraphQL.newGraphQL(runtime).build() + + expect: + graphQL.execute(input(query).transform { it.operationName(operation) }).errors.empty + observed == [[value: expected]] + + where: + operation | expected + 'A' | 1 + 'B' | 2 + } + + def "transformed execution contexts retain the prepared graph"() { + given: + def request = input('{ box { name } }') + def prepared = ParseAndValidate.parseAndValidate(schema, request) + def context = ExecutionContextBuilder.newExecutionContextBuilder() + .executionId(graphql.execution.ExecutionId.generate()).graphQLSchema(schema) + .graphQLContext(request.graphQLContext).document(prepared.document) + .normalizedDocument(prepared.normalizedDocument).build() + + expect: + context.transform { it.localContext('event') }.normalizedDocument.is(prepared.normalizedDocument) + } + + def "complexity rejection discards the optional graph"() { + given: + def request = input('{ box { name } }') + request.graphQLContext.put(QueryComplexityLimits.KEY, + QueryComplexityLimits.newLimitsWithDefaults().maxMergedFieldCount(1).build()) + + when: + def result = ParseAndValidate.parseAndValidate(schema, request) + + then: + result.errors.size() == 1 + result.normalizedDocument == null + } + + def "preparsed entries reject an artifact combined with validation errors"() { + given: + def prepared = ParseAndValidate.parseAndValidate(schema, input('{ box { name } }')) + def error = graphql.GraphqlErrorBuilder.newError().message('invalid').build() + + when: + new PreparsedDocumentEntry(prepared.document, [error], prepared.normalizedDocument) + + then: + thrown(graphql.AssertException) + } + +} diff --git a/src/test/groovy/graphql/normalized/ValueToVariableValueCompilerTest.groovy b/src/test/groovy/graphql/normalized/ValueToVariableValueCompilerTest.groovy deleted file mode 100644 index 0a168121e7..0000000000 --- a/src/test/groovy/graphql/normalized/ValueToVariableValueCompilerTest.groovy +++ /dev/null @@ -1,134 +0,0 @@ -package graphql.normalized - -import graphql.language.ArrayValue -import graphql.language.BooleanValue -import graphql.language.EnumValue -import graphql.language.FloatValue -import graphql.language.IntValue -import graphql.language.ListType -import graphql.language.NonNullType -import graphql.language.NullValue -import graphql.language.ObjectField -import graphql.language.ObjectValue -import graphql.language.StringValue -import graphql.language.TypeName -import graphql.schema.idl.TypeUtil -import spock.lang.Specification - -class ValueToVariableValueCompilerTest extends Specification { - - def "cam handle different ast Value objects"() { - - expect: - def actual = ValueToVariableValueCompiler.normalisedValueToVariableValue(value) - actual == expected - - where: - value | expected - NullValue.of() | null - IntValue.of(666) | 666 - StringValue.of("str") | "str" - BooleanValue.of(true) | true - FloatValue.of(999d) | 999d - EnumValue.of("enumValue") | "enumValue" - ObjectValue.newObjectValue() - .objectField(ObjectField.newObjectField().name("a").value(IntValue.of(64)).build()) - .objectField(ObjectField.newObjectField().name("b").value(StringValue.of("65")).build()) - .build() | [a: 64, b: "65"] - ArrayValue.newArrayValue() - .value(IntValue.of(9)) - .value(StringValue.of("10")) - .value(EnumValue.of("enum")) - .build() | [9, "10", "enum"] - - } - - def "can handle NormalizedInputValue values that are literals"() { - expect: - def niv = new NormalizedInputValue("TypeName", value) - def actual = ValueToVariableValueCompiler.normalisedValueToVariableValue(niv) - actual == expected - - where: - value | expected - NullValue.of() | null - IntValue.of(666) | 666 - StringValue.of("str") | "str" - BooleanValue.of(true) | true - FloatValue.of(999d) | 999d - EnumValue.of("enumValue") | "enumValue" - ObjectValue.newObjectValue() - .objectField(ObjectField.newObjectField().name("a").value(IntValue.of(64)).build()) - .objectField(ObjectField.newObjectField().name("b").value(StringValue.of("65")).build()) - .build() | [a: 64, b: "65"] - ArrayValue.newArrayValue() - .value(IntValue.of(9)) - .value(StringValue.of("10")) - .value(EnumValue.of("enum")) - .build() | [9, "10", "enum"] - - - } - - def "can handle NormalizedInputValue values that are not literals"() { - expect: - def niv = new NormalizedInputValue("TypeName", value) - def actual = ValueToVariableValueCompiler.normalisedValueToVariableValue(niv) - actual == expected - - where: - value | expected - null | null - [IntValue.of(666), IntValue.of(664)] | [666, 664] - [a: IntValue.of(666), b: IntValue.of(664)] | [a: 666, b: 664] - - // at present we dont handle straight up java objects like 123 because - // the ValueResolver never produces them during - // ValueResolver.getNormalizedVariableValues say - this is debatable behavior - // but for now this is what we do - } - - def "can handle NormalizedInputValue values that are NIV with null members"() { - expect: - def niv = new NormalizedInputValue("TypeName", value) - def actual = ValueToVariableValueCompiler.normalisedValueToVariableValue(niv) - actual == expected - - where: - value | expected - [a: new NormalizedInputValue("X", IntValue.of(666)), b: new NormalizedInputValue("X", null)] | [a: 666, b: null] - [new NormalizedInputValue("X", IntValue.of(666)), new NormalizedInputValue("X", null)] | [666, null] - } - - - def "can print variables as expected"() { - expect: - def niv = new NormalizedInputValue(typeName, value) - def actual = ValueToVariableValueCompiler.normalizedInputValueToVariable(niv, varCount) - actual.value == expectedValue - actual.variableReference.name == expectedVarName - actual.definition.name == expectedVarName - // compare actual type - def actualType = actual.definition.type - actualType.isEqualTo(expectedType) - if (actualType instanceof NonNullType || actualType instanceof ListType) { - actualType.type.isEqualTo(expectedType.type) - } - TypeUtil.simplePrint(actualType) == typeName - - where: - value | varCount | typeName | expectedValue | expectedVarName | expectedType - NullValue.newNullValue().build() | 1 | "ID" | null | "v1" | new TypeName("ID") - IntValue.of(666) | 2 | "Int!" | 666 | "v2" | new NonNullType(new TypeName("Int")) - StringValue.of("str") | 3 | "String" | "str" | "v3" | new TypeName("String") - BooleanValue.of(true) | 4 | "Boolean!" | true | "v4" | new NonNullType(new TypeName("Boolean")) - FloatValue.of(999d) | 5 | "Float" | 999d | "v5" | new TypeName("Float") - EnumValue.of("enumValue") | 6 | "Foo!" | "enumValue" | "v6" | new NonNullType(new TypeName("Foo")) - ["a": IntValue.of(64), - "b": IntValue.of(65)] | 7 | "ObjectType" | [a: 64, b: 65] | "v7" | new TypeName("ObjectType") - [StringValue.of("9"), - StringValue.of("10"), - StringValue.of("11")] | 8 | "[String]" | ["9", "10", "11"] | "v8" | new ListType((new TypeName("String"))) - - } -} diff --git a/src/test/groovy/graphql/normalized/VariableAccumulatorTest.groovy b/src/test/groovy/graphql/normalized/VariableAccumulatorTest.groovy deleted file mode 100644 index 377907b771..0000000000 --- a/src/test/groovy/graphql/normalized/VariableAccumulatorTest.groovy +++ /dev/null @@ -1,46 +0,0 @@ -package graphql.normalized - -import graphql.language.IntValue -import graphql.language.NullValue -import graphql.language.StringValue -import graphql.language.TypeName -import spock.lang.Specification - -class VariableAccumulatorTest extends Specification { - - def alwaysTruePredicate = new VariablePredicate() { - @Override - boolean shouldMakeVariable(ExecutableNormalizedField executableNormalizedField, String argName, NormalizedInputValue normalizedInputValue) { - return true - } - } - - def "can build itself handing null values"() { - when: - VariableAccumulator accumulator = new VariableAccumulator(alwaysTruePredicate) - accumulateData(accumulator) - - def variablesMap = accumulator.getVariablesMap() - then: - variablesMap == [v0: "hello", v1: 666, v2: null, v3: null] - } - - def "can build variable definitions"() { - when: - VariableAccumulator accumulator = new VariableAccumulator(alwaysTruePredicate) - accumulateData(accumulator) - def names = accumulator.getVariableDefinitions().collect { vd -> vd.name } - def typeNames = accumulator.getVariableDefinitions().collect { vd -> (vd.type as TypeName).name } - - then: - names == ["v0", "v1", "v2", "v3"] - typeNames == ["String", "Int", "Int", "String"] - } - - private void accumulateData(VariableAccumulator accumulator) { - accumulator.accumulateVariable(new NormalizedInputValue("String", StringValue.of("hello"))) - accumulator.accumulateVariable(new NormalizedInputValue("Int", IntValue.of(666))) - accumulator.accumulateVariable(new NormalizedInputValue("Int", NullValue.of())) - accumulator.accumulateVariable(new NormalizedInputValue("String", null)) - } -} diff --git a/src/test/groovy/graphql/normalized/nf/NormalizedDocumentFactoryTest.groovy b/src/test/groovy/graphql/normalized/nf/NormalizedDocumentFactoryTest.groovy deleted file mode 100644 index 5ef79cd417..0000000000 --- a/src/test/groovy/graphql/normalized/nf/NormalizedDocumentFactoryTest.groovy +++ /dev/null @@ -1,251 +0,0 @@ -package graphql.normalized.nf - -import graphql.ExecutionInput -import graphql.GraphQL -import graphql.TestUtil -import graphql.language.Document -import graphql.schema.GraphQLSchema -import graphql.schema.GraphQLTypeUtil -import graphql.util.TraversalControl -import graphql.util.Traverser -import graphql.util.TraverserContext -import graphql.util.TraverserVisitorStub -import spock.lang.Specification - -class NormalizedDocumentFactoryTest extends Specification { - - def "test"() { - String schema = """ -type Query{ - animal: Animal -} -interface Animal { - name: String - friends: [Friend] -} - -union Pet = Dog | Cat - -type Friend { - name: String - isBirdOwner: Boolean - isCatOwner: Boolean - pets: [Pet] -} - -type Bird implements Animal { - name: String - friends: [Friend] -} - -type Cat implements Animal{ - name: String - friends: [Friend] - breed: String -} - -type Dog implements Animal{ - name: String - breed: String - friends: [Friend] -} - - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = """ - { - animal{ - name - otherName: name - ... on Animal { - name - } - ... on Cat { - name - friends { - ... on Friend { - isCatOwner - pets { - ... on Dog { - name - } - } - } - } - } - ... on Bird { - friends { - isBirdOwner - } - friends { - name - pets { - ... on Cat { - breed - } - } - } - } - ... on Dog { - name - } - }} - - """ - - assertValidQuery(graphQLSchema, query) - - Document document = TestUtil.parseQuery(query) - def tree = NormalizedDocumentFactory.createNormalizedDocument(graphQLSchema, document) - def printedTree = printDocumentWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree == ['-Query.animal: Animal', - '--[Bird, Cat, Dog].name: String', - '--otherName: [Bird, Cat, Dog].name: String', - '--Cat.friends: [Friend]', - '---Friend.isCatOwner: Boolean', - '---Friend.pets: [Pet]', - '----Dog.name: String', - '--Bird.friends: [Friend]', - '---Friend.isBirdOwner: Boolean', - '---Friend.name: String', - '---Friend.pets: [Pet]', - '----Cat.breed: String' - ] - } - - def "document with skip/include with variables"() { - String schema = """ - type Query{ - foo: Foo - } - type Foo { - bar: Bar - name: String - } - type Bar { - baz: String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = ''' - query ($skip: Boolean!, $include: Boolean!) { - foo { - name - bar @skip(if: $skip) { - baz @include(if: $include) - } - } - } - ''' - - - assertValidQuery(graphQLSchema, query, [skip: false, include: true]) - - Document document = TestUtil.parseQuery(query) - def tree = NormalizedDocumentFactory.createNormalizedDocument(graphQLSchema, document) - def printedTree = printDocumentWithLevelInfo(tree, graphQLSchema) - - expect: - printedTree.join("\n") == '''variables: [skip:false, include:false] --Query.foo: Foo ---Foo.name: String ---Foo.bar: Bar -variables: [skip:true, include:false] --Query.foo: Foo ---Foo.name: String -variables: [skip:false, include:true] --Query.foo: Foo ---Foo.name: String ---Foo.bar: Bar ----Bar.baz: String -variables: [skip:true, include:true] --Query.foo: Foo ---Foo.name: String''' - } - - def "document with custom directives"() { - String schema = """ - directive @cache(time: Int!) on FIELD - type Query{ - foo: Foo - } - type Foo { - bar: Bar - name: String - } - type Bar { - baz: String - } - """ - GraphQLSchema graphQLSchema = TestUtil.schema(schema) - - String query = ''' - query { - foo { - name - bar @cache(time:100) { - baz - } - bar @cache(time:200) { - baz - } - - } - } - ''' - - - assertValidQuery(graphQLSchema, query, [skip: false, include: true]) - - Document document = TestUtil.parseQuery(query) - def normalizedDocument = NormalizedDocumentFactory.createNormalizedDocument(graphQLSchema, document) - def rootField = normalizedDocument.getSingleNormalizedOperation().getRootFields().get(0) - def bar = rootField.getChildren().get(1) - - expect: - bar.getAstDirectives().size() == 2 - } - - - private void assertValidQuery(GraphQLSchema graphQLSchema, String query, Map variables = [:]) { - GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build() - def ei = ExecutionInput.newExecutionInput(query).variables(variables).build() - assert graphQL.execute(ei).errors.size() == 0 - } - - static List printDocumentWithLevelInfo(NormalizedDocument normalizedDocument, GraphQLSchema schema) { - def result = [] - for (NormalizedDocument.NormalizedOperationWithAssumedSkipIncludeVariables normalizedOperationWithAssumedSkipIncludeVariables : normalizedDocument.normalizedOperations) { - NormalizedOperation normalizedOperation = normalizedOperationWithAssumedSkipIncludeVariables.normalizedOperation; - if (normalizedOperationWithAssumedSkipIncludeVariables.assumedSkipIncludeVariables != null) { - result << "variables: " + normalizedOperationWithAssumedSkipIncludeVariables.assumedSkipIncludeVariables - } - Traverser traverser = Traverser.depthFirst({ it.getChildren() }) - traverser.traverse(normalizedOperation.getRootFields(), new TraverserVisitorStub() { - @Override - TraversalControl enter(TraverserContext context) { - NormalizedField normalizedField = context.thisNode() - String prefix = "" - for (int i = 1; i <= normalizedField.getLevel(); i++) { - prefix += "-" - } - - def possibleOutputTypes = new LinkedHashSet() - for (fieldDef in normalizedField.getFieldDefinitions(schema)) { - possibleOutputTypes.add(GraphQLTypeUtil.simplePrint(fieldDef.type)) - } - - result << (prefix + normalizedField.printDetails() + ": " + possibleOutputTypes.join(", ")) - return TraversalControl.CONTINUE - } - }) - } - result - } - - -} diff --git a/src/test/groovy/graphql/normalized/nf/NormalizedOperationToAstCompilerTest.groovy b/src/test/groovy/graphql/normalized/nf/NormalizedOperationToAstCompilerTest.groovy deleted file mode 100644 index c797392fe3..0000000000 --- a/src/test/groovy/graphql/normalized/nf/NormalizedOperationToAstCompilerTest.groovy +++ /dev/null @@ -1,257 +0,0 @@ -package graphql.normalized.nf - -import graphql.GraphQL -import graphql.TestUtil -import graphql.language.AstPrinter -import graphql.language.AstSorter -import graphql.language.OperationDefinition -import graphql.parser.Parser -import graphql.schema.GraphQLSchema -import spock.lang.Specification - -import static graphql.ExecutionInput.newExecutionInput - -class NormalizedOperationToAstCompilerTest extends Specification { - - - def "test pet interfaces"() { - String sdl = """ - type Query { - animal: Animal - } - interface Animal { - name: String - friends: [Friend] - } - - union Pet = Dog | Cat - - type Friend { - name: String - isBirdOwner: Boolean - isCatOwner: Boolean - pets: [Pet] - } - - type Bird implements Animal { - name: String - friends: [Friend] - } - - type Cat implements Animal { - name: String - friends: [Friend] - breed: String - mood: String - } - - type Dog implements Animal { - name: String - breed: String - friends: [Friend] - } - """ - - String query = """ - { - animal { - name - otherName: name - ... on Animal { - name - } - ... on Cat { - name - mood - friends { - ... on Friend { - isCatOwner - pets { - ... on Dog { - name - } - } - } - } - } - ... on Bird { - friends { - isBirdOwner - } - friends { - name - pets { - ... on Cat { - breed - } - } - } - } - ... on Dog { - name - breed - } - } - } - """ - GraphQLSchema schema = TestUtil.schema(sdl) - assertValidQuery(schema, query) - def normalizedDocument = NormalizedDocumentFactory.createNormalizedDocument(schema, Parser.parse(query)) - def normalizedOperation = normalizedDocument.getSingleNormalizedOperation() - when: - def result = NormalizedOperationToAstCompiler.compileToDocument(schema, normalizedOperation) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - animal { - name - otherName: name - ... on Bird { - friends { - isBirdOwner - name - pets { - ... on Cat { - breed - } - } - } - } - ... on Cat { - friends { - isCatOwner - pets { - ... on Dog { - name - } - } - } - mood - } - ... on Dog { - breed - } - } -} -''' - } - - def "print custom directives"() { - String sdl = """ - directive @cache(time: Int!) on FIELD - type Query{ - foo: Foo - } - type Foo { - bar: Bar - name: String - } - type Bar { - baz: String - } - """ - - String query = ''' - query { - foo { - name - bar @cache(time:100) { - baz - } - bar @cache(time:200) { - baz - } - - } - } - ''' - - GraphQLSchema schema = TestUtil.schema(sdl) - assertValidQuery(schema, query) - def normalizedDocument = NormalizedDocumentFactory.createNormalizedDocument(schema, Parser.parse(query)) - def normalizedOperation = normalizedDocument.getSingleNormalizedOperation() - when: - def result = NormalizedOperationToAstCompiler.compileToDocument(schema, normalizedOperation) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''{ - foo { - bar @cache(time: 100) @cache(time: 200) { - baz - } - name - } -} -''' - } - - - def "print one root field"() { - def sdl = """ - type Query { - foo: Foo - } - type Foo { - bar: String - } - """ - def query = ''' - { foo { bar } } - ''' - GraphQLSchema schema = TestUtil.schema(sdl) - assertValidQuery(schema, query) - def normalizedDocument = NormalizedDocumentFactory.createNormalizedDocument(schema, Parser.parse(query)) - def normalizedOperation = normalizedDocument.getSingleNormalizedOperation() - def rootField = normalizedOperation.getRootFields().get(0) - when: - def result = NormalizedOperationToAstCompiler.compileToDocument(schema, schema.getObjectType("Query"), rootField, "myOperation", OperationDefinition.Operation.QUERY) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''query myOperation { - foo { - bar - } -} -''' - } - - def "print list of root fields"() { - def sdl = """ - type Query { - foo: Foo - } - type Foo { - bar: String - } - """ - def query = ''' - { foo { bar } foo2: foo { bar } } - ''' - GraphQLSchema schema = TestUtil.schema(sdl) - assertValidQuery(schema, query) - def normalizedDocument = NormalizedDocumentFactory.createNormalizedDocument(schema, Parser.parse(query)) - def normalizedOperation = normalizedDocument.getSingleNormalizedOperation() - def rootFields = normalizedOperation.getRootFields() - when: - def result = NormalizedOperationToAstCompiler.compileToDocument(schema, schema.getObjectType("Query"), rootFields, "myOperation", OperationDefinition.Operation.QUERY) - def printed = AstPrinter.printAst(new AstSorter().sort(result.document)) - then: - printed == '''query myOperation { - foo { - bar - } - foo2: foo { - bar - } -} -''' - } - - - private void assertValidQuery(GraphQLSchema graphQLSchema, String query, Map variables = [:]) { - GraphQL graphQL = GraphQL.newGraphQL(graphQLSchema).build() - assert graphQL.execute(newExecutionInput().query(query).variables(variables)).errors.isEmpty() - } - - -} diff --git a/src/test/groovy/graphql/schema/DataFetchingFieldSelectionSetImplTest.groovy b/src/test/groovy/graphql/schema/DataFetchingFieldSelectionSetImplTest.groovy index ff80ad9b32..794b0ccf70 100644 --- a/src/test/groovy/graphql/schema/DataFetchingFieldSelectionSetImplTest.groovy +++ b/src/test/groovy/graphql/schema/DataFetchingFieldSelectionSetImplTest.groovy @@ -2,6 +2,7 @@ package graphql.schema import graphql.ExecutionInput import graphql.GraphQL +import graphql.normalized.NormalizedDocument import graphql.StarWarsData import graphql.TestUtil import graphql.schema.idl.RuntimeWiring @@ -56,7 +57,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def "glob pattern matching works"() { - def ei = ExecutionInput.newExecutionInput(starWarsQuery).build() + def ei = ExecutionInput.newExecutionInput(starWarsQuery).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = starWarsGraphql.execute(ei) expect: @@ -179,7 +180,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def "test getting sub selected fields by name"() { when: - def ei = ExecutionInput.newExecutionInput(relayQuery).build() + def ei = ExecutionInput.newExecutionInput(relayQuery).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = relayGraphql.execute(ei) then: @@ -227,7 +228,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def "test getting sub selected fields by glob"() { when: - def ei = ExecutionInput.newExecutionInput(relayQuery).build() + def ei = ExecutionInput.newExecutionInput(relayQuery).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = relayGraphql.execute(ei) then: @@ -257,7 +258,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def "test that aster aster is equal to get all"() { when: - def ei = ExecutionInput.newExecutionInput(relayQuery).build() + def ei = ExecutionInput.newExecutionInput(relayQuery).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = relayGraphql.execute(ei) then: @@ -317,7 +318,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def "fields are returned in pre order"() { when: - def ei = ExecutionInput.newExecutionInput(relayQuery).build() + def ei = ExecutionInput.newExecutionInput(relayQuery).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = relayGraphql.execute(ei) then: @@ -352,7 +353,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def "immediate fields followed by fields are computed"() { when: - def ei = ExecutionInput.newExecutionInput(relayQuery).build() + def ei = ExecutionInput.newExecutionInput(relayQuery).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = relayGraphql.execute(ei) then: @@ -513,7 +514,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { } ''' - def ei = ExecutionInput.newExecutionInput(query).build() + def ei = ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = petSchema.execute(ei) then: er.errors.isEmpty() @@ -534,12 +535,12 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def selectedFields = petSelectionSet.getFields("name") then: - selectedFields.size() == 3 - assertTheyAreExpected(selectedFields, ["[Bird, Cat, Dog].name", "n1:Cat.name", "n2:Cat.name"]) + selectedFields.size() == 5 + assertTheyAreExpected(selectedFields, ["Bird.name", "Cat.name", "Dog.name", "n1:Cat.name", "n2:Cat.name"]) def byResultKey = petSelectionSet.getFieldsGroupedByResultKey("name") byResultKey.size() == 3 - assertTheyAreExpected(byResultKey["name"], ["[Bird, Cat, Dog].name"]) + assertTheyAreExpected(byResultKey["name"], ["Bird.name", "Cat.name", "Dog.name"]) assertTheyAreExpected(byResultKey["n1"], ["n1:Cat.name"]) assertTheyAreExpected(byResultKey["n2"], ["n2:Cat.name"]) @@ -556,8 +557,8 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { selectedFields.sort(byName()) then: - selectedFields.size() == 1 - assertTheyAreExpected(selectedFields, ["[Bird, Cat, Dog].lead"]) + selectedFields.size() == 3 + assertTheyAreExpected(selectedFields, ["Bird.lead", "Cat.lead", "Dog.lead"]) // we can work our sub selection from them as well selectedFields[0].getSelectionSet().contains("material") !selectedFields[0].getSelectionSet().contains("rubbish") @@ -568,9 +569,9 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { selectedFields.sort(byName()) then: - selectedFields.size() == 1 //one for the Cat and Dog and Bird entries - assertTheyAreExpected(selectedFields, ["Lead.material"]) - selectedFields[0].getParentField().getFullyQualifiedName() == "[Bird, Cat, Dog].lead" + selectedFields.size() == 3 + assertTheyAreExpected(selectedFields, ["Lead.material", "Lead.material", "Lead.material"]) + selectedFields[0].getParentField().getFullyQualifiedName() == "Bird.lead" // parents can have computed selection sets def birdLead = selectedFields[0].getParentField() @@ -580,7 +581,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { when: selectedFields = petSelectionSet.getFields("name", "lead**") then: - selectedFields.size() == 5 + selectedFields.size() == 11 } def "aliasing returns values as selected fields"() { @@ -596,18 +597,18 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { } ''' - def ei = ExecutionInput.newExecutionInput(query).build() + def ei = ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = petSchema.execute(ei) then: er.errors.isEmpty() def selectedFields = petSelectionSet.getFields("name") - selectedFields.size() == 2 - assertTheyAreExpected(selectedFields, ["[Bird, Cat, Dog].name", "aliasedName:Dog.name"]) + selectedFields.size() == 4 + assertTheyAreExpected(selectedFields, ["Bird.name", "Cat.name", "Dog.name", "aliasedName:Dog.name"]) def getFields = petSelectionSet.getFields() - getFields.size() == 2 - assertTheyAreExpected(getFields, ["[Bird, Cat, Dog].name", "aliasedName:Dog.name"]) + getFields.size() == 4 + assertTheyAreExpected(getFields, ["Bird.name", "Cat.name", "Dog.name", "aliasedName:Dog.name"]) def byResultKey = petSelectionSet.getFieldsGroupedByResultKey() byResultKey.size() == 2 @@ -648,7 +649,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { } } ''' - def ei = ExecutionInput.newExecutionInput(query).build() + def ei = ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = petSchema.execute(ei) then: er.errors.isEmpty() @@ -665,8 +666,8 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { when: def selectedFields = petUnionSelectionSet.getFields("name") then: - selectedFields.size() == 1 - assertTheyAreExpected(selectedFields, ["[Cat, Dog].name"]) + selectedFields.size() == 2 + assertTheyAreExpected(selectedFields, ["Cat.name", "Dog.name"]) } def "test normalised selection occurs on objects"() { @@ -679,7 +680,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { } } ''' - def ei = ExecutionInput.newExecutionInput(query).build() + def ei = ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = petSchema.execute(ei) then: er.errors.isEmpty() @@ -713,7 +714,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { } ''' - def ei = ExecutionInput.newExecutionInput(query).build() + def ei = ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = petSchema.execute(ei) then: er.errors.isEmpty() @@ -722,8 +723,8 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def selectedFields = petSelectionSet.getFields("name") then: - selectedFields.size() == 3 - assertTheyAreExpected(selectedFields, ["[Bird, Cat, Dog].name", "n1:Cat.name", "n2:Cat.name"]) + selectedFields.size() == 5 + assertTheyAreExpected(selectedFields, ["Bird.name", "Cat.name", "Dog.name", "n1:Cat.name", "n2:Cat.name"]) def byResultKey = petSelectionSet.getFieldsGroupedByResultKey("name") byResultKey.size() == 3 @@ -743,7 +744,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { } } ''' - def ei = ExecutionInput.newExecutionInput(query).build() + def ei = ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = petSchema.execute(ei) then: er.errors.isEmpty() @@ -753,13 +754,13 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { selectedFields.sort(byName()) then: - selectedFields[0].getObjectTypeNames() == ["Bird", "Cat", "Dog"] + selectedFields*.objectTypeNames == [["Bird"], ["Cat"], ["Dog"]] + selectedFields*.fieldDefinitions*.size() == [1, 1, 1] selectedFields[0].getName() == "name" } def "fragments inline and defined work as expected"() { - // this is repeating a lot of the underlying NormalisedField tests - so this is not extensively tested here when: def query = ''' { @@ -776,7 +777,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { name } ''' - def ei = ExecutionInput.newExecutionInput(query).build() + def ei = ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = petSchema.execute(ei) then: er.errors.isEmpty() @@ -786,8 +787,8 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { selectedFields.sort(byName()) then: - selectedFields.size() == 1 - assertTheyAreExpected(selectedFields, ["[Bird, Cat, Dog].name"]) + selectedFields.size() == 3 + assertTheyAreExpected(selectedFields, ["Bird.name", "Cat.name", "Dog.name"]) } @@ -809,7 +810,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { } } ''' - def ei = ExecutionInput.newExecutionInput(query).build() + def ei = ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = petSchema.execute(ei) then: er.errors.isEmpty() @@ -817,7 +818,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def selectedFields = petSelectionSet.getImmediateFields() then: assertTheyAreExpected(selectedFields, [ - "Cat.meow", "Dog.woof", "[Bird, Cat, Dog].lead", "[Bird, Cat, Dog].name"]) + "Bird.lead", "Bird.name", "Cat.lead", "Cat.meow", "Cat.name", "Dog.lead", "Dog.name", "Dog.woof"]) when: selectedFields = petSelectionSet.getFields("lead") @@ -835,7 +836,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { } } ''' - def ei = ExecutionInput.newExecutionInput(query).build() + def ei = ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = petSchema.execute(ei) then: er.errors.isEmpty() @@ -854,7 +855,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { } } ''' - def ei = ExecutionInput.newExecutionInput(query).build() + def ei = ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build() def er = petSchema.execute(ei) then: er.errors.isEmpty() @@ -901,13 +902,13 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def graphQL = GraphQL.newGraphQL(schema).build() when: - def er = graphQL.execute('''mutation M { + def er = graphQL.execute(ExecutionInput.newExecutionInput('''mutation M { mutate { selectedFieldNames b c } - }''') + }''').graphQLContext([(NormalizedDocument.ENABLED): true]).build()) then: er.errors.isEmpty() er.data["mutate"]["selectedFieldNames"] == ["selectedFieldNames", "b", "c"] @@ -955,7 +956,7 @@ class DataFetchingFieldSelectionSetImplTest extends Specification { def graphQL = GraphQL.newGraphQL(schema).build() when: - def er = graphQL.execute(query) + def er = graphQL.execute(ExecutionInput.newExecutionInput(query).graphQLContext([(NormalizedDocument.ENABLED): true]).build()) then: er.errors.isEmpty() diff --git a/src/test/groovy/graphql/validation/LargeSchemaQueryComplexityTest.groovy b/src/test/groovy/graphql/validation/LargeSchemaQueryComplexityTest.groovy index 1cd43e6395..8501cdee2a 100644 --- a/src/test/groovy/graphql/validation/LargeSchemaQueryComplexityTest.groovy +++ b/src/test/groovy/graphql/validation/LargeSchemaQueryComplexityTest.groovy @@ -1,18 +1,13 @@ package graphql.validation -import graphql.execution.CoercedVariables -import graphql.execution.TypeFromAST +import graphql.GraphQLContext +import graphql.normalized.NormalizedDocument import graphql.introspection.Introspection -import graphql.language.BooleanValue -import graphql.language.Directive import graphql.language.Document import graphql.language.Field import graphql.language.FragmentDefinition import graphql.language.Node -import graphql.language.NodeChildrenContainer import graphql.language.OperationDefinition -import graphql.normalized.ExecutableNormalizedField -import graphql.normalized.ExecutableNormalizedOperationFactory import graphql.parser.Parser import graphql.parser.ParserEnvironment import graphql.parser.ParserOptions @@ -20,12 +15,7 @@ import graphql.parser.exceptions.ParseCancelledException import graphql.parser.exceptions.ParseCancelledTooDeepException import graphql.parser.exceptions.ParseCancelledTooManyCharsException import graphql.parser.exceptions.ParseCancelledTooManyNumericLiteralCharactersException -import graphql.schema.GraphQLEnumType -import graphql.schema.GraphQLInputObjectType -import graphql.schema.GraphQLList -import graphql.schema.GraphQLNonNull import graphql.schema.GraphQLSchema -import graphql.schema.GraphQLType import graphql.schema.idl.RuntimeWiring import graphql.schema.idl.SchemaGenerator import graphql.schema.idl.SchemaParser @@ -110,23 +100,19 @@ class LargeSchemaQueryComplexityTest extends Specification { 'maxNumericLiteralCharacters' | 5 | ParseCancelledTooManyNumericLiteralCharactersException } - def "ENF creation count and final tree differ from validation groups with all selections retained"() { + def "the prepared graph stores AST fields once without requiring execution variables"() { given: - def operation = document.getDefinitionsOfType(OperationDefinition).first() - // These stand-in coerced values satisfy arguments; they are not production request variables. - def variables = operation.variableDefinitions.collectEntries { - [(it.name): sampleValue(TypeFromAST.getTypeFromAST(schema, it.type))] - } - def structuralDocument = (Document) retainAllConditionalSelections(document) + def context = GraphQLContext.of([(NormalizedDocument.ENABLED): true]) when: - def normalized = ExecutableNormalizedOperationFactory.createExecutableNormalizedOperation( - schema, structuralDocument, operation.name, CoercedVariables.of(variables)) + def result = new Validator().validateDocumentWithResult(schema, document, { true }, Locale.ENGLISH, + QueryComplexityLimits.DEFAULT, context) then: - normalized.operationFieldCount == 5648 - normalized.operationDepth == 15 - countNormalizedFields(normalized.topLevelFields) == 3882 + result.errors().empty + result.normalizedDocument().fields.size() == 5687 + result.normalizedDocument().operations.size() == 1 + result.normalizedDocument().document.is(document) } private List validate(QueryComplexityLimits limits) { @@ -141,53 +127,4 @@ class LargeSchemaQueryComplexityTest extends Specification { [node] + node.children.collectMany { collectNodes(it) } } - private static int countNormalizedFields(List fields) { - fields.sum(0) { 1 + countNormalizedFields(it.children) } as int - } - - private static Node retainAllConditionalSelections(Node node) { - if (node instanceof Directive && node.name in ['skip', 'include']) { - return retainConditionalSelection(node) - } - def children = node.namedChildren.children.collectEntries { name, values -> - [(name): values.collect { retainAllConditionalSelections(it) }] - } - node.withNewChildren(NodeChildrenContainer.newNodeChildrenContainer(children).build()) - } - - private static Directive retainConditionalSelection(Directive directive) { - def value = BooleanValue.newBooleanValue(directive.name == 'include').build() - def arguments = directive.arguments.collect { argument -> argument.transform { it.value(value) } } - directive.transform { it.arguments(arguments) } - } - - private static Object sampleValue(GraphQLType type) { - if (type instanceof GraphQLNonNull) { - return sampleValue(type.wrappedType) - } - if (type instanceof GraphQLList) { - return [] - } - if (type instanceof GraphQLInputObjectType) { - return sampleInputObject(type) - } - if (type instanceof GraphQLEnumType) { - return type.values.first().value - } - switch (type.name) { - case 'Boolean': return true - case 'Int': return 1 - case 'Float': return 1.0d - default: return 'example' - } - } - - private static Map sampleInputObject(GraphQLInputObjectType type) { - if (type.isOneOf()) { - def field = type.fieldDefinitions.first() - return [(field.name): sampleValue(field.type)] - } - type.fieldDefinitions.findAll { it.type instanceof GraphQLNonNull && !it.hasSetDefaultValue() } - .collectEntries { [(it.name): sampleValue(it.type)] } - } } diff --git a/src/test/groovy/readme/FieldSelectionExamples.java b/src/test/groovy/readme/FieldSelectionExamples.java index 19fc4fb121..3e6c417d9f 100644 --- a/src/test/groovy/readme/FieldSelectionExamples.java +++ b/src/test/groovy/readme/FieldSelectionExamples.java @@ -1,15 +1,23 @@ package readme; +import graphql.ExecutionInput; +import graphql.normalized.NormalizedDocument; import graphql.schema.DataFetcher; import graphql.schema.DataFetchingEnvironment; import graphql.schema.DataFetchingFieldSelectionSet; import graphql.schema.SelectedField; import java.util.List; +import java.util.Map; @SuppressWarnings({"unused", "Convert2Lambda"}) public class FieldSelectionExamples { + ExecutionInput enableLookahead(String query) { + return ExecutionInput.newExecutionInput(query) + .graphQLContext(Map.of(NormalizedDocument.ENABLED, true)).build(); + } + void usingSelectionSet() { DataFetcher smartUserDF = new DataFetcher() { @Override diff --git a/src/test/resources/graphql/archunit/nullability/NullableNormalizedUsage.java b/src/test/resources/graphql/archunit/nullability/NullableNormalizedUsage.java index 7368e608b2..26aab434aa 100644 --- a/src/test/resources/graphql/archunit/nullability/NullableNormalizedUsage.java +++ b/src/test/resources/graphql/archunit/nullability/NullableNormalizedUsage.java @@ -2,13 +2,13 @@ import graphql.analysis.QueryReducer; import graphql.analysis.QueryTraverser; -import graphql.normalized.nf.NormalizedField; -import graphql.normalized.nf.NormalizedOperation; -import graphql.normalized.nf.NormalizedOperationToAstCompiler; +import graphql.language.FragmentDefinition; +import graphql.normalized.NormalizedDocument; +import graphql.normalized.NormalizedSelectionScope; +import graphql.execution.preparsed.PreparsedDocumentEntry; import org.jspecify.annotations.NullMarked; import org.jspecify.annotations.Nullable; -import java.util.Map; @NullMarked public class NullableNormalizedUsage { @@ -18,12 +18,10 @@ public class NullableNormalizedUsage { return traverser.reducePostOrder(reducer, null); } - public static void absentMetadata(NormalizedField field, NormalizedOperation operation, - NormalizedOperationToAstCompiler.CompilerResult compiled) { - @Nullable String name = operation.getOperationName(); - @Nullable String alias = field.getAlias(); - @Nullable NormalizedField parent = field.getParent(); - @Nullable Map variables = compiled.getVariables(); - field.replaceParent(null); + public static void absentMetadata(NormalizedSelectionScope scope, + PreparsedDocumentEntry entry) { + @Nullable String condition = scope.getTypeCondition(); + @Nullable FragmentDefinition fragment = scope.getFragmentDefinition(); + @Nullable NormalizedDocument document = entry.getNormalizedDocument(); } } diff --git a/test-baseline.json b/test-baseline.json index 1a8ed50c84..ef6e789a25 100644 --- a/test-baseline.json +++ b/test-baseline.json @@ -998,16 +998,16 @@ }, "graphql.language.NonNullType": { "line": { - "covered": 23, - "missed": 2 + "covered": 22, + "missed": 3 }, "branch": { "covered": 3, "missed": 3 }, "method": { - "covered": 14, - "missed": 0 + "covered": 13, + "missed": 1 }, "methods": [ { @@ -1168,16 +1168,16 @@ "line": 89, "counters": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } }, @@ -1280,16 +1280,16 @@ }, "graphql.language.InlineFragment$Builder": { "line": { - "covered": 30, - "missed": 4 + "covered": 26, + "missed": 8 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 10, - "missed": 2 + "covered": 8, + "missed": 4 }, "methods": [ { @@ -1355,16 +1355,16 @@ "line": 202, "counters": { "line": { - "covered": 2, - "missed": 0 + "covered": 0, + "missed": 2 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } }, @@ -1412,16 +1412,16 @@ "line": 218, "counters": { "line": { - "covered": 2, - "missed": 0 + "covered": 0, + "missed": 2 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } }, @@ -29299,16 +29299,16 @@ }, "graphql.language.ListType": { "line": { - "covered": 23, - "missed": 2 + "covered": 22, + "missed": 3 }, "branch": { "covered": 3, "missed": 3 }, "method": { - "covered": 14, - "missed": 0 + "covered": 13, + "missed": 1 }, "methods": [ { @@ -29469,16 +29469,16 @@ "line": 88, "counters": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } }, @@ -67649,16 +67649,16 @@ }, "graphql.collect.ImmutableKit": { "line": { - "covered": 72, - "missed": 2 + "covered": 64, + "missed": 10 }, "branch": { - "covered": 26, - "missed": 0 + "covered": 24, + "missed": 2 }, "method": { - "covered": 13, - "missed": 2 + "covered": 12, + "missed": 3 }, "methods": [ { @@ -67800,16 +67800,16 @@ "line": 65, "counters": { "line": { - "covered": 8, - "missed": 0 + "covered": 0, + "missed": 8 }, "branch": { - "covered": 2, - "missed": 0 + "covered": 0, + "missed": 2 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } }, @@ -99020,16 +99020,16 @@ }, "graphql.util.LinkedHashMapFactory": { "line": { - "covered": 1, - "missed": 83 + "covered": 0, + "missed": 84 }, "branch": { "covered": 0, "missed": 4 }, "method": { - "covered": 1, - "missed": 11 + "covered": 0, + "missed": 12 }, "methods": [ { @@ -99038,16 +99038,16 @@ "line": 30, "counters": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } }, @@ -99810,16 +99810,16 @@ }, "graphql.util.TraverserVisitorStub": { "line": { - "covered": 2, - "missed": 1 + "covered": 0, + "missed": 3 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 2, - "missed": 1 + "covered": 0, + "missed": 3 }, "methods": [ { @@ -99828,16 +99828,16 @@ "line": 6, "counters": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } }, @@ -99866,16 +99866,16 @@ "line": 16, "counters": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } } @@ -100207,16 +100207,16 @@ }, "graphql.util.TreeTransformer$1": { "line": { - "covered": 6, - "missed": 0 + "covered": 5, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 4, - "missed": 0 + "covered": 3, + "missed": 1 }, "methods": [ { @@ -100282,16 +100282,16 @@ "line": 49, "counters": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } } @@ -100914,16 +100914,16 @@ }, "graphql.util.TraverserVisitor": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "methods": [ { @@ -100932,16 +100932,16 @@ "line": 34, "counters": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } } @@ -101526,16 +101526,16 @@ }, "graphql.util.FpKit": { "line": { - "covered": 95, - "missed": 15 + "covered": 88, + "missed": 22 }, "branch": { - "covered": 65, - "missed": 9 + "covered": 59, + "missed": 15 }, "method": { - "covered": 34, - "missed": 3 + "covered": 31, + "missed": 6 }, "methods": [ { @@ -101981,16 +101981,16 @@ "line": 318, "counters": { "line": { - "covered": 6, - "missed": 0 + "covered": 0, + "missed": 6 }, "branch": { - "covered": 4, - "missed": 0 + "covered": 0, + "missed": 4 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } }, @@ -102000,16 +102000,16 @@ "line": 336, "counters": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } }, @@ -102061,8 +102061,8 @@ "missed": 0 }, "branch": { - "covered": 10, - "missed": 0 + "covered": 8, + "missed": 2 }, "method": { "covered": 1, @@ -102076,16 +102076,16 @@ "line": 336, "counters": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } }, @@ -151072,16 +151072,16 @@ }, "graphql.normalized.NormalizedInputValue": { "line": { - "covered": 29, - "missed": 1 + "covered": 28, + "missed": 2 }, "branch": { "covered": 19, "missed": 1 }, "method": { - "covered": 13, - "missed": 0 + "covered": 12, + "missed": 1 }, "methods": [ { @@ -151318,16 +151318,16 @@ "line": 142, "counters": { "line": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 }, "branch": { "covered": 0, "missed": 0 }, "method": { - "covered": 1, - "missed": 0 + "covered": 0, + "missed": 1 } } } From 69c7bfbef920e5b95b7c295b60ef0652523eef3d Mon Sep 17 00:00:00 2001 From: Andreas Marek Date: Sun, 15 Nov 2026 09:58:53 +1000 Subject: [PATCH 2/2] Bound lookahead enumeration with configured occurrence limit --- docs/normalized-document.md | 50 +++- .../schema/DataFetchingFieldSelectionSet.java | 7 + .../DataFetchingFieldSelectionSetImpl.java | 35 ++- .../graphql/schema/LookaheadFieldBudget.java | 20 ++ .../graphql/schema/SelectedFieldImpl.java | 10 +- .../validation/QueryComplexityLimits.java | 22 +- .../schema/LookaheadFieldLimitTest.groovy | 218 ++++++++++++++++++ 7 files changed, 336 insertions(+), 26 deletions(-) create mode 100644 src/main/java/graphql/schema/LookaheadFieldBudget.java create mode 100644 src/test/groovy/graphql/schema/LookaheadFieldLimitTest.groovy diff --git a/docs/normalized-document.md b/docs/normalized-document.md index 96a7a2d1ce..780443866f 100644 --- a/docs/normalized-document.md +++ b/docs/normalized-document.md @@ -187,11 +187,45 @@ For resource protection, continue to use parser limits and `QueryComplexityLimits` during validation. `NormalizedDocument.getFields().size()` counts stored AST fields, not expanded occurrences or merged execution fields. -## Open draft question: flat lookahead paths - -The stored graph stays shared, but full `getFields()` enumeration can expand -many concrete-type paths through nested interfaces. With two implementations -at every level, the number of such paths can grow exponentially with depth. -The current draft has not added an enumeration budget. The remaining choice is -whether to bound these compatibility methods with the configured occurrence -limit or replace them with an API that exposes shared graph views. +## Bounded lookahead enumeration + +The stored graph stays shared, but flat lookahead expands concrete-type paths. +To bound this expansion, each enumeration uses the configured +`QueryComplexityLimits.maxFieldOccurrences` (initial default: 100,000). +Request-specific limits override the current JVM defaults. Each selection-set +view captures its limit when created. `QueryComplexityLimits.NONE`, or setting +`maxFieldOccurrences(Integer.MAX_VALUE)`, disables this bound. + +Validation and lookahead use the same threshold for **different counts**: + +- Validation counts AST field occurrences after fragment expansion, without + merging duplicates or expanding possible runtime types. +- Lookahead counts collected fields at every concrete-type path. Active + selections with the same concrete parent type and response key merge into one + entry at that position. The field whose selection set is inspected is excluded. + +For example, suppose `Node` has two implementations, `A` and `B`, and both expose +`next: Node` and `value: String`: + +```graphql +{ node { next { next { value } } } } +``` + +Validation counts **4** occurrences: `node`, two `next` fields, and `value`. +The `node` data fetcher's full lookahead counts **14**: 2 immediate `next` +entries, 4 second-level `next` entries, and 8 `value` entries. A limit of 13 +therefore permits validation but rejects full lookahead. With further nested +`next` selections, the AST grows linearly while concrete paths grow exponentially. + +`getImmediateFields()` bounds only its immediate entries. `getFields()`, glob +matching (`getFields(pattern)`, `contains` and their variants), and result-key +grouping bound the full enumeration. Non-matching entries still count because +enumeration precedes filtering. Inspecting a selected field's own selection set +starts a separate count relative to that field; counts are not cumulative across +calls or data fetchers. + +Exceeding the limit throws `IllegalStateException` identifying +`QueryComplexityLimits.maxFieldOccurrences` and the configured limit; results +are never truncated. The check occurs before constructing each selected-field +entry. Previously cached child lists still count toward the total, and concurrent +enumerations use separate counters. Successful complete results remain cached. diff --git a/src/main/java/graphql/schema/DataFetchingFieldSelectionSet.java b/src/main/java/graphql/schema/DataFetchingFieldSelectionSet.java index 990b652cb0..23a68648da 100644 --- a/src/main/java/graphql/schema/DataFetchingFieldSelectionSet.java +++ b/src/main/java/graphql/schema/DataFetchingFieldSelectionSet.java @@ -15,6 +15,13 @@ * in any preparsed cache. Otherwise inspection methods throw {@link IllegalStateException}. * Creation is off by default; inspection does not build a missing graph. *

+ * Enumeration is bounded by {@link graphql.validation.QueryComplexityLimits#getMaxFieldOccurrences()}, + * using request-specific limits or the JVM defaults. Each collected field counts once per concrete + * parent type, response key and path. The field being resolved is excluded. Immediate inspection + * counts only immediate fields; full inspection counts all descendants, including fields that + * do not match a requested glob. Exceeding the limit throws {@link IllegalStateException}; + * results are never truncated. {@link graphql.validation.QueryComplexityLimits#NONE} disables this bound. + *

* For example imagine we are fetching the field 'user' in the following query * *

diff --git a/src/main/java/graphql/schema/DataFetchingFieldSelectionSetImpl.java b/src/main/java/graphql/schema/DataFetchingFieldSelectionSetImpl.java
index 99865d1d8b..5733c324fc 100644
--- a/src/main/java/graphql/schema/DataFetchingFieldSelectionSetImpl.java
+++ b/src/main/java/graphql/schema/DataFetchingFieldSelectionSetImpl.java
@@ -6,6 +6,8 @@
 import graphql.language.Field;
 import graphql.normalized.NormalizedDocument;
 import graphql.normalized.NormalizedFieldCollector;
+import graphql.util.LockKit;
+import graphql.validation.QueryComplexityLimits;
 import org.jspecify.annotations.Nullable;
 
 import java.io.File;
@@ -34,7 +36,9 @@ public final class DataFetchingFieldSelectionSetImpl implements DataFetchingFiel
     private final @Nullable SelectedField parent;
     private final String simplePrefix;
     private final String typePrefix;
-    private final Supplier> immediateFields;
+    private final int maxFieldOccurrences;
+    private final LockKit.ReentrantLock immediateFieldsLock = new LockKit.ReentrantLock();
+    private @Nullable List immediateFields;
     private final Supplier> allFields;
 
     public static DataFetchingFieldSelectionSet newCollector(ExecutionContext context, MergedField field, GraphQLOutputType outputType, int parentLevel) {
@@ -53,7 +57,8 @@ public DataFetchingFieldSelectionSetImpl(ExecutionContext context, List p
         this.parent = parent;
         this.simplePrefix = simplePrefix;
         this.typePrefix = typePrefix;
-        this.immediateFields = interThreadMemoize(this::collectImmediateFields);
+        QueryComplexityLimits limits = context.getGraphQLContext().get(QueryComplexityLimits.KEY);
+        this.maxFieldOccurrences = (limits == null ? QueryComplexityLimits.getDefaultLimits() : limits).getMaxFieldOccurrences();
         this.allFields = interThreadMemoize(this::collectAllFields);
     }
 
@@ -65,12 +70,12 @@ private NormalizedDocument requireDocument() {
         return document;
     }
 
-    private List collectImmediateFields() {
+    private List collectImmediateFields(LookaheadFieldBudget budget) {
         NormalizedFieldCollector collector = new NormalizedFieldCollector(requireDocument(), context);
         List types = possibleTypes();
         List fields = new ArrayList<>();
         for (GraphQLObjectType type : types) {
-            addFields(fields, collector.collect(parentFields, type), type, types.size() > 1);
+            addFields(fields, collector.collect(parentFields, type), type, types.size() > 1, budget);
         }
         return List.copyOf(fields);
     }
@@ -90,8 +95,9 @@ private List possibleTypes() {
         return types;
     }
 
-    private void addFields(List result, List> groups, GraphQLObjectType objectType, boolean conditional) {
+    private void addFields(List result, List> groups, GraphQLObjectType objectType, boolean conditional, LookaheadFieldBudget budget) {
         for (List fields : groups) {
+            budget.consume(1);
             result.add(new SelectedFieldImpl(context, fields, objectType, parentLevel + 1, conditional, parent, simplePrefix, typePrefix));
         }
     }
@@ -99,11 +105,12 @@ private void addFields(List result, List> groups, Gra
     private List collectAllFields() {
         List result = new ArrayList<>();
         Deque pending = new ArrayDeque<>();
-        pushReverse(pending, getImmediateFields());
+        LookaheadFieldBudget budget = new LookaheadFieldBudget(maxFieldOccurrences);
+        pushReverse(pending, getImmediateFields(budget));
         while (!pending.isEmpty()) {
             SelectedFieldImpl field = (SelectedFieldImpl) pending.pop();
             result.add(field);
-            pushReverse(pending, field.getTraversalChildren());
+            pushReverse(pending, field.getTraversalChildren(budget));
         }
         return List.copyOf(result);
     }
@@ -116,8 +123,20 @@ private void pushReverse(Deque pending, List field
 
     @Override
     public List getImmediateFields() {
+        return getImmediateFields(new LookaheadFieldBudget(maxFieldOccurrences));
+    }
+
+    public List getImmediateFields(LookaheadFieldBudget budget) {
         requireDocument();
-        return immediateFields.get();
+        return immediateFieldsLock.callLocked(() -> {
+            if (immediateFields != null) {
+                budget.consume(immediateFields.size());
+                return immediateFields;
+            }
+            List fields = collectImmediateFields(budget);
+            immediateFields = fields;
+            return fields;
+        });
     }
 
     @Override
diff --git a/src/main/java/graphql/schema/LookaheadFieldBudget.java b/src/main/java/graphql/schema/LookaheadFieldBudget.java
new file mode 100644
index 0000000000..3045210666
--- /dev/null
+++ b/src/main/java/graphql/schema/LookaheadFieldBudget.java
@@ -0,0 +1,20 @@
+package graphql.schema;
+
+import graphql.Internal;
+
+@Internal
+public final class LookaheadFieldBudget {
+    private final int limit;
+    private long fields;
+
+    public LookaheadFieldBudget(int limit) {
+        this.limit = limit;
+    }
+
+    public void consume(int count) {
+        fields += count;
+        if (limit != Integer.MAX_VALUE && fields > limit) {
+            throw new IllegalStateException("Lookahead field enumeration exceeds QueryComplexityLimits.maxFieldOccurrences (limit=" + limit + ")");
+        }
+    }
+}
diff --git a/src/main/java/graphql/schema/SelectedFieldImpl.java b/src/main/java/graphql/schema/SelectedFieldImpl.java
index 6e5f9d9897..87c914f8d6 100644
--- a/src/main/java/graphql/schema/SelectedFieldImpl.java
+++ b/src/main/java/graphql/schema/SelectedFieldImpl.java
@@ -26,7 +26,7 @@ public final class SelectedFieldImpl implements SelectedField {
     private final String fullyQualifiedName;
     private final Supplier> arguments;
     private final Supplier children;
-    private final Supplier> traversalChildren;
+    private final Supplier traversalChildren;
 
     public SelectedFieldImpl(ExecutionContext context, List fields, GraphQLObjectType objectType, int level,
                              boolean conditional, @Nullable SelectedField parent, String simplePrefix, String typePrefix) {
@@ -42,19 +42,19 @@ public SelectedFieldImpl(ExecutionContext context, List fields, GraphQLOb
         this.arguments = interThreadMemoize(() -> ValuesResolver.getArgumentValues(context.getGraphQLSchema().getCodeRegistry(),
                 definition.getArguments(), fields.get(0).getArguments(), context.getCoercedVariables(), context.getGraphQLContext(), context.getLocale()));
         this.children = interThreadMemoize(() -> childSelectionSet("", ""));
-        this.traversalChildren = interThreadMemoize(() -> childSelectionSet(qualifiedName, fullyQualifiedName).getImmediateFields());
+        this.traversalChildren = interThreadMemoize(() -> childSelectionSet(qualifiedName, fullyQualifiedName));
     }
 
     private String qualify(String prefix, String name) {
         return prefix.isEmpty() ? name : prefix + "/" + name;
     }
 
-    private DataFetchingFieldSelectionSet childSelectionSet(String simplePrefix, String typePrefix) {
+    private DataFetchingFieldSelectionSetImpl childSelectionSet(String simplePrefix, String typePrefix) {
         return new DataFetchingFieldSelectionSetImpl(context, fields, getType(), level, this, simplePrefix, typePrefix);
     }
 
-    public List getTraversalChildren() {
-        return traversalChildren.get();
+    public List getTraversalChildren(LookaheadFieldBudget budget) {
+        return traversalChildren.get().getImmediateFields(budget);
     }
 
     @Override
diff --git a/src/main/java/graphql/validation/QueryComplexityLimits.java b/src/main/java/graphql/validation/QueryComplexityLimits.java
index 96f38f6c4a..ca71e92870 100644
--- a/src/main/java/graphql/validation/QueryComplexityLimits.java
+++ b/src/main/java/graphql/validation/QueryComplexityLimits.java
@@ -7,7 +7,7 @@
 import java.util.function.Consumer;
 
 /**
- * Configuration class for query complexity limits enforced during validation.
+ * Configuration class for query complexity limits enforced during validation and lookahead.
  * Limits the number and depth of merged fields using the same selections as field-merging validation.
  * Fields with the same response name (alias, or field name when unaliased) and a common parent type
  * count once at each response position. Their child selections are combined before counting.
@@ -30,6 +30,14 @@
  * Occurrences are limited separately for each operation, regardless of directives or runtime types.
  * Complexity limits are enforced independently of the validation-rule predicate.
  *
+ * 

When lookahead is enabled, the occurrence threshold also bounds each selection-set enumeration. + * This count is separate from validation: it counts collected fields at every concrete-type path, + * merging active selections with the same concrete parent type and response key at that position. + * Immediate inspection counts only immediate fields; full inspection counts all descendants, + * including fields that do not match a requested glob. Exceeding this threshold throws + * {@link IllegalStateException} instead of returning a partial result. See + * {@link graphql.schema.DataFetchingFieldSelectionSet}. + * *

The JVM-wide defaults initially enforce limits (maxDepth=100, maxMergedFieldCount=10000, * maxFieldOccurrences=100000), with introspection protections enabled at 500 merged fields and depth 20. * New builders copy all current JVM-wide settings; setting one limit preserves the others. @@ -113,7 +121,7 @@ public class QueryComplexityLimits { public static final QueryComplexityLimits DEFAULT = new Builder().build(); /** - * Disables general complexity limits and all introspection protections. + * Disables general complexity limits, lookahead enumeration limits and all introspection protections. * The introspection thresholds retain their library defaults, so transforming this instance * to re-enable introspection restores the default introspection protections. */ @@ -127,7 +135,7 @@ public class QueryComplexityLimits { private static volatile QueryComplexityLimits defaultLimits = DEFAULT; /** - * Sets the JVM-wide defaults used by new builders and by validation when no limits + * Sets the JVM-wide defaults used by new builders, validation and lookahead when no limits * are specified in GraphQLContext. Existing builders and limits remain unchanged. * This is useful for testing or for applications that want different global defaults. * @@ -178,8 +186,8 @@ public int getMaxMergedFieldCount() { } /** - * @return the maximum field occurrences in each operation after fragment expansion, - * or {@link Integer#MAX_VALUE} when occurrence counting is disabled + * @return the maximum field occurrences in each operation after fragment expansion and, + * separately, in each lookahead enumeration; or {@link Integer#MAX_VALUE} to disable these limits */ public int getMaxFieldOccurrences() { return maxFieldOccurrences; @@ -295,6 +303,10 @@ public Builder maxMergedFieldCount(int maxMergedFieldCount) { * contribute at every spread, even when their response names merge. All selections count * regardless of {@code @skip} or {@code @include}. Fragment definitions that are not * referenced by an operation do not contribute to its count. + *

The same threshold separately bounds lookahead enumeration of collected fields at + * every concrete-type path. Active selections that merge count once at that position; + * glob filtering does not reduce the count. Exceeding the lookahead limit throws + * {@link IllegalStateException}. * * @param maxFieldOccurrences the positive limit, or {@link Integer#MAX_VALUE} to disable it * @return this builder diff --git a/src/test/groovy/graphql/schema/LookaheadFieldLimitTest.groovy b/src/test/groovy/graphql/schema/LookaheadFieldLimitTest.groovy new file mode 100644 index 0000000000..35001807a6 --- /dev/null +++ b/src/test/groovy/graphql/schema/LookaheadFieldLimitTest.groovy @@ -0,0 +1,218 @@ +package graphql.schema + +import graphql.ExecutionInput +import graphql.GraphQL +import graphql.TestUtil +import graphql.execution.conditional.ConditionalNodeDecision +import graphql.language.Field +import graphql.normalized.NormalizedDocument +import graphql.validation.QueryComplexityLimits +import spock.lang.Specification +import spock.lang.Timeout + +import java.util.concurrent.CompletableFuture +import java.util.concurrent.atomic.AtomicInteger + +class LookaheadFieldLimitTest extends Specification { + def originalDefaults = QueryComplexityLimits.getDefaultLimits() + + def cleanup() { + QueryComplexityLimits.setDefaultLimits(originalDefaults) + } + + def "the exact limit includes every concrete path and permits empty leaf selections"() { + given: + def selection = selectionSet(nestedSelection(depth), limits(limit)) + + expect: + selection.fields.size() == limit + selection.getFields('**').size() == limit + selection.fields.every { it.objectTypeNames.size() == 1 } + + where: + depth | limit + 1 | 2 + 3 | 14 + } + + def "all flat inspection methods enforce the limit even when a glob matches nothing"() { + given: + def selection = selectionSet(nestedSelection(3), limits(13)) + // Warm the immediate cache before starting the bounded full traversal. + assert selection.immediateFields.size() == 2 + + when: + inspect(selection) + + then: + def failure = thrown(IllegalStateException) + failure.message == 'Lookahead field enumeration exceeds QueryComplexityLimits.maxFieldOccurrences (limit=13)' + + where: + inspect << [ + { it.fields }, + { it.getFields('**') }, + { it.getFields('missing') }, + { it.contains('missing') }, + { it.containsAnyOf('missing', 'value') }, + { it.containsAllOf('missing', 'value') }, + { it.fieldsGroupedByResultKey }, + { it.getFieldsGroupedByResultKey('missing') } + ] + } + + def "retrying a failed traversal charges cached child batches again"() { + given: + def selection = selectionSet(nestedSelection(3), limits(13)) + + when: + selection.fields + + then: + thrown(IllegalStateException) + + when: + selection.fields + + then: + thrown(IllegalStateException) + selection.immediateFields.size() == 2 + selection.immediateFields[0].selectionSet.fields.size() == 6 + } + + @Timeout(10) + def "nested interfaces stop before materializing exponentially many paths"() { + given: + def decisions = new AtomicInteger() + // Without a bound, this small AST has more than 68 billion concrete field occurrences. + def selection = selectionSet(nestedSelection(35), limits(128), 2, decisions, 129) + + when: + selection.fields + + then: + thrown(IllegalStateException) + decisions.get() == 129 + } + + def "the remaining budget also bounds a wide child batch before it is cached"() { + given: + def decisions = new AtomicInteger() + def selection = selectionSet(nestedSelection(2), limits(150), 100, decisions, 151) + assert selection.immediateFields.size() == 100 + + when: + selection.fields + + then: + thrown(IllegalStateException) + decisions.get() == 151 + } + + def "immediate enumeration also rejects an oversized concrete type expansion"() { + given: + def selection = selectionSet('value', limits(99), 100) + + when: + selection.immediateFields + + then: + thrown(IllegalStateException) + + when: + selection.immediateFields + + then: + thrown(IllegalStateException) + } + + def "merged duplicates count once per concrete parent and response key"() { + given: + def selection = selectionSet('value value alias: value', limits(4)) + + expect: + selection.fields*.resultKey == ['value', 'alias', 'value', 'alias'] + selection.fieldsGroupedByResultKey*.value*.size() == [2, 2] + } + + def "concurrent repeated reads do not share a mutable enumeration budget"() { + given: + def selection = selectionSet(nestedSelection(3), limits(14)) + + when: + def reads = (1..12).collect { CompletableFuture.supplyAsync { selection.fields.size() } } + + then: + reads.collect { it.join() } == [14] * 12 + selection.getFields('**').size() == 14 + } + + def "request limits override JVM defaults and NONE disables the enumeration bound"() { + given: + QueryComplexityLimits.setDefaultLimits(limits(globalLimit)) + def requestLimits = requestLimit == null ? null : limits(requestLimit) + def selection = selectionSet(nestedSelection(3), requestLimits) + + when: + def count = 0 + IllegalStateException failure = null + try { + count = selection.fields.size() + } catch (IllegalStateException exception) { + failure = exception + } + + then: + (failure != null) == rejected + rejected || count == 14 + + where: + globalLimit | requestLimit | rejected + 13 | null | true + 14 | null | false + 13 | 14 | false + 14 | 13 | true + 13 | Integer.MAX_VALUE | false + Integer.MAX_VALUE | null | false + } + + private static QueryComplexityLimits limits(int count) { + QueryComplexityLimits.NONE.transform { it.maxFieldOccurrences(count) } + } + + private static String nestedSelection(int depth) { + def selection = 'value' + (1.. captured = env.selectionSet; null } + def registry = schema.codeRegistry.transform { it.dataFetcher(FieldCoordinates.coordinates('Query', 'node'), fetcher) } + def graphQL = GraphQL.newGraphQL(schema.transform { it.codeRegistry(registry) }).build() + def input = ExecutionInput.newExecutionInput("{ node { $selection } }") + .graphQLContext([(NormalizedDocument.ENABLED): true]).build() + if (limits != null) { + input.graphQLContext.put(QueryComplexityLimits.KEY, limits) + } + input.graphQLContext.put(ConditionalNodeDecision, { env -> + def source = env.directivesContainer + if (source instanceof Field && source.name != 'node') { + assert decisions.incrementAndGet() <= safetyBound: 'Enumeration continued past the expected bound' + } + true + } as ConditionalNodeDecision) + def result = graphQL.execute(input) + assert result.errors.empty + captured + } +}