-
-
Notifications
You must be signed in to change notification settings - Fork 463
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
Merged
Merged
Changes from 35 commits
Commits
Show all changes
37 commits
Select commit
Hold shift + click to select a range
5645889
Add Ktor client integration
lcian 93b4a83
tracing
lcian f9538d5
improve
lcian 26372fe
fix scopes and stuff
lcian c01a756
Format code
getsentry-bot ecaf243
improve
lcian 61e714e
work
lcian 82c54aa
improve
lcian ad4abc9
improve
lcian eb3db76
improve
lcian 7d8dcd1
improve
lcian 0c58628
Merge branch 'main' into lcian/feat/ktor-client
lcian 80fb52f
changelog
lcian 665b6ec
improve
lcian d0a408b
improve
lcian 0765227
improve
lcian 26a7e07
Merge branch 'main' into lcian/feat/ktor-client
lcian 236ea9e
Merge branch 'main' into lcian/feat/ktor-client
lcian b6aeec5
changelog
lcian 8b75851
address feedback from code review
lcian 8816597
Merge branch 'main' into lcian/feat/ktor-client
lcian 5b439dc
improve
lcian 8499b5d
improve
lcian e9a5b48
improve
lcian d050c7b
improve
lcian 998f52c
improve
lcian 2aae940
address Seer
lcian ae6ec68
revert non-working OkHttp detection, and finish addressing Seer
lcian 8a42315
okhttp detection
lcian b0f5803
improve
lcian 38220c9
remove okhttp instrumentation detection
lcian e8671f2
Merge branch 'main' into lcian/feat/ktor-client
lcian f3044e1
improve
lcian 5382d70
improve
lcian 3c650dd
name
lcian c0027c2
readme
lcian 8763d70
change scopes
lcian File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| public final class io/sentry/ktorClient/BuildConfig { | ||
| public static final field SENTRY_KTOR_CLIENT_SDK_NAME Ljava/lang/String; | ||
| public static final field VERSION_NAME Ljava/lang/String; | ||
| } | ||
|
|
||
| public final class io/sentry/ktorClient/SentryKtorClientPluginConfig { | ||
| public fun <init> ()V | ||
| public final fun getBeforeSpan ()Lio/sentry/ktorClient/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/ktorClient/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/ktorClient/SentryKtorClientPluginConfig$BeforeSpanCallback { | ||
| public abstract fun execute (Lio/sentry/ISpan;Lio/ktor/client/request/HttpRequest;)Lio/sentry/ISpan; | ||
| } | ||
|
|
||
| public class io/sentry/ktorClient/SentryKtorClientPluginContextHook : io/ktor/client/plugins/api/ClientHook { | ||
| public fun <init> (Lio/sentry/IScopes;)V | ||
| protected final fun getScopes ()Lio/sentry/IScopes; | ||
| 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/ktorClient/SentryKtorClientPluginKt { | ||
| public static final fun getSentryKtorClientPlugin ()Lio/ktor/client/plugins/api/ClientPlugin; | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| 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)) | ||
| api(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.ktorClient") | ||
| buildConfigField( | ||
| "String", | ||
| "SENTRY_KTOR_CLIENT_SDK_NAME", | ||
| "\"${Config.Sentry.SENTRY_KTOR_CLIENT_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_CLIENT_SDK_NAME, | ||
| "Sentry-SDK-Package-Name" to "maven:io.sentry:sentry-ktor-client", | ||
| "Implementation-Vendor" to "Sentry", | ||
| "Implementation-Title" to project.name, | ||
| "Implementation-Version" to project.version, | ||
| ) | ||
| } | ||
| } | ||
210 changes: 210 additions & 0 deletions
210
sentry-ktor-client/src/main/java/io/sentry/ktorClient/SentryKtorClientPlugin.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,210 @@ | ||
| package io.sentry.ktorClient | ||
|
|
||
| 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.BaggageHeader | ||
| import io.sentry.BuildConfig | ||
| import io.sentry.HttpStatusCodeRange | ||
| import io.sentry.IScopes | ||
| import io.sentry.ISpan | ||
| import io.sentry.ScopesAdapter | ||
| import io.sentry.Sentry | ||
| import io.sentry.SentryDate | ||
| import io.sentry.SentryIntegrationPackageStorage | ||
| import io.sentry.SentryOptions | ||
| import io.sentry.SpanStatus | ||
| import io.sentry.kotlin.SentryContext | ||
| import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion | ||
| import io.sentry.util.Platform | ||
| import io.sentry.util.PropagationTargetsUtils | ||
| import io.sentry.util.SpanUtils | ||
| import io.sentry.util.TracingUtils | ||
| 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. */ | ||
lcian marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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: HttpRequest): ISpan? | ||
| } | ||
|
|
||
| /** | ||
| * Forcefully use the passed in scope instead of relying on the one injected by [SentryContext]. | ||
| * Used for testing. | ||
| */ | ||
| internal var forceScopes: Boolean = false | ||
| } | ||
|
|
||
| internal const val SENTRY_KTOR_CLIENT_PLUGIN_KEY = "SentryKtorClientPlugin" | ||
| internal const val TRACE_ORIGIN = "auto.http.ktor-client" | ||
|
|
||
| /** | ||
| * Sentry plugin for Ktor HTTP client that provides automatic instrumentation for HTTP requests, | ||
| * including error capturing, request/response breadcrumbs, and distributed tracing. | ||
| */ | ||
| public val SentryKtorClientPlugin: ClientPlugin<SentryKtorClientPluginConfig> = | ||
| createClientPlugin(SENTRY_KTOR_CLIENT_PLUGIN_KEY, ::SentryKtorClientPluginConfig) { | ||
| // Init | ||
| SentryIntegrationPackageStorage.getInstance() | ||
| .addPackage("maven:io.sentry:sentry-ktor-client", BuildConfig.VERSION_NAME) | ||
| addIntegrationToSdkVersion("KtorClient") | ||
|
|
||
| // Options | ||
| val scopes = pluginConfig.scopes | ||
| val beforeSpan = pluginConfig.beforeSpan | ||
| val captureFailedRequests = pluginConfig.captureFailedRequests | ||
| val failedRequestStatusCodes = pluginConfig.failedRequestStatusCodes | ||
| val failedRequestTargets = pluginConfig.failedRequestTargets | ||
| val forceScopes = pluginConfig.forceScopes | ||
|
|
||
| // Attributes | ||
| // Request start time for breadcrumbs | ||
| val requestStartTimestampKey = AttributeKey<SentryDate>("SentryRequestStartTimestamp") | ||
| // Span associated with the request | ||
| val requestSpanKey = AttributeKey<ISpan>("SentryRequestSpan") | ||
lcian marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| onRequest { request, _ -> | ||
| request.attributes.put( | ||
| requestStartTimestampKey, | ||
| (if (forceScopes) scopes else Sentry.getCurrentScopes()).options.dateProvider.now(), | ||
| ) | ||
|
|
||
| val parentSpan: ISpan? = | ||
| if (forceScopes) scopes.getSpan() | ||
| else { | ||
| if (Platform.isAndroid()) scopes.transaction else scopes.span | ||
| } | ||
|
|
||
| val spanOp = "http.client" | ||
| val spanDescription = "${request.method.value.toString()} ${request.url.buildString()}" | ||
| val span: ISpan? = parentSpan?.startChild(spanOp, spanDescription) | ||
| if (span != null) { | ||
| span.spanContext.origin = TRACE_ORIGIN | ||
| request.attributes.put(requestSpanKey, span) | ||
| } | ||
|
|
||
| if ( | ||
| !SpanUtils.isIgnored( | ||
| (if (forceScopes) scopes else Sentry.getCurrentScopes()).options.getIgnoredSpanOrigins(), | ||
| TRACE_ORIGIN, | ||
| ) | ||
lcian marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) { | ||
| TracingUtils.traceIfAllowed( | ||
| if (forceScopes) scopes else Sentry.getCurrentScopes(), | ||
| request.url.buildString(), | ||
| request.headers.getAll(BaggageHeader.BAGGAGE_HEADER), | ||
| span, | ||
| ) | ||
| ?.let { tracingHeaders -> | ||
| request.headers[tracingHeaders.sentryTraceHeader.name] = | ||
| tracingHeaders.sentryTraceHeader.value | ||
| tracingHeaders.baggageHeader?.let { | ||
| request.headers.remove(BaggageHeader.BAGGAGE_HEADER) | ||
| request.headers[it.name] = it.value | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| client.requestPipeline.intercept(HttpRequestPipeline.Before) { | ||
| try { | ||
| proceed() | ||
| } catch (t: Throwable) { | ||
| context.attributes.getOrNull(requestSpanKey)?.apply { | ||
| throwable = t | ||
| status = SpanStatus.INTERNAL_ERROR | ||
| finish() | ||
| } | ||
| throw t | ||
| } | ||
| } | ||
|
|
||
| onResponse { response -> | ||
| val request = response.request | ||
| val startTimestamp = response.call.attributes.getOrNull(requestStartTimestampKey) | ||
lcian marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| val endTimestamp = | ||
| (if (forceScopes) scopes else Sentry.getCurrentScopes()).options.dateProvider.now() | ||
|
|
||
| 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) | ||
lcian marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| response.call.attributes.getOrNull(requestSpanKey)?.let { span -> | ||
| var result: ISpan? = span | ||
lcian marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| if (beforeSpan != null) { | ||
| result = beforeSpan.execute(span, request) | ||
| } | ||
|
|
||
| if (result == null) { | ||
| // span is dropped | ||
| span.spanContext.sampled = false | ||
| } | ||
lcian marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| val spanStatus = SpanStatus.fromHttpStatusCode(response.status.value) | ||
| span.finish(spanStatus, endTimestamp) | ||
| } | ||
| } | ||
|
|
||
| on(SentryKtorClientPluginContextHook(scopes)) { block -> block() } | ||
| } | ||
|
|
||
| /** | ||
| * Context hook to manage scopes during request handling. Forks the current scope and uses | ||
| * [SentryContext] to ensure that the whole pipeline runs within the correct scopes. | ||
| */ | ||
| public open class SentryKtorClientPluginContextHook(protected val scopes: IScopes) : | ||
| 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) { | ||
| val scopes = | ||
| [email protected]( | ||
| SENTRY_KTOR_CLIENT_PLUGIN_KEY | ||
| ) | ||
| withContext(SentryContext(scopes)) { proceed() } | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.