Skip to content

Commit

Permalink
add automatic persisted queries implementation to client (#1802)
Browse files Browse the repository at this point in the history
### 📝 Description
- add apq interfaces to client
- add apq implementation to ktor client
- add apq implementation to spring client

### 🔗 Related Issues
#1640
  • Loading branch information
gumimin authored Jul 3, 2023
1 parent e7ea357 commit 707731a
Show file tree
Hide file tree
Showing 9 changed files with 711 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2021 Expedia, Inc
* Copyright 2023 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,13 +16,15 @@

package com.expediagroup.graphql.client

import com.expediagroup.graphql.client.types.AutomaticPersistedQueriesSettings
import com.expediagroup.graphql.client.types.GraphQLClientRequest
import com.expediagroup.graphql.client.types.GraphQLClientResponse

/**
* A lightweight typesafe GraphQL HTTP client.
*/
interface GraphQLClient<RequestCustomizer> {
val automaticPersistedQueriesSettings: AutomaticPersistedQueriesSettings

/**
* Executes [GraphQLClientRequest] and returns corresponding [GraphQLClientResponse].
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.expediagroup.graphql.client.extensions

import com.expediagroup.graphql.client.types.AutomaticPersistedQueriesExtension
import com.expediagroup.graphql.client.types.GraphQLClientRequest
import java.math.BigInteger
import java.nio.charset.StandardCharsets
import java.security.MessageDigest

internal val MESSAGE_DIGEST: MessageDigest = MessageDigest.getInstance("SHA-256")

fun GraphQLClientRequest<*>.getQueryId(): String =
String.format(
"%064x",
BigInteger(1, MESSAGE_DIGEST.digest(this.query?.toByteArray(StandardCharsets.UTF_8)))
).also {
MESSAGE_DIGEST.reset()
}

fun AutomaticPersistedQueriesExtension.toQueryParamString() = """{"persistedQuery":{"version":$version,"sha256Hash":"$sha256Hash"}}"""
fun AutomaticPersistedQueriesExtension.toExtentionsBodyMap() = mapOf(
"persistedQuery" to mapOf(
"version" to version,
"sha256Hash" to sha256Hash
)
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Copyright 2023 Expedia, 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
*
* https://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.expediagroup.graphql.client.types

data class AutomaticPersistedQueriesExtension(
val version: Int,
val sha256Hash: String
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* Copyright 2023 Expedia, 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
*
* https://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.expediagroup.graphql.client.types

data class AutomaticPersistedQueriesSettings(
val enabled: Boolean = false,
val httpMethod: HttpMethod = HttpMethod.GET
) {
companion object {
const val VERSION: Int = 1
}
sealed class HttpMethod {
object GET : HttpMethod()
object POST : HttpMethod()
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2021 Expedia, Inc
* Copyright 2023 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -24,11 +24,14 @@ import kotlin.reflect.KClass
* @see [GraphQL Over HTTP](https://graphql.org/learn/serving-over-http/#post-request) for additional details
*/
interface GraphQLClientRequest<T : Any> {
val query: String
val query: String?
get() = null
val operationName: String?
get() = null
val variables: Any?
get() = null
val extensions: Map<String, Any>?
get() = null

/**
* Parameterized type of a corresponding GraphQLResponse.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2022 Expedia, Inc
* Copyright 2023 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -17,18 +17,27 @@
package com.expediagroup.graphql.client.ktor

import com.expediagroup.graphql.client.GraphQLClient
import com.expediagroup.graphql.client.extensions.getQueryId
import com.expediagroup.graphql.client.extensions.toExtentionsBodyMap
import com.expediagroup.graphql.client.extensions.toQueryParamString
import com.expediagroup.graphql.client.serializer.GraphQLClientSerializer
import com.expediagroup.graphql.client.serializer.defaultGraphQLSerializer
import com.expediagroup.graphql.client.types.AutomaticPersistedQueriesExtension
import com.expediagroup.graphql.client.types.AutomaticPersistedQueriesSettings
import com.expediagroup.graphql.client.types.GraphQLClientRequest
import com.expediagroup.graphql.client.types.GraphQLClientResponse
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.expectSuccess
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.accept
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.http.content.TextContent
import java.io.Closeable
import java.net.URL
Expand All @@ -39,16 +48,90 @@ import java.net.URL
open class GraphQLKtorClient(
private val url: URL,
private val httpClient: HttpClient = HttpClient(engineFactory = CIO),
private val serializer: GraphQLClientSerializer = defaultGraphQLSerializer()
private val serializer: GraphQLClientSerializer = defaultGraphQLSerializer(),
override val automaticPersistedQueriesSettings: AutomaticPersistedQueriesSettings = AutomaticPersistedQueriesSettings()
) : GraphQLClient<HttpRequestBuilder>, Closeable {

override suspend fun <T : Any> execute(request: GraphQLClientRequest<T>, requestCustomizer: HttpRequestBuilder.() -> Unit): GraphQLClientResponse<T> {
val rawResult: String = httpClient.post(url) {
expectSuccess = true
apply(requestCustomizer)
setBody(TextContent(serializer.serialize(request), ContentType.Application.Json))
}.body()
return serializer.deserialize(rawResult, request.responseType())
return if (automaticPersistedQueriesSettings.enabled) {
val queryId = request.getQueryId()
val automaticPersistedQueriesExtension = AutomaticPersistedQueriesExtension(
version = AutomaticPersistedQueriesSettings.VERSION,
sha256Hash = queryId
)
val extensions = request.extensions?.let {
automaticPersistedQueriesExtension.toExtentionsBodyMap().plus(it)
} ?: automaticPersistedQueriesExtension.toExtentionsBodyMap()

val apqRawResultWithoutQuery: String = when (automaticPersistedQueriesSettings.httpMethod) {
is AutomaticPersistedQueriesSettings.HttpMethod.GET -> {
httpClient
.get(url) {
expectSuccess = true
header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded)
accept(ContentType.Application.Json)
url {
parameters.append("extension", automaticPersistedQueriesExtension.toQueryParamString())
}
}.body()
}

is AutomaticPersistedQueriesSettings.HttpMethod.POST -> {
val requestWithoutQuery = object : GraphQLClientRequest<T> by request {
override val query = null
override val extensions = extensions
}
httpClient
.post(url) {
expectSuccess = true
apply(requestCustomizer)
accept(ContentType.Application.Json)
setBody(TextContent(serializer.serialize(requestWithoutQuery), ContentType.Application.Json))
}.body()
}
}

serializer.deserialize(apqRawResultWithoutQuery, request.responseType()).let {
if (it.errors.isNullOrEmpty() && it.data != null) return it
}

val apqRawResultWithQuery: String = when (automaticPersistedQueriesSettings.httpMethod) {
is AutomaticPersistedQueriesSettings.HttpMethod.GET -> {
httpClient
.get(url) {
expectSuccess = true
header(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded)
accept(ContentType.Application.Json)
url {
parameters.append("query", serializer.serialize(request))
parameters.append("extension", automaticPersistedQueriesExtension.toQueryParamString())
}
}.body()
}

is AutomaticPersistedQueriesSettings.HttpMethod.POST -> {
val requestWithQuery = object : GraphQLClientRequest<T> by request {
override val extensions = extensions
}
httpClient
.post(url) {
expectSuccess = true
apply(requestCustomizer)
accept(ContentType.Application.Json)
setBody(TextContent(serializer.serialize(requestWithQuery), ContentType.Application.Json))
}.body()
}
}

serializer.deserialize(apqRawResultWithQuery, request.responseType())
} else {
val rawResult: String = httpClient.post(url) {
expectSuccess = true
apply(requestCustomizer)
setBody(TextContent(serializer.serialize(request), ContentType.Application.Json))
}.body()
serializer.deserialize(rawResult, request.responseType())
}
}

override suspend fun execute(requests: List<GraphQLClientRequest<*>>, requestCustomizer: HttpRequestBuilder.() -> Unit): List<GraphQLClientResponse<*>> {
Expand Down
Loading

0 comments on commit 707731a

Please sign in to comment.