Skip to content

Add Ktor client integration #4527

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

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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 buildSrc/src/main/java/Config.kt
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ object Config {
val SENTRY_OKHTTP_SDK_NAME = "$SENTRY_JAVA_SDK_NAME.okhttp"
val SENTRY_REACTOR_SDK_NAME = "$SENTRY_JAVA_SDK_NAME.reactor"
val SENTRY_KOTLIN_EXTENSIONS_SDK_NAME = "$SENTRY_JAVA_SDK_NAME.kotlin-extensions"
val SENTRY_KTOR_SDK_NAME = "$SENTRY_JAVA_SDK_NAME.ktor"
val group = "io.sentry"
val description = "SDK for sentry.io"
val versionNameProp = "versionName"
Expand Down
3 changes: 3 additions & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ jackson = "2.18.3"
jetbrainsCompose = "1.6.11"
kotlin = "1.9.24"
kotlin-compatible-version = "1.6"
ktorClient = "3.0.0"
logback = "1.2.9"
log4j2 = "2.20.0"
nopen = "1.0.1"
Expand Down Expand Up @@ -94,6 +95,8 @@ jetbrains-annotations = { module = "org.jetbrains:annotations", version = "23.0.
kotlin-test-junit = { module = "org.jetbrains.kotlin:kotlin-test-junit", version.ref = "kotlin" }
kotlinx-coroutines = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "coroutines" }
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktorClient" }
ktor-client-java = { module = "io.ktor:ktor-client-java", version.ref = "ktorClient" }
log4j-api = { module = "org.apache.logging.log4j:log4j-api", version.ref = "log4j2" }
log4j-core = { module = "org.apache.logging.log4j:log4j-core", version.ref = "log4j2" }
leakcanary = { module = "com.squareup.leakcanary:leakcanary-android", version = "2.14" }
Expand Down
33 changes: 33 additions & 0 deletions sentry-ktor/api/sentry-ktor.api
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
public final class io/sentry/ktor/BuildConfig {
public static final field SENTRY_KTOR_SDK_NAME Ljava/lang/String;
public static final field VERSION_NAME Ljava/lang/String;
}

public final class io/sentry/ktor/SentryKtorClientPluginConfig {
public fun <init> ()V
public final fun getBeforeSpan ()Lio/sentry/ktor/SentryKtorClientPluginConfig$BeforeSpanCallback;
public final fun getCaptureFailedRequests ()Z
public final fun getFailedRequestStatusCodes ()Ljava/util/List;
public final fun getFailedRequestTargets ()Ljava/util/List;
public final fun getScopes ()Lio/sentry/IScopes;
public final fun setBeforeSpan (Lio/sentry/ktor/SentryKtorClientPluginConfig$BeforeSpanCallback;)V
public final fun setCaptureFailedRequests (Z)V
public final fun setFailedRequestStatusCodes (Ljava/util/List;)V
public final fun setFailedRequestTargets (Ljava/util/List;)V
public final fun setScopes (Lio/sentry/IScopes;)V
}

public abstract interface class io/sentry/ktor/SentryKtorClientPluginConfig$BeforeSpanCallback {
public abstract fun execute (Lio/sentry/ISpan;Lio/ktor/client/request/HttpRequestBuilder;)Lio/sentry/ISpan;
}

public class io/sentry/ktor/SentryKtorClientPluginContextHook : io/ktor/client/plugins/api/ClientHook {
public fun <init> ()V
public synthetic fun install (Lio/ktor/client/HttpClient;Ljava/lang/Object;)V
public fun install (Lio/ktor/client/HttpClient;Lkotlin/jvm/functions/Function2;)V
}

public final class io/sentry/ktor/SentryKtorClientPluginKt {
public static final fun getSentryKtorClientPlugin ()Lio/ktor/client/plugins/api/ClientPlugin;
}

90 changes: 90 additions & 0 deletions sentry-ktor/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import net.ltgt.gradle.errorprone.errorprone
import org.jetbrains.kotlin.config.KotlinCompilerVersion
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
`java-library`
kotlin("jvm")
jacoco
id("io.sentry.javadoc")
alias(libs.plugins.errorprone)
alias(libs.plugins.gradle.versions)
alias(libs.plugins.buildconfig)
}

tasks.withType<KotlinCompile>().configureEach {
kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8.toString()
}

kotlin { explicitApi() }

dependencies {
api(projects.sentry)

implementation(kotlin(Config.kotlinStdLib, KotlinCompilerVersion.VERSION))
implementation(projects.sentryKotlinExtensions)

compileOnly(libs.jetbrains.annotations)
compileOnly(libs.nopen.annotations)
compileOnly(libs.ktor.client.core)
errorprone(libs.errorprone.core)
errorprone(libs.nopen.checker)
errorprone(libs.nullaway)

testImplementation(projects.sentryTestSupport)
testImplementation(libs.kotlin.test.junit)
testImplementation(libs.mockito.kotlin)
testImplementation(libs.mockito.inline)
testImplementation(libs.ktor.client.core)
testImplementation(libs.ktor.client.java)
testImplementation(libs.okhttp.mockwebserver)
}

