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鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix rewinding the Json stream when nested objects are encountered #3691

Merged
merged 3 commits into from
Dec 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,27 @@ class MapJsonWriter : JsonWriter {
}

override fun beginObject(): JsonWriter = apply {
val map = mutableMapOf<String, Any?>()
val map = if (stack.isEmpty()) {
mutableMapOf<String, Any?>()
} else {
val state = stack[stack.size - 1]
when (state) {
is State.List -> mutableMapOf<String, Any?>()
is State.Map -> {
val existingValue = state.map.get(state.name)
if (existingValue == null) {
mutableMapOf<String, Any?>()
} else {
// The stream rewinded. This happens with fragments as interface
check(existingValue is MutableMap<*, *>) {
"Trying to overwrite a non-object value with an object at $path: $existingValue"
}
@Suppress("UNCHECKED_CAST")
existingValue as MutableMap<String, Any?>
}
}
}
}

valueInternal(map)

Expand All @@ -80,18 +100,7 @@ class MapJsonWriter : JsonWriter {
when (val state = stack.lastOrNull()) {
is State.Map -> {
check(state.name != null)

// We support writing the same fields several time for fragments as classes
val existingValue = state.map[state.name!!]
if (existingValue != null && existingValue is Map<*, *>) {
check(value is Map<*, *>)
// merge any incoming object
state.map[state.name!!] = existingValue + value
} else {
// just overwrite what was previously there
// by construction it should be either null or the same value
state.map[state.name!!] = value
}
state.map[state.name!!] = value
state.name = null
}
is State.List -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ internal class Normalizer(
val compiledFields = allFields.filter { it.responseName == entry.key }
if (compiledFields.isEmpty()) {
// If we come here, `obj` contains more data than the CompiledSelections can understand
// It's not 100% clear how this could happen, log what field triggered this
// This happened previously (see https://github.com/apollographql/apollo-android/pull/3636)
// This should not happen anymore but in case it does, we're logging some info here
throw RuntimeException("Cannot find a CompiledField for entry: {${entry.key}: ${entry.value}}, __typename = $typename, key = $key")
}
val includedFields = compiledFields.filter {
Expand Down
17 changes: 17 additions & 0 deletions tests/normalization-tests/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
plugins {
id("org.jetbrains.kotlin.jvm")
id("com.apollographql.apollo3")
}

dependencies {
implementation("com.apollographql.apollo3:apollo-runtime")
implementation("com.apollographql.apollo3:apollo-mockserver")
implementation("com.apollographql.apollo3:apollo-normalized-cache")
implementation("com.apollographql.apollo3:apollo-testing-support")
testImplementation(groovy.util.Eval.x(project, "x.dep.kotlinJunit"))
testImplementation(groovy.util.Eval.x(project, "x.dep.junit"))
}

apollo {
packageName.set("com.example")
}
43 changes: 43 additions & 0 deletions tests/normalization-tests/src/main/graphql/operations.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
query Issue3672 {
viewer {
libraries(limit: 1) {
book { id }
...nestedBook
...anotherBookFragment
}
}
}

fragment nestedBook on Library {
name
book {
name
}
}

fragment anotherBookFragment on Library {
book {
year
}
}

fragment bookAuthor on Book {
author
}


query Issue2818 {
home {
...sectionFragment
sectionA {
name
}
}
}

fragment sectionFragment on Home {
sectionA {
id
imageUrl
}
}
31 changes: 31 additions & 0 deletions tests/normalization-tests/src/main/graphql/schema.graphqls
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
type Query {
viewer: Viewer!
home: Home!
}

type Viewer {
libraries(limit: Int): [Library!]!
}

type Book {
id: String!
name: String!
year: Int!
author: String!
}

type Library {
id: String!
name: String!
book: Book!
}

type Home {
sectionA: SectionA
}

type SectionA {
id: String!
name: String!
imageUrl: String
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package com.example

import com.apollographql.apollo3.api.CompiledField
import com.apollographql.apollo3.api.CustomScalarAdapters
import com.apollographql.apollo3.api.Executable
import com.apollographql.apollo3.api.json.jsonReader
import com.apollographql.apollo3.api.parseJsonResponse
import com.apollographql.apollo3.cache.normalized.ApolloStore
import com.apollographql.apollo3.cache.normalized.FetchPolicy
import com.apollographql.apollo3.cache.normalized.api.CacheKey
import com.apollographql.apollo3.cache.normalized.api.CacheKeyGenerator
import com.apollographql.apollo3.cache.normalized.api.CacheKeyGeneratorContext
import com.apollographql.apollo3.cache.normalized.api.CacheResolver
import com.apollographql.apollo3.cache.normalized.api.FieldPolicyCacheResolver
import com.apollographql.apollo3.cache.normalized.api.MemoryCacheFactory
import com.apollographql.apollo3.cache.normalized.api.TypePolicyCacheKeyGenerator
import com.example.fragment.SectionFragment
import kotlinx.coroutines.runBlocking
import okio.Buffer
import org.junit.Test

internal object IdBasedCacheKeyResolver : CacheResolver, CacheKeyGenerator {

override fun cacheKeyForObject(obj: Map<String, Any?>, context: CacheKeyGeneratorContext) =
obj["id"]?.toString()?.let(::CacheKey) ?: TypePolicyCacheKeyGenerator.cacheKeyForObject(obj, context)

override fun resolveField(field: CompiledField, variables: Executable.Variables, parent: Map<String, Any?>, parentId: String) =
FieldPolicyCacheResolver.resolveField(field, variables, parent, parentId)
}

class NormalizationTest() {

@Test
fun issue3672() = runBlocking {
val store = ApolloStore(
normalizedCacheFactory = MemoryCacheFactory(),
cacheKeyGenerator = IdBasedCacheKeyResolver,
cacheResolver = IdBasedCacheKeyResolver
)

val query = Issue3672Query()

val data1 = query.parseJsonResponse(Buffer().writeUtf8(nestedResponse).jsonReader(), CustomScalarAdapters.Empty).dataAssertNoErrors
store.writeOperation(query, data1)

val data2 = store.readOperation(query)
check(data1 == data2)
}


@Test
fun issue2818() = runBlocking {
val apolloStore = ApolloStore(
normalizedCacheFactory = MemoryCacheFactory(),
cacheKeyGenerator = IdBasedCacheKeyResolver,
cacheResolver = IdBasedCacheKeyResolver
)

apolloStore.writeOperation(
Issue2818Query(),
Issue2818Query.Data(
Issue2818Query.Home(
__typename = "Home",
sectionA = Issue2818Query.SectionA(
name = "section-name",
),
sectionFragment = SectionFragment(
sectionA = SectionFragment.SectionA(
id = "section-id",
imageUrl = "https://...",
),
),
),
),
)

val data = apolloStore.readOperation(Issue2818Query())
check(data.home.sectionA?.name == "section-name")
check(data.home.sectionFragment.sectionA?.id == "section-id")
check(data.home.sectionFragment.sectionA?.imageUrl == "https://...")
}
}
28 changes: 28 additions & 0 deletions tests/normalization-tests/src/test/kotlin/com/example/response.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.example

import org.intellij.lang.annotations.Language


@Language("JSON")
val nestedResponse = """
{
"data": {
"viewer": {
"__typename": "Viewer",
"libraries": [
{
"__typename": "Library",
"name": "library-1",
"book":{
"__typename": "Book",
"id": "book=1",
"name": "name-1",
"year": 1991,
"author": "John Doe"
}
}
]
}
}
}
""".trimIndent()