dgs-framework icon indicating copy to clipboard operation
dgs-framework copied to clipboard

Custom scalars not usable as mutation input

Open faust2199 opened this issue 5 years ago • 16 comments

Hey guys,

First of all, I really like your framework! I was trying to add a custom scalar (LocalDateTime) to my project, using the latest dgs release 3.5.1. I followed instructions on https://netflix.github.io/dgs/scalars/ and made changes accordingly. However when I tested it it threw exceptions. Then I tried the other method mentioned in https://github.com/Netflix/dgs-examples-java/blob/main/src/main/java/com/example/demo/scalars/DateTimeScalar.java and got the same error.

I've been able to reproduce the issue using my fork of the dgs-examples repo: https://github.com/faust2199/dgs-examples-java/tree/dgs-issue . After adding submittedDate to the input type, the following mutation causes an internal error:

mutation {
  addReview (review: {
    showId: 1
    username: "dgs-user"
    starScore: 0
    submittedDate: "1999-02-01T05:43:53.28Z"
  }) {
    username
    submittedDate
  }
}
{
  "errors": [
    {
      "message": "java.lang.IllegalArgumentException: Cannot construct instance of `java.time.OffsetDateTime` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)\n at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.example.demo.generated.types.SubmittedReview[\"submittedDate\"])",
      "locations": [],
      "path": [
        "addReview"
      ],
      "extensions": {
        "errorType": "INTERNAL"
      }
    }
  ],
  "data": {
    "addReview": null
  }
}

By the way, I ran across the following piece of code when looking at the stack trace. https://github.com/Netflix/dgs-framework/blob/3d38065e9525f349563881ff069b6dc09a865373/graphql-dgs/src/main/kotlin/com/netflix/graphql/dgs/internal/DgsSchemaProvider.kt#L268

Is it creating a new ObjectMapper on every request? I think it is more efficient to reuse.

Thanks in advance!

faust2199 avatar Feb 19 '21 10:02 faust2199

Looking into it. I did see your PR, but not sure those changes are needed.

srinivasankavitha avatar Feb 19 '21 18:02 srinivasankavitha

Looking into it. I did your PR, but not sure those changes are needed.