configure<SourceSetContainer> { test { java.srcDir("src/test/java") } }

jacoco { toolVersion = libs.versions.jacoco.get() }

tasks.jacocoTestReport {
reports {
xml.required.set(true)
html.required.set(false)
}
}

tasks {
jacocoTestCoverageVerification {
violationRules { rule { limit { minimum = Config.QualityPlugins.Jacoco.minimumCoverage } } }
}
check {
dependsOn(jacocoTestCoverageVerification)
dependsOn(jacocoTestReport)
}
}

buildConfig {
useJavaOutput()
packageName("io.sentry.ktor")
buildConfigField("String", "SENTRY_KTOR_SDK_NAME", "\"${Config.Sentry.SENTRY_KTOR_SDK_NAME}\"")
buildConfigField("String", "VERSION_NAME", "\"${project.version}\"")
}

tasks.withType<JavaCompile>().configureEach {
dependsOn(tasks.generateBuildConfig)
options.errorprone {
check("NullAway", net.ltgt.gradle.errorprone.CheckSeverity.ERROR)
option("NullAway:AnnotatedPackages", "io.sentry")
}
}

tasks.jar {
manifest {
attributes(
"Sentry-Version-Name" to project.version,
"Sentry-SDK-Name" to Config.Sentry.SENTRY_KTOR_SDK_NAME,
"Sentry-SDK-Package-Name" to "maven:io.sentry:sentry-ktor",
"Implementation-Vendor" to "Sentry",
"Implementation-Title" to project.name,
"Implementation-Version" to project.version,
)
}
}
121 changes: 121 additions & 0 deletions sentry-ktor/src/main/java/io/sentry/ktor/SentryKtorClientPlugin.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package io.sentry.ktor

import io.ktor.client.HttpClient
import io.ktor.client.plugins.api.*
import io.ktor.client.plugins.api.ClientPlugin
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.util.*
import io.ktor.util.pipeline.*
import io.sentry.HttpStatusCodeRange
import io.sentry.IScopes
import io.sentry.ISpan
import io.sentry.ScopesAdapter
import io.sentry.Sentry
import io.sentry.SentryIntegrationPackageStorage
import io.sentry.SentryOptions
import io.sentry.kotlin.SentryContext
import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion
import io.sentry.util.PropagationTargetsUtils
import kotlinx.coroutines.withContext

/** Configuration for the Sentry Ktor client plugin. */
public class SentryKtorClientPluginConfig {
/** The [IScopes] instance to use. Defaults to [ScopesAdapter.getInstance]. */
public var scopes: IScopes = ScopesAdapter.getInstance()

/** Callback to customize or drop spans before they are created. Return null to drop the span. */
public var beforeSpan: BeforeSpanCallback? = null

/** Whether to capture HTTP client errors as Sentry events. Defaults to true. */
public var captureFailedRequests: Boolean = true

/**
* The HTTP status code ranges that should be considered as failed requests. Defaults to 500-599
* (server errors).
*/
public var failedRequestStatusCodes: List<HttpStatusCodeRange> =
listOf(HttpStatusCodeRange(HttpStatusCodeRange.DEFAULT_MIN, HttpStatusCodeRange.DEFAULT_MAX))

/**
* The list of targets (URLs) for which failed requests should be captured. Supports regex
* patterns. Defaults to capture all requests.
*/
public var failedRequestTargets: List<String> = listOf(SentryOptions.DEFAULT_PROPAGATION_TARGETS)

/** Callback interface for customizing spans before they are created. */
public fun interface BeforeSpanCallback {
/**
* Customize or drop a span before it's created.
*
* @param span The span to customize
* @param request The HTTP request being executed
* @return The customized span, or null to drop the span
*/
public fun execute(span: ISpan, request: HttpRequestBuilder): ISpan?
}
}

internal const val SENTRY_KTOR_CLIENT_PLUGIN_KEY = "SentryKtorClientPlugin"

/**
* Sentry plugin for Ktor HTTP client that provides automatic instrumentation for HTTP requests,
* including distributed tracing, breadcrumbs, and error capturing.
*/
public val SentryKtorClientPlugin: ClientPlugin<SentryKtorClientPluginConfig> =
createClientPlugin(SENTRY_KTOR_CLIENT_PLUGIN_KEY, ::SentryKtorClientPluginConfig) {
// Init
SentryIntegrationPackageStorage.getInstance()
.addPackage("maven:io.sentry:sentry-ktor", BuildConfig.VERSION_NAME)
addIntegrationToSdkVersion("Ktor")

// Options
val scopes = pluginConfig.scopes
val captureFailedRequests = pluginConfig.captureFailedRequests
val failedRequestStatusCodes = pluginConfig.failedRequestStatusCodes
val failedRequestTargets = pluginConfig.failedRequestTargets

// Attributes
// Request start time for breadcrumbs
val requestStartTimestampKey = AttributeKey<Long>("SentryRequestStartTimestamp")

onRequest { request, _ ->
request.attributes.put(requestStartTimestampKey, System.currentTimeMillis())
// TODO: start span
// TODO: inject tracing headers
}

onResponse { response ->
val request = response.request
val startTimestamp = response.call.attributes.getOrNull(requestStartTimestampKey)
val endTimestamp = System.currentTimeMillis()

if (
captureFailedRequests &&
failedRequestStatusCodes.any { it.isInRange(response.status.value) } &&
PropagationTargetsUtils.contain(failedRequestTargets, request.url.toString())
) {
SentryKtorClientUtils.captureClientError(scopes, request, response)
}

SentryKtorClientUtils.addBreadcrumb(scopes, request, response, startTimestamp, endTimestamp)

// TODO: end span
}

on(SentryKtorClientPluginContextHook()) { block -> block() }
}

