Skip to content

Commit b5d5345

Browse files
committed
Merge branch 'agent-friendly' into agent-friendly-p10-type-shape
TypeClassMatcher takes MergedDefinitions and matches a TypeShape leaf.
2 parents fe70cab + ea0b9a1 commit b5d5345

19 files changed

Lines changed: 758 additions & 379 deletions

‎AGENTS.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@ resolver classes. Published to Maven Central. Kotlin, with a few Java files, tar
55

66
## Layout
77

8-
- `src/main/kotlin/graphql/kickstart/tools`: `SchemaParser` and its builder and options, `SchemaClassScanner` (matches schema
9-
types to classes), `resolver/` (field resolvers and data fetchers), `directive/`, `relay/`, `proxy/` (finds the class
10-
behind a Spring, Guice, Weld or Javassist proxied resolver), `util/`
8+
- `src/main/kotlin/graphql/kickstart/tools`: `SchemaParser` and its builder and options, `MergedDefinitions.kt` (merges each
9+
SDL type with its extensions into a `MergedType`. Other code, apart from the Relay factory, reads SDL types only through
10+
it), `SchemaClassScanner` (matches schema types to classes), `resolver/` (field resolvers and data fetchers), `directive/`,
11+
`relay/`, `proxy/` (finds the class behind a Spring, Guice, Weld or Javassist proxied resolver), `util/`
1112
- `src/test/kotlin`: JUnit tests, one class per feature. A test for an issue goes into the class for its feature.
1213
`EndToEndTest` and `EndToEndSpecHelper` hold the shared schema and resolvers
1314
- `.claude/skills/verify-tools`: the probe that checks a change from a consuming app's side
@@ -94,7 +95,8 @@ happening. "docs only" means nothing does yet, so the rule depends on you readin
9495
| A resolver method's parameter layout, type variables and source are decided once, at schema build | docs only |
9596
| A change to how resolvers are found, bound or unwrapped keeps what a method, a property and a Map field return | `ResolverCompatibilityTest` and the bounded check in `ReturnValueUnwrappingTest`. Each lists exactly today's property and Map gaps as known findings, and fails when one is fixed until it's removed, or when a new failure would hide under one |
9697
| One output has one builder. Don't add a second path that builds the same thing | docs only |
97-
| Read an SDL type's members merged with its extensions, never from the raw definition | docs only |
98+
| Read an SDL type's members merged with its extensions, never from the raw definition | `MergedType` in `MergedDefinitions.kt` and `DefinitionsBoundaryTest`, which fails on a raw member, directive or child-node read, an extension class, an SDL node walk or a `TypeDefinitionRegistry` call outside it. A read by reflection gets past it |
99+
| Every kind of SDL type starts its graphql-java type from the same recipe | `MergedType.prepare`, `DefinitionsBoundaryTest` and `TypeKindRecipeTest` |
98100
| Reuse an existing structure before you add a parallel one | docs only |
99101
| Argument conversion goes through one entry point | docs only |
100102
| An input field's Java type comes from the mapping Jackson uses, not from guessed getters | docs only |

‎pom.xml‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,11 @@
8585
</dependency>
8686

8787
<!-- Test -->
88+
<dependency>
89+
<groupId>com.tngtech.archunit</groupId>
90+
<artifactId>archunit</artifactId>
91+
<version>1.5.1</version>
92+
</dependency>
8893
<dependency>
8994
<groupId>ch.qos.logback</groupId>
9095
<artifactId>logback-classic</artifactId>
@@ -181,6 +186,11 @@
181186
</dependency>
182187

183188
<!-- Test -->
189+
<dependency>
190+
<groupId>com.tngtech.archunit</groupId>
191+
<artifactId>archunit</artifactId>
192+
<scope>test</scope>
193+
</dependency>
184194
<dependency>
185195
<groupId>ch.qos.logback</groupId>
186196
<artifactId>logback-classic</artifactId>
@@ -261,6 +271,11 @@
261271
<goals>
262272
<goal>test-jar</goal>
263273
</goals>
274+
<configuration>
275+
<excludes>
276+
<exclude>logback-test.xml</exclude>
277+
</excludes>
278+
</configuration>
264279
</execution>
265280
</executions>
266281
</plugin>

