Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide consistent support for dynamically registered DataFetchers #1770

Merged
merged 12 commits into from
Jan 29, 2024
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright 2024 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.graphql.dgs

import com.netflix.graphql.dgs.internal.DataFetcherResultProcessor
import graphql.schema.*

/**
* Utility wrapper for [GraphQLCodeRegistry.Builder] which provides
* a consistent registration mechanism of DataFetchers similar to the annotation-based approach.
* Can be used as a first parameter of a [DgsCodeRegistry] annotated method.
*/
class DgsCodeRegistryBuilder(
private val dataFetcherResultProcessors: List<DataFetcherResultProcessor>,
private val graphQLCodeRegistry: GraphQLCodeRegistry.Builder
) {

fun dataFetcher(coordinates: FieldCoordinates, dataFetcher: DataFetcher<*>): DgsCodeRegistryBuilder {
val wrapped = DataFetcherFactories.wrapDataFetcher(dataFetcher) { dfe, result ->
result?.let {
val env = DgsDataFetchingEnvironment(dfe)
dataFetcherResultProcessors.find { it.supportsType(result) }?.process(result, env) ?: result
}
}

graphQLCodeRegistry.dataFetcher(coordinates, wrapped)
return this
}

fun hasDataFetcher(coordinates: FieldCoordinates): Boolean {
return graphQLCodeRegistry.hasDataFetcher(coordinates)
}

fun getDataFetcher(coordinates: FieldCoordinates, fieldDefinition: GraphQLFieldDefinition): DataFetcher<*> {
return graphQLCodeRegistry.getDataFetcher(coordinates, fieldDefinition)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ import graphql.language.TypeName
import graphql.language.UnionTypeDefinition
import graphql.parser.MultiSourceReader
import graphql.schema.Coercing
import graphql.schema.DataFetcher
import graphql.schema.DataFetcherFactories
import graphql.schema.DataFetcherFactory
import graphql.schema.FieldCoordinates
import graphql.schema.GraphQLCodeRegistry
Expand Down Expand Up @@ -187,12 +185,14 @@ class DgsSchemaProvider(
val runtimeWiringBuilder =
RuntimeWiring.newRuntimeWiring().codeRegistry(codeRegistryBuilder).fieldVisibility(fieldVisibility)

val dgsCodeRegistryBuilder = DgsCodeRegistryBuilder(dataFetcherResultProcessors, codeRegistryBuilder)

dgsComponents.asSequence()
.mapNotNull { dgsComponent -> invokeDgsTypeDefinitionRegistry(dgsComponent, mergedRegistry) }
.fold(mergedRegistry) { a, b -> a.merge(b) }
findScalars(applicationContext, runtimeWiringBuilder)
findDirectives(applicationContext, runtimeWiringBuilder)
findDataFetchers(dgsComponents, codeRegistryBuilder, mergedRegistry)
findDataFetchers(dgsComponents, dgsCodeRegistryBuilder, mergedRegistry)
findTypeResolvers(dgsComponents, runtimeWiringBuilder, mergedRegistry)

dgsComponents.forEach { dgsComponent ->
Expand Down Expand Up @@ -259,17 +259,26 @@ class DgsSchemaProvider(
codeRegistryBuilder: GraphQLCodeRegistry.Builder,
registry: TypeDefinitionRegistry
) {
val dgsCodeRegistryBuilder = DgsCodeRegistryBuilder(dataFetcherResultProcessors, codeRegistryBuilder)

dgsComponent.annotatedMethods<DgsCodeRegistry>()
.forEach { method ->
if (method.returnType != GraphQLCodeRegistry.Builder::class.java) {
throw InvalidDgsConfigurationException("Method annotated with @DgsCodeRegistry must have return type GraphQLCodeRegistry.Builder")
if (method.returnType != GraphQLCodeRegistry.Builder::class.java && method.returnType != DgsCodeRegistryBuilder::class.java) {
throw InvalidDgsConfigurationException("Method annotated with @DgsCodeRegistry must have return type GraphQLCodeRegistry.Builder or DgsCodeRegistryBuilder")
}

if (method.parameterCount != 2 || method.parameterTypes[0] != GraphQLCodeRegistry.Builder::class.java || method.parameterTypes[1] != TypeDefinitionRegistry::class.java) {
throw InvalidDgsConfigurationException("Method annotated with @DgsCodeRegistry must accept the following arguments: GraphQLCodeRegistry.Builder, TypeDefinitionRegistry. ${dgsComponent.javaClass.name}.${method.name} has the following arguments: ${method.parameterTypes.joinToString()}")
if (method.parameterCount != 2 ||
method.parameterTypes[0] != method.returnType || // Check that the first argument is of type DgsCodeRegistryBuilder or GraphQLCodeRegistry.Builder and the return type is the same
method.parameterTypes[1] != TypeDefinitionRegistry::class.java
) {
throw InvalidDgsConfigurationException("Method annotated with @DgsCodeRegistry must accept the following arguments: GraphQLCodeRegistry.Builder or DgsCodeRegistryBuilder, and TypeDefinitionRegistry. ${dgsComponent.javaClass.name}.${method.name} has the following arguments: ${method.parameterTypes.joinToString()}")
}

ReflectionUtils.invokeMethod(method, dgsComponent.instance, codeRegistryBuilder, registry)
if (method.returnType == DgsCodeRegistryBuilder::class.java) {
ReflectionUtils.invokeMethod(method, dgsComponent.instance, dgsCodeRegistryBuilder, registry)
} else if (method.returnType == GraphQLCodeRegistry.Builder::class.java) {
ReflectionUtils.invokeMethod(method, dgsComponent.instance, codeRegistryBuilder, registry)
}
}
}

Expand All @@ -290,7 +299,7 @@ class DgsSchemaProvider(

private fun findDataFetchers(
dgsComponents: Collection<DgsBean>,
codeRegistryBuilder: GraphQLCodeRegistry.Builder,
codeRegistryBuilder: DgsCodeRegistryBuilder,
typeDefinitionRegistry: TypeDefinitionRegistry
) {
dgsComponents.forEach { dgsComponent ->
Expand Down Expand Up @@ -323,7 +332,7 @@ class DgsSchemaProvider(

private fun registerDataFetcher(
typeDefinitionRegistry: TypeDefinitionRegistry,
codeRegistryBuilder: GraphQLCodeRegistry.Builder,
codeRegistryBuilder: DgsCodeRegistryBuilder,
dgsComponent: DgsBean,
method: Method,
dgsDataAnnotation: MergedAnnotation<DgsData>,
Expand Down Expand Up @@ -376,12 +385,9 @@ class DgsSchemaProvider(
// if we have a datafetcher explicitly defined for a parentType/field, use that and do not
// register the base implementation for interfaces
if (!codeRegistryBuilder.hasDataFetcher(FieldCoordinates.coordinates(implType.name, field))) {
val dataFetcher =
createBasicDataFetcher(method, dgsComponent.instance)
codeRegistryBuilder.dataFetcher(
FieldCoordinates.coordinates(implType.name, field),
dataFetcher
)
val dataFetcher = methodDataFetcherFactory.createDataFetcher(dgsComponent.instance, method)
codeRegistryBuilder.dataFetcher(FieldCoordinates.coordinates(implType.name, field), dataFetcher)

dataFetcherTracingInstrumentationEnabled["${implType.name}.$field"] =
enableTracingInstrumentation
dataFetcherMetricsInstrumentationEnabled["${implType.name}.$field"] =
Expand All @@ -391,12 +397,9 @@ class DgsSchemaProvider(
}
is UnionTypeDefinition -> {
type.memberTypes.asSequence().filterIsInstance<TypeName>().forEach { memberType ->
val dataFetcher =
createBasicDataFetcher(method, dgsComponent.instance)
codeRegistryBuilder.dataFetcher(
FieldCoordinates.coordinates(memberType.name, field),
dataFetcher
)
val dataFetcher = methodDataFetcherFactory.createDataFetcher(dgsComponent.instance, method)
codeRegistryBuilder.dataFetcher(FieldCoordinates.coordinates(memberType.name, field), dataFetcher)

dataFetcherTracingInstrumentationEnabled["${memberType.name}.$field"] = enableTracingInstrumentation
dataFetcherMetricsInstrumentationEnabled["${memberType.name}.$field"] = enableMetricsInstrumentation
}
Expand All @@ -410,11 +413,9 @@ class DgsSchemaProvider(
matchingField.inputValueDefinitions.asSequence().map { it.name }.toSet()
)
}
val dataFetcher = createBasicDataFetcher(method, dgsComponent.instance)
codeRegistryBuilder.dataFetcher(
FieldCoordinates.coordinates(parentType, field),
dataFetcher
)

val dataFetcher = methodDataFetcherFactory.createDataFetcher(dgsComponent.instance, method)
codeRegistryBuilder.dataFetcher(FieldCoordinates.coordinates(parentType, field), dataFetcher)
}
else -> {
throw InvalidDgsConfigurationException(
Expand Down Expand Up @@ -569,17 +570,6 @@ class DgsSchemaProvider(
return null
}

private fun createBasicDataFetcher(method: Method, dgsComponent: Any): DataFetcher<Any?> {
val dataFetcher = methodDataFetcherFactory.createDataFetcher(dgsComponent, method)

return DataFetcherFactories.wrapDataFetcher(dataFetcher) { dfe, result ->
result?.let {
val env = DgsDataFetchingEnvironment(dfe)
dataFetcherResultProcessors.find { it.supportsType(result) }?.process(result, env) ?: result
}
}
}

private fun findTypeResolvers(
dgsComponents: Collection<DgsBean>,
runtimeWiringBuilder: RuntimeWiring.Builder,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import com.netflix.graphql.dgs.exceptions.DataFetcherSchemaMismatchException
import com.netflix.graphql.dgs.exceptions.InvalidDgsConfigurationException
import com.netflix.graphql.dgs.exceptions.InvalidTypeResolverException
import com.netflix.graphql.dgs.exceptions.NoSchemaFoundException
import com.netflix.graphql.dgs.internal.DataFetcherResultProcessor
import com.netflix.graphql.dgs.internal.DefaultInputObjectMapper
import com.netflix.graphql.dgs.internal.DgsSchemaProvider
import com.netflix.graphql.dgs.internal.kotlin.test.Show
Expand Down Expand Up @@ -73,7 +74,8 @@ internal class DgsSchemaProviderTest {
typeDefinitionRegistry: TypeDefinitionRegistry? = null,
schemaLocations: List<String> = listOf(DgsSchemaProvider.DEFAULT_SCHEMA_LOCATION),
componentFilter: ((Any) -> Boolean)? = null,
schemaWiringValidationEnabled: Boolean = true
schemaWiringValidationEnabled: Boolean = true,
dataFetcherResultProcessors: List<DataFetcherResultProcessor> = emptyList()
): DgsSchemaProvider {
return DgsSchemaProvider(
applicationContext = applicationContext,
Expand All @@ -87,7 +89,8 @@ internal class DgsSchemaProviderTest {
)
),
componentFilter = componentFilter,
schemaWiringValidationEnabled = schemaWiringValidationEnabled
schemaWiringValidationEnabled = schemaWiringValidationEnabled,
dataFetcherResultProcessors = dataFetcherResultProcessors
)
}

Expand Down Expand Up @@ -468,6 +471,7 @@ internal class DgsSchemaProviderTest {
fun allowMergingStaticAndDynamicSchema() {
@DgsComponent
class CodeRegistryComponent {
// Result should not be processed by DataFetcherResultProcessors
@DgsCodeRegistry
fun registry(
codeRegistryBuilder: GraphQLCodeRegistry.Builder,
Expand All @@ -477,29 +481,66 @@ internal class DgsSchemaProviderTest {
val coordinates = FieldCoordinates.coordinates("Query", "myField")
return codeRegistryBuilder.dataFetcher(coordinates, df)
}

// Result should be processed by DataFetcherResultProcessors
@DgsCodeRegistry
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you be able to also update our docs to use the DgsCodeRegistryBuilder? Much appreciated.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ack

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, where are the docs 😄 ?

fun dgsProcessedRegistry(
codeRegistryBuilder: DgsCodeRegistryBuilder,
@Suppress("unused_parameter") registry: TypeDefinitionRegistry?
): DgsCodeRegistryBuilder {
val df = DataFetcher { "Runtime added field" }
val coordinates = FieldCoordinates.coordinates("Query", "myProcessedField")
return codeRegistryBuilder.dataFetcher(coordinates, df)
}
}

contextRunner.withBeans(HelloFetcher::class, CodeRegistryComponent::class).run { context ->
val typeDefinitionRegistry = TypeDefinitionRegistry()
val objectTypeExtensionDefinition = ObjectTypeExtensionDefinition.newObjectTypeExtensionDefinition()
.name("Query")
.fieldDefinition(
FieldDefinition.newFieldDefinition()
.name("myField")
.type(TypeName("String")).build()
)
.build()
.fieldDefinitions(
listOf(
FieldDefinition.newFieldDefinition()
.name("myField")
.type(TypeName("String")).build(),
FieldDefinition.newFieldDefinition()
.name("myProcessedField")
.type(TypeName("String")).build()
)
).build()

val processor = object : DataFetcherResultProcessor {
override fun supportsType(originalResult: Any): Boolean {
return true
}

override fun process(originalResult: Any, dfe: DgsDataFetchingEnvironment): Any {
// Avoid processing other results apart from the one for this test
if (originalResult != "Runtime added field") {
return originalResult
}
return originalResult as String + " [suffixFromProcessor]"
}
}

typeDefinitionRegistry.add(objectTypeExtensionDefinition)
val schema = schemaProvider(applicationContext = context, typeDefinitionRegistry = typeDefinitionRegistry).schema()
val schema = schemaProvider(
applicationContext = context,
typeDefinitionRegistry = typeDefinitionRegistry,
dataFetcherResultProcessors = listOf(processor)
).schema()
val build = GraphQL.newGraphQL(schema).build()
assertHello(build)

val executionResult2 = build.execute("{myField}")
assertTrue(executionResult2.isDataPresent)

val data = executionResult2.getData<Map<String, *>>()
val executionResult = build.execute("{myField}")
assertTrue(executionResult.isDataPresent)
val data = executionResult.getData<Map<String, *>>()
assertEquals("Runtime added field", data["myField"])

val processedExecutionResult = build.execute("{myProcessedField}")
assertTrue(processedExecutionResult.isDataPresent)
val processedData = processedExecutionResult.getData<Map<String, *>>()
assertEquals("Runtime added field [suffixFromProcessor]", processedData["myProcessedField"])
}

contextRunner.withBeans(HelloFetcher::class, CodeRegistryComponent::class).run { context ->
Expand Down
Loading