public open class SentryKtorClientPluginContextHook :
ClientHook<suspend (suspend () -> Unit) -> Unit> {
private val phase = PipelinePhase("SentryKtorClientPluginContext")

override fun install(client: HttpClient, handler: suspend (suspend () -> Unit) -> Unit) {
client.requestPipeline.insertPhaseBefore(HttpRequestPipeline.Before, phase)
client.requestPipeline.intercept(phase) {
withContext(SentryContext(Sentry.forkedCurrentScope(SENTRY_KTOR_CLIENT_PLUGIN_KEY))) {
proceed()
}
}
}
}
112 changes: 112 additions & 0 deletions sentry-ktor/src/main/java/io/sentry/ktor/SentryKtorClientUtils.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package io.sentry.ktor

import io.ktor.client.request.HttpRequest
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsBytes
import io.ktor.http.Headers
import io.ktor.http.contentLength
import io.ktor.util.toMap
import io.sentry.Breadcrumb
import io.sentry.Hint
import io.sentry.IScopes
import io.sentry.SentryEvent
import io.sentry.SpanDataConvention
import io.sentry.TypeCheckHint
import io.sentry.exception.ExceptionMechanismException
import io.sentry.exception.SentryHttpClientException
import io.sentry.protocol.Mechanism
import io.sentry.util.HttpUtils
import io.sentry.util.UrlUtils

internal object SentryKtorClientUtils {
internal suspend fun captureClientError(
scopes: IScopes,
request: HttpRequest,
response: HttpResponse,
) {
val urlDetails = UrlUtils.parse(request.url.toString())

val mechanism = Mechanism().apply { type = "SentryKtorClientPlugin" }
val exception =
SentryHttpClientException("HTTP Client Error with status code: ${response.status.value}")
val mechanismException =
ExceptionMechanismException(mechanism, exception, Thread.currentThread(), true)
val event = SentryEvent(mechanismException)

val hint = Hint()
hint.set(TypeCheckHint.KTOR_REQUEST, request)
hint.set(TypeCheckHint.KTOR_RESPONSE, response)

val sentryRequest =
io.sentry.protocol.Request().apply {
// Cookie is only sent if isSendDefaultPii is enabled
urlDetails.applyToRequest(this)
cookies = if (scopes.options.isSendDefaultPii) request.headers["Cookie"] else null
method = request.method.value
headers = getHeaders(scopes, request.headers)
bodySize = request.content.contentLength
}

val sentryResponse =
io.sentry.protocol.Response().apply {
// Set-Cookie is only sent if isSendDefaultPii is enabled due to PII
cookies = if (scopes.options.isSendDefaultPii) response.headers["Set-Cookie"] else null
headers = getHeaders(scopes, response.headers)
statusCode = response.status.value
bodySize = response.bodyAsBytes().size.toLong()
}

event.request = sentryRequest
event.contexts.setResponse(sentryResponse)

scopes.captureEvent(event, hint)
}

private fun getHeaders(scopes: IScopes, headers: Headers): MutableMap<String, String>? {
// Headers are only sent if isSendDefaultPii is enabled due to PII
if (!scopes.options.isSendDefaultPii) {
return null
}

val res = mutableMapOf<String, String>()
headers.toMap().forEach { (key, values) ->
if (!HttpUtils.containsSensitiveHeader(key)) {
if (values.size == 1) {
res[key] = values[0]
} else {
for ((i, value) in values.withIndex()) {
res["$key[$i]"] = value
}
}
}
}
return res
}

internal fun addBreadcrumb(
scopes: IScopes,
request: HttpRequest,
response: HttpResponse,
startTimestamp: Long?,
endTimestamp: Long?,
) {
val breadcrumb =
Breadcrumb.http(request.url.toString(), request.method.value, response.status.value)
breadcrumb.setData(
SpanDataConvention.HTTP_RESPONSE_CONTENT_LENGTH_KEY,
response.contentLength(),
)
if (startTimestamp != null) {
breadcrumb.setData(SpanDataConvention.HTTP_START_TIMESTAMP, startTimestamp)
}
if (endTimestamp != null) {
breadcrumb.setData(SpanDataConvention.HTTP_END_TIMESTAMP, endTimestamp)
}

val hint = Hint().also { it.set(TypeCheckHint.KTOR_REQUEST, request) }
hint[TypeCheckHint.KTOR_REQUEST] = request
hint[TypeCheckHint.KTOR_RESPONSE] = response

scopes.addBreadcrumb(breadcrumb, hint)
}
}
Loading
Loading