‎src/main/kotlin/graphql/kickstart/tools/DictionaryTypeResolver.kt‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package graphql.kickstart.tools
33
import graphql.TypeResolutionEnvironment
44
import graphql.kickstart.tools.util.JavaType
55
import graphql.kickstart.tools.util.unwrap
6-
import graphql.language.TypeDefinition
76
import graphql.schema.GraphQLInterfaceType
87
import graphql.schema.GraphQLObjectType
98
import graphql.schema.GraphQLUnionType
@@ -14,7 +13,7 @@ import java.lang.reflect.ParameterizedType
1413
* @author Andrew Potter
1514
*/
1615
internal abstract class DictionaryTypeResolver(
17-
private val dictionary: Map<JavaType, TypeDefinition<*>>
16+
private val dictionary: Map<JavaType, MergedType<*>>
1817
) : TypeResolver {
1918
// Raw class of each parameterized entry, e.g. Box for Box<String>, unless several entries share it
2019
private val rawClassDictionary by lazy {
@@ -25,7 +24,7 @@ internal abstract class DictionaryTypeResolver(
2524
.toMap()
2625
}
2726

28-
private fun <T> getTypeDefinition(clazz: Class<T>): TypeDefinition<*>? {
27+
private fun <T> getTypeDefinition(clazz: Class<T>): MergedType<*>? {
2928
return dictionary[clazz]
3029
?: (if (clazz.superclass == null) null else getTypeDefinition(clazz.superclass))
3130
?: clazz.interfaces.mapNotNull { getTypeDefinition(it) }.firstOrNull()
@@ -45,7 +44,7 @@ internal abstract class DictionaryTypeResolver(
4544
}
4645

4746
internal class InterfaceTypeResolver(
48-
dictionary: Map<JavaType, TypeDefinition<*>>,
47+
dictionary: Map<JavaType, MergedType<*>>,
4948
private val thisInterface: GraphQLInterfaceType
5049
) : DictionaryTypeResolver(
5150
dictionary
@@ -54,7 +53,7 @@ internal class InterfaceTypeResolver(
5453
}
5554

5655
internal class UnionTypeResolver(
57-
dictionary: Map<JavaType, TypeDefinition<*>>,
56+
dictionary: Map<JavaType, MergedType<*>>,
5857
private val thisUnion: GraphQLUnionType
5958
) : DictionaryTypeResolver(
6059
dictionary
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
package graphql.kickstart.tools
2+
3+
import graphql.Directives
4+
import graphql.introspection.Introspection.DirectiveLocation
5+
import graphql.kickstart.tools.util.describe
6+
import graphql.kickstart.tools.util.getDocumentation
7+
import graphql.kickstart.tools.util.unwrap
8+
import graphql.language.*
9+
import graphql.schema.*
10+
import graphql.schema.idl.ScalarInfo
11+
12+
internal class MergedDefinitions(definitions: List<Definition<*>>) {
13+
val directiveDefinitions: List<DirectiveDefinition> = definitions.filterIsInstance<DirectiveDefinition>()
14+
val rootInfo: RootTypeInfo = RootTypeInfo.fromSchemaDefinitions(definitions.filterIsInstance<SchemaDefinition>())
15+
16+
val scalarNames: Set<String> = ScalarInfo.GRAPHQL_SPECIFICATION_SCALARS_DEFINITIONS.keys + definitions.filterIsInstance<ScalarTypeDefinition>().map { it.name }
17+
18+
private val typeDefinitions = definitions.filterIsInstance<TypeDefinition<*>>()
19+
private val baseTypeNames = typeDefinitions.filter { it !is SDLExtensionDefinition }.map { it.name }.toSet()
20+
21+
private val loneExtensions = typeDefinitions
22+
.filter { it is SDLExtensionDefinition && it !is ObjectTypeDefinition && it !is InputObjectTypeDefinition && it.name !in baseTypeNames }
23+
.distinctBy { it.name }
24+
.toSet()
25+
26+
private val sources = typeDefinitions.filter { it !is SDLExtensionDefinition || it in loneExtensions }
27+
28+
private val sourcesByName = sources.associateBy { it.name }
29+
30+
private val extensionsByName = typeDefinitions
31+
.filter { it is SDLExtensionDefinition && it !in loneExtensions && !extendsOtherKind(it) }
32+
.groupBy { it.name }
33+
34+
private val typesBySource: List<Pair<TypeDefinition<*>, MergedType<*>>> = sources.mapNotNull { source -> merge(source)?.let { source to it } }
35+
36+
private val specificationScalars: List<Pair<ScalarTypeDefinition, MergedType.Scalar>> = ScalarInfo.GRAPHQL_SPECIFICATION_SCALARS_DEFINITIONS.values.map { definition ->
37+
definition to MergedType.Scalar(definition, extensionsByName[definition.name].orEmpty().filterIsInstance<ScalarTypeExtensionDefinition>())
38+
}
39+
40+
private val specificationScalarsByName: Map<String, MergedType.Scalar> = specificationScalars.associate { (_, type) -> type.name to type }
41+
42+
private val sourceOf: Map<MergedType<*>, TypeDefinition<*>> = (typesBySource + specificationScalars).associate { (source, type) -> type to source }
43+
44+
val byName: Map<String, MergedType<*>> = typesBySource.associate { (_, type) -> type.name to type }
45+
46+
val objectsWithRepeats: List<MergedType.Object> = typesBySource.map { it.second }.filterIsInstance<MergedType.Object>()
47+
48+
val ignoredExtensionWarnings: List<String> = typeDefinitions.filter(::extendsOtherKind).map { extension ->
49+
"Type '${extension.name}' is defined as ${sourcesByName.getValue(extension.name).kind()}, but extended as ${extension.kind()}. The extension is ignored."
50+
}
51+
52+
fun resolve(name: String?): MergedType<*>? = specificationScalarsByName[name] ?: byName[name]
53+
54+
fun definitionsOf(types: Set<MergedType<*>>): Set<TypeDefinition<*>> = types.mapNotNullTo(linkedSetOf()) { sourceOf[it] }
55+
56+
fun findUsage(reference: TypeName, types: Collection<MergedType<*>>): String? =
57+
(types.mapNotNull { sourceOf[it] } + directiveDefinitions + extensionsByName.values.flatten()).asSequence().flatMap { definition ->
58+
when (definition) {
59+
is ObjectTypeDefinition -> fieldUsages(definition.name, definition.fieldDefinitions)
60+
is InterfaceTypeDefinition -> fieldUsages(definition.name, definition.fieldDefinitions)
61+
is InputObjectTypeDefinition -> definition.inputValueDefinitions.map { "input field '${definition.name}.${it.name}'" to it.type }
62+
is DirectiveDefinition -> definition.inputValueDefinitions.map { "argument '${it.name}' of directive '@${definition.name}'" to it.type }
63+
else -> emptyList()
64+
}
65+
}.find { (_, type) -> type.unwrap() === reference }?.first
66+
67+
private fun fieldUsages(typeName: String, fields: List<FieldDefinition>): List<Pair<String, Type<*>>> = fields.flatMap { field ->
68+
listOf("field '$typeName.${field.name}'" to field.type) +
69+
field.inputValueDefinitions.map { "argument '${it.name}' of field '$typeName.${field.name}'" to it.type }
70+
}
71+
72+
private fun merge(source: TypeDefinition<*>): MergedType<*>? {
73+
val extensions = extensionsByName[source.name].orEmpty()
74+
return when (source) {
75+
is ObjectTypeDefinition -> MergedType.Object(source, extensions.filterIsInstance<ObjectTypeExtensionDefinition>())
76+
is InterfaceTypeDefinition -> MergedType.Interface(source, extensions.filterIsInstance<InterfaceTypeExtensionDefinition>())
77+
is UnionTypeDefinition -> MergedType.Union(source, extensions.filterIsInstance<UnionTypeExtensionDefinition>())
78+
is EnumTypeDefinition -> MergedType.Enum(source, extensions.filterIsInstance<EnumTypeExtensionDefinition>())
79+
is InputObjectTypeDefinition -> MergedType.Input(source, extensions.filterIsInstance<InputObjectTypeExtensionDefinition>())
80+
is ScalarTypeDefinition -> MergedType.Scalar(source, extensions.filterIsInstance<ScalarTypeExtensionDefinition>())
81+
else -> null
82+
}
83+
}
84+
85+
private fun extendsOtherKind(definition: TypeDefinition<*>): Boolean {
86+
val type = sourcesByName[definition.name]
87+
return definition is SDLExtensionDefinition && type != null && type.kind() != definition.kind()
88+
}
89+
}
90+
91+
private fun TypeDefinition<*>.kind(): String = when (this) {
92+
is ObjectTypeDefinition -> "an object type"
93+
is InterfaceTypeDefinition -> "an interface"
94+
is UnionTypeDefinition -> "a union"
95+
is EnumTypeDefinition -> "an enum"
96+
is InputObjectTypeDefinition -> "an input object type"
97+
is ScalarTypeDefinition -> "a scalar"
98+
else -> javaClass.simpleName
99+
}
100+
101+
internal class TypeBuildContext(
102+
val options: SchemaParserOptions,
103+
val directives: SdlDirectives,
104+
val customScalars: CustomScalarMap,
105+
)
106+
107+
internal sealed class MergedType<B : GraphqlDirectivesContainerTypeBuilder<B, B>>(
108+
private val definition: TypeDefinition<*>,
109+
extensions: List<TypeDefinition<*>>,
110+
) {
111+
val name: String get() = definition.name
112+
113+
val definitionClassName: String get() = definition.javaClass.simpleName
114+
115+
val kindPhrase: String get() = definition.kind()
116+
117+
protected val directives: List<Directive> = definition.directives + extensions.flatMap { it.directives }
118+
119+
protected abstract val location: DirectiveLocation
120+
121+
protected abstract val declarations: List<NamedNode<*>>
122+
123+
protected abstract fun newBuilder(context: TypeBuildContext): B
124+
125+
fun prepare(context: TypeBuildContext): B {
126+
rejectRepeated()
127+
val builder = newBuilder(context).name(name)
128+
getDocumentation(definition as AbstractNode<*>, context.options)?.let { builder.description(it) }
129+
return with(context.directives) { builder.withSdlDirectives(directives, location) }
130+
}
131+
132+
private fun rejectRepeated() {
133+
val noun = when (this) {
134+
is Object, is Interface, is Input -> "field"
135+
is Enum -> "value"
136+
is Union -> "member"
137+
is Scalar -> return
138+
}
139+
val names = mutableSetOf<String?>()
140+
val repeat = declarations.firstOrNull { !names.add(it.name) } ?: return
141+
throw SchemaError("Type '$name' declares $noun '${repeat.name}' more than once${repeat.sourceLocation.describe()}.")
142+
}
143+
144+
sealed interface Implementing {
145+
val fields: List<FieldDefinition>
146+
val interfaces: List<Type<*>>
147+
}
148+
149+
class Object(
150+
private val definition: ObjectTypeDefinition,
151+
private val extensions: List<ObjectTypeExtensionDefinition>,
152+
) : MergedType<GraphQLObjectType.Builder>(definition, extensions), Implementing {
153+
override val fields: List<FieldDefinition> = definition.fieldDefinitions + extensions.flatMap { it.fieldDefinitions }
154+
override val interfaces: List<Type<*>> = definition.implements + extensions.flatMap { it.implements }
155+
override val location = DirectiveLocation.OBJECT
156+
override val declarations get() = fields
157+
override fun newBuilder(context: TypeBuildContext): GraphQLObjectType.Builder =
158+
GraphQLObjectType.newObject().definition(definition).extensionDefinitions(extensions)
159+
}
160+
161+
class Interface(
162+
private val definition: InterfaceTypeDefinition,
163+
private val extensions: List<InterfaceTypeExtensionDefinition>,
164+
) : MergedType<GraphQLInterfaceType.Builder>(definition, extensions), Implementing {
165+
override val fields: List<FieldDefinition> = definition.fieldDefinitions + extensions.flatMap { it.fieldDefinitions }
166+
override val interfaces: List<Type<*>> = definition.implements + extensions.flatMap { it.implements }
167+
override val location = DirectiveLocation.INTERFACE
168+
override val declarations get() = fields
169+
override fun newBuilder(context: TypeBuildContext): GraphQLInterfaceType.Builder =
170+
GraphQLInterfaceType.newInterface().definition(definition).extensionDefinitions(extensions)
171+
}
172+
173+
class Union(
174+
private val definition: UnionTypeDefinition,
175+
private val extensions: List<UnionTypeExtensionDefinition>,
176+
) : MergedType<GraphQLUnionType.Builder>(definition, extensions) {
177+
val members: List<Type<*>> = definition.memberTypes + extensions.flatMap { it.memberTypes }
178+
override val location = DirectiveLocation.UNION
179+
override val declarations get() = members.map { it as TypeName }
180+
override fun newBuilder(context: TypeBuildContext): GraphQLUnionType.Builder =
181+
GraphQLUnionType.newUnionType().definition(definition).extensionDefinitions(extensions)
182+
183+
fun declarationTextOf(member: Type<*>): String =
184+
(listOf(definition) + extensions).first { declaration -> declaration.memberTypes.any { it === member } }.toString()
185+
}
186+
187+
class Enum(
188+
private val definition: EnumTypeDefinition,
189+
private val extensions: List<EnumTypeExtensionDefinition>,
190+
) : MergedType<GraphQLEnumType.Builder>(definition, extensions) {
191+
val values: List<EnumValueDefinition> = definition.enumValueDefinitions + extensions.flatMap { it.enumValueDefinitions }
192+
override val location = DirectiveLocation.ENUM
193+
override val declarations get() = values
194+
override fun newBuilder(context: TypeBuildContext): GraphQLEnumType.Builder =
195+
GraphQLEnumType.newEnum().definition(definition).extensionDefinitions(extensions)
196+
}
197+
198+
class Input(
199+
private val definition: InputObjectTypeDefinition,
200+
private val extensions: List<InputObjectTypeExtensionDefinition>,
201+
) : MergedType<GraphQLInputObjectType.Builder>(definition, extensions) {
202+
val fields: List<InputValueDefinition> = definition.inputValueDefinitions + extensions.flatMap { it.inputValueDefinitions }
203+
override val location = DirectiveLocation.INPUT_OBJECT
204+
override val declarations get() = fields
205+
override fun newBuilder(context: TypeBuildContext): GraphQLInputObjectType.Builder =
206+
GraphQLInputObjectType.newInputObject().definition(definition).extensionDefinitions(extensions)
207+
}
208+
209+
class Scalar(
210+
private val definition: ScalarTypeDefinition,
211+
private val extensions: List<ScalarTypeExtensionDefinition>,
212+
) : MergedType<GraphQLScalarType.Builder>(definition, extensions) {
213+
override val location = DirectiveLocation.SCALAR
214+
override val declarations = emptyList<NamedNode<*>>()
215+
216+
// like graphql-java, only the schema's directives are applied
217+
override fun newBuilder(context: TypeBuildContext): GraphQLScalarType.Builder {
218+
val provided = context.customScalars.getValue(name)
219+
return GraphQLScalarType.newScalar(provided)
220+
.definition(definition)
221+
.extensionDefinitions(extensions)
222+
.specifiedByUrl(specifiedByUrl() ?: provided.specifiedByUrl)
223+
.clearDirectives()
224+
}
225+
226+
private fun specifiedByUrl(): String? =
227+
(directives.find { it.name == Directives.SpecifiedByDirective.name }?.getArgument("url")?.value as? StringValue)?.value
228+
}
229+
}

0 commit comments

Comments
 (0)