Skip to content
New issue

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

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

Already on GitHub? # to your account

Accept gzip responses, compress request with deflate #172

Merged
merged 1 commit into from
May 13, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions core/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ kotlin {
api(libs.kotlinx.datetime)
implementation(libs.kotlinx.coroutines.core)
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.encoding)
// implementation(project(":crypto"))
implementation(libs.lightspark.crypto)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import com.lightspark.sdk.core.crypto.NodeKeyCache
import com.lightspark.sdk.core.crypto.nextInt
import com.lightspark.sdk.core.util.getPlatform
import io.ktor.client.HttpClient
import io.ktor.client.plugins.compression.ContentEncoding
import io.ktor.client.plugins.websocket.WebSockets
import io.ktor.client.request.headers
import io.ktor.client.request.post
Expand All @@ -34,6 +35,7 @@ import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import java.util.zip.Deflater

private const val DEFAULT_BASE_URL = "api.lightspark.com"

Expand All @@ -45,6 +47,9 @@ class Requester constructor(
private val baseUrl: String = DEFAULT_BASE_URL,
) {
private val httpClient = HttpClient {
install(ContentEncoding) {
gzip() // Switch to deflate() when https://youtrack.jetbrains.com/issue/KTOR-6999 is fixed
}
install(WebSockets)
}
private val userAgent =
Expand Down Expand Up @@ -87,15 +92,15 @@ class Requester constructor(
)
}
val operation = operationMatch.groupValues[2]
var bodyData = buildJsonObject {
var payload = buildJsonObject {
put("query", JsonPrimitive(queryPayload))
variables?.let { put("variables", it) }
put("operationName", JsonPrimitive(operation))
}
var headers = defaultHeaders + authProvider.getCredentialHeaders()
var headers = defaultHeaders + authProvider.getCredentialHeaders() + mapOf("X-GraphQL-Operation" to operation)
val signedBodyAndHeaders = try {
addSigningDataIfNeeded(
bodyData,
payload,
headers,
signingNodeId,
)
Expand All @@ -106,11 +111,25 @@ class Requester constructor(
e,
)
}
bodyData = signedBodyAndHeaders.first
var body = signedBodyAndHeaders.first
headers = signedBodyAndHeaders.second

if (body.size > 1024) {
val output = ByteArray(body.size)
val deflater = Deflater(Deflater.BEST_SPEED)
deflater.setInput(body)
deflater.finish()
val length = deflater.deflate(output)
deflater.end()
body = output.copyOfRange(0, length)

headers = headers.toMutableMap().apply {
this["Content-Encoding"] = "deflate"
}
}

val response = httpClient.post("https://$baseUrl/$schemaEndpoint") {
setBody(bodyData.toString())
setBody(body)
headers {
headers.forEach { (key, value) ->
append(key, value)
Expand Down Expand Up @@ -193,9 +212,9 @@ class Requester constructor(
bodyData: JsonObject,
headers: Map<String, String>,
signingNodeId: String?,
): Pair<JsonObject, Map<String, String>> {
): Pair<ByteArray, Map<String, String>> {
if (signingNodeId == null) {
return bodyData to headers
return bodyData.toString().encodeToByteArray() to headers
}
if (!nodeKeyCache.contains(signingNodeId)) {
throw MissingKeyException(signingNodeId)
Expand All @@ -207,13 +226,13 @@ class Requester constructor(
put("nonce", JsonPrimitive(nextInt().toUInt().toLong()))
put("expires_at", JsonPrimitive(anHourFromNowISOString()))
}.let { JsonObject(it) }
val newBodyString = Json.encodeToString(newBodyData)
val signature = nodeKeyCache[signingNodeId].sign(newBodyString.encodeToByteArray())
val newBodyString = newBodyData.toString().encodeToByteArray()
val signature = nodeKeyCache[signingNodeId].sign(newBodyString)
val newHeaders = headers.toMutableMap().apply {
this["X-LIGHTSPARK-SIGNING"] =
"{\"v\":1,\"signature\":\"${signature.base64Encoded}\"}"
}
return newBodyData to newHeaders
return newBodyString to newHeaders
}

private fun anHourFromNowISOString() = Clock.System.now().plus(1.hours).toString()
Expand Down
3 changes: 2 additions & 1 deletion gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ ktor-client-serialization = { module = "io.ktor:ktor-client-serialization", vers
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
ktor-client-websockets = { module = "io.ktor:ktor-client-websockets", version.ref = "ktor" }
ktor-client-encoding = { module = "io.ktor:ktor-client-encoding", version.ref = "ktor" }

kotest-assertions = { module = "io.kotest:kotest-assertions-core", version.ref = "kotest" }

Expand Down Expand Up @@ -140,4 +141,4 @@ ktlint = { id = "org.jlleitschuh.gradle.ktlint", version.ref = "ktlint" }
mavenPublish = { id = "com.vanniktech.maven.publish", version.ref = "mavenPublish" }
dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" }
gradleS3 = { id = "com.mgd.core.gradle.s3", version.ref = "gradleS3" }
downloadFile = { id = "de.undercouch.download", version.ref = "downloadFile" }
downloadFile = { id = "de.undercouch.download", version.ref = "downloadFile" }