Thanks for the quick response! Were you able to reproduce the issue? If so, I believe the cause is that the objectMapper obtained through calling jacksonObjectMapper() has only kotlinModule registered ( see https://github.com/FasterXML/jackson-module-kotlin/blob/214af87d7d3e222598ae7458613b4fe8345c0808/src/main/kotlin/com/fasterxml/jackson/module/kotlin/Extensions.kt#L29 ). To properly handle Date/Time types, the JSR-310 module has to be added. Reusing the ObjectMapper is an optimization. According to https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html , "if possible, you should still pool and reuse mappers if you intend to use them for multiple operations".

If reusing the ObjectMapper is not desirable here, we can make a function wrapping jacksonObjectMapper() so that JavaTimeModule is always added.

faust2199 avatar Feb 19 '21 19:02 faust2199

Yes, I am able to reproduce the issue and understand the problem you are experiencing. I also tested out your changes and they make sense to me. What I am unsure of is whether we need to register other modules for other scalars.

Reusing the object mapper looks fine to me, don't see a reason not to.

srinivasankavitha avatar Feb 19 '21 21:02 srinivasankavitha

To provide full Java 8 support, we want to have all 3 modules mentioned in https://github.com/FasterXML/jackson-modules-java8 : com.fasterxml.jackson.module.paramnames.ParameterNamesModule, com.fasterxml.jackson.datatype.jsr310.JavaTimeModule and com.fasterxml.jackson.datatype.jdk8.Jdk8Module.

Another pattern I've seen is to provide consumers a way to customize the ObjectMapper, or make it possible to inject an ObjectMapper instance or factory. For example, graphql-java-spring-webmvc does that via https://github.com/graphql-java/graphql-java-spring/blob/master/graphql-java-spring-webmvc/src/main/java/graphql/spring/web/servlet/components/JacksonJsonSerializer.java , where a default one is provided but can be overridden by the consumer using Spring annotations. In the long term, something similar would make a lot of sense to satisfy different needs.

faust2199 avatar Feb 20 '21 02:02 faust2199

That's a good idea and would indeed address my concern around not knowing about all the different use cases. We will look into adding that as an enhancement.

srinivasankavitha avatar Feb 20 '21 23:02 srinivasankavitha

For this issue, let's go with the changes you have in the PR. We'll implement further enhancements in the future . Do you want to add the other modules as well as part of this PR?

srinivasankavitha avatar Feb 22 '21 18:02 srinivasankavitha

I think the other modules are nice to have. Fans of Java 8 Optional<T> can use it if Jdk8Module is added. Here is a hypothetical use case based on the previous test case (it only works after adding the module):

data class DateTimeOptionalInput(val date: Optional<LocalDateTime>)
        val schema = """
            type Mutation {
                setDate(input:DateTimeInput): String
            }
            
            input DateTimeInput {
                date: DateTime
            }
            
            scalar DateTime
        """.trimIndent()

        val fetcher = object : Any() {
            @DgsData(parentType = "Mutation", field = "setDate")
            fun someFetcher(@InputArgument("input") input: DateTimeOptionalInput): String {
                return "The date is: ${input.date.get().format(DateTimeFormatter.ISO_DATE)}"
            }
        }

ParameterNamesModule "enable clients to abandon the JavaBeans standard if they want to without forcing them to use annotations", per https://github.com/FasterXML/jackson-modules-java8/tree/master/parameter-names . I don't think the absence of this module will block anyone, given the context here: if someone is already using customized classes, then it's easy to just add the annotations.

faust2199 avatar Feb 23 '21 14:02 faust2199

We went into a bit of a rabbit hole testing this. I didn't understand why this PR was necessary, because the mapping should already have been done by the scalar implementation, so started digging in. It turns out there is a bigger issue.

When a query/mutation is received that contains an input type, and the input type contains a property which is a scalar, the following happens:

  1. The scalar implementation is called to deserialize the scalar value. For the date example, this results in an instance of LocalDateTime for example.
  2. While invoking the datafetcher, we scan for @InputArgument. If the argument is an input type, we run objectMapper.convertValue(parameterValue, parameter.type), to convert the Map<String,Object> to the expected Java representation of the input type.
  3. Jackson doesn't know that the scalar property was already converted by our scalar, so it tries to "deserialize" again.

This means each scalar value is technically deserialized twice. Once by the scalar implementation, and once by Jackson. That shouldn't happen. However, it does have the desired result in almost all cases, as long as the Java class representing the scalar has a default constructor (or has Jackson annotations). For the java.time types that's not the case, which explains the need for the extra Jackson module.

Long story short, adding the Jackson module fixes a code path that shouldn't be there, to begin with. The correct solution is probably implementing a custom JsonDesrializer, which checks if a value is a scalar.

Because implementing the JsonDeserializer is going to be some more work, and with the Jackson date module in place, the current implementation works for most use cases, we decided to merge this PR, but create an issue to properly fix the issue as well. So this is a temporary workaround.

paulbakker avatar Feb 24 '21 23:02 paulbakker

Thanks for the work @faust2199! To be clear, the described remaining issue wasn't caused by your PR, we just happened to find the existing issue while reviewing the PR.

Let's keep this issue open to work on the next steps, although the submitted PR is merged.

paulbakker avatar Feb 24 '21 23:02 paulbakker

Thanks for the update @paulbakker

Is there any way I could help with this?

ColadaFF avatar Feb 24 '21 23:02 ColadaFF

@ColadaFF This is the code branch that needs further work: https://github.com/Netflix/dgs-framework/blob/master/graphql-dgs/src/main/kotlin/com/netflix/graphql/dgs/internal/DgsSchemaProvider.kt#L271

What I think can be done is implement a JsonDeserializer, which checks if a type is a scalar or not (e.g. by looking it up in the schema). If it's a scalar we can assume it was already converted, so just return the current value, or continue normal deserialization otherwise.

However, I've never actually implemented a JsonDeserializer and can't be sure that's the correct direction. If you're comfortable in that area, help would be much appreciated!

paulbakker avatar Feb 24 '21 23:02 paulbakker

I would like to say it would be super convenient to be able to inject our own object mapper. There are some use cases where you might need to register additional modules into the object mapper.

havenotfear avatar May 06 '21 15:05 havenotfear

Just throwing my vote in here, as i've come across this a few times myself.

briandilley avatar Jun 26 '21 17:06 briandilley

I would like to say it would be super convenient to be able to inject our own object mapper. There are some use cases where you might need to register additional modules into the object mapper.

Exactly, we could set it up using something like DgsRuntimeWiring or, even better, using the one provided by Spring DI (if present).

bbaret avatar Jul 07 '21 20:07 bbaret

I wanted to add to this issue that the same problem exists with the DgsQueryExecutor when it attempts to deserialize the response into objects. And because we can't inject our own ObjectMapper the only workaround is to setup the jackson serializers/deserializers using the @JsonSerialize and @JsonDeserialize annotations.

briandilley avatar Aug 06 '21 22:08 briandilley

I wanted to add to this issue that the same problem exists with the DgsQueryExecutor when it attempts to deserialize the response into objects. And because we can't inject our own ObjectMapper the only workaround is to setup the jackson serializers/deserializers using the @JsonSerialize and @JsonDeserialize annotations.

Note that this isn't fixed in the mentioned PR, it's a separate issue.

paulbakker avatar Aug 20 '21 18:08 paulbakker