|
| 1 | +package io.sentry.ktor |
| 2 | + |
| 3 | +import io.ktor.client.HttpClient |
| 4 | +import io.ktor.client.plugins.api.* |
| 5 | +import io.ktor.client.plugins.api.ClientPlugin |
| 6 | +import io.ktor.client.request.* |
| 7 | +import io.ktor.client.statement.* |
| 8 | +import io.ktor.util.* |
| 9 | +import io.ktor.util.pipeline.* |
| 10 | +import io.sentry.BaggageHeader |
| 11 | +import io.sentry.HttpStatusCodeRange |
| 12 | +import io.sentry.IScopes |
| 13 | +import io.sentry.ISpan |
| 14 | +import io.sentry.ScopesAdapter |
| 15 | +import io.sentry.Sentry |
| 16 | +import io.sentry.SentryIntegrationPackageStorage |
| 17 | +import io.sentry.SentryLongDate |
| 18 | +import io.sentry.SentryOptions |
| 19 | +import io.sentry.SpanStatus |
| 20 | +import io.sentry.kotlin.SentryContext |
| 21 | +import io.sentry.transport.CurrentDateProvider |
| 22 | +import io.sentry.util.IntegrationUtils.addIntegrationToSdkVersion |
| 23 | +import io.sentry.util.Platform |
| 24 | +import io.sentry.util.PropagationTargetsUtils |
| 25 | +import io.sentry.util.SpanUtils |
| 26 | +import io.sentry.util.TracingUtils |
| 27 | +import kotlinx.coroutines.withContext |
| 28 | + |
| 29 | +/** Configuration for the Sentry Ktor client plugin. */ |
| 30 | +public class SentryKtorClientPluginConfig { |
| 31 | + /** The [IScopes] instance to use. Defaults to [ScopesAdapter.getInstance]. */ |
| 32 | + public var scopes: IScopes = ScopesAdapter.getInstance() |
| 33 | + |
| 34 | + /** Callback to customize or drop spans before they are created. Return null to drop the span. */ |
| 35 | + public var beforeSpan: BeforeSpanCallback? = null |
| 36 | + |
| 37 | + /** Whether to capture HTTP client errors as Sentry events. Defaults to true. */ |
| 38 | + public var captureFailedRequests: Boolean = true |
| 39 | + |
| 40 | + /** |
| 41 | + * The HTTP status code ranges that should be considered as failed requests. Defaults to 500-599 |
| 42 | + * (server errors). |
| 43 | + */ |
| 44 | + public var failedRequestStatusCodes: List<HttpStatusCodeRange> = |
| 45 | + listOf(HttpStatusCodeRange(HttpStatusCodeRange.DEFAULT_MIN, HttpStatusCodeRange.DEFAULT_MAX)) |
| 46 | + |
| 47 | + /** |
| 48 | + * The list of targets (URLs) for which failed requests should be captured. Supports regex |
| 49 | + * patterns. Defaults to capture all requests. |
| 50 | + */ |
| 51 | + public var failedRequestTargets: List<String> = listOf(SentryOptions.DEFAULT_PROPAGATION_TARGETS) |
| 52 | + |
| 53 | + /** Callback interface for customizing spans before they are created. */ |
| 54 | + public fun interface BeforeSpanCallback { |
| 55 | + /** |
| 56 | + * Customize or drop a span before it's created. |
| 57 | + * |
| 58 | + * @param span The span to customize |
| 59 | + * @param request The HTTP request being executed |
| 60 | + * @return The customized span, or null to drop the span |
| 61 | + */ |
| 62 | + public fun execute(span: ISpan, request: HttpRequestBuilder): ISpan? |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +internal const val SENTRY_KTOR_CLIENT_PLUGIN_KEY = "SentryKtorClientPlugin" |
| 67 | +internal const val TRACE_ORIGIN = "auto.http.ktor" |
| 68 | + |
| 69 | +/** |
| 70 | + * Sentry plugin for Ktor HTTP client that provides automatic instrumentation for HTTP requests, |
| 71 | + * including distributed tracing, breadcrumbs, and error capturing. |
| 72 | + */ |
| 73 | +public val SentryKtorClientPlugin: ClientPlugin<SentryKtorClientPluginConfig> = |
| 74 | + createClientPlugin(SENTRY_KTOR_CLIENT_PLUGIN_KEY, ::SentryKtorClientPluginConfig) { |
| 75 | + // Init |
| 76 | + SentryIntegrationPackageStorage.getInstance() |
| 77 | + .addPackage("maven:io.sentry:sentry-ktor", BuildConfig.VERSION_NAME) |
| 78 | + addIntegrationToSdkVersion("Ktor") |
| 79 | + |
| 80 | + // Options |
| 81 | + val scopes = pluginConfig.scopes |
| 82 | + val captureFailedRequests = pluginConfig.captureFailedRequests |
| 83 | + val failedRequestStatusCodes = pluginConfig.failedRequestStatusCodes |
| 84 | + val failedRequestTargets = pluginConfig.failedRequestTargets |
| 85 | + |
| 86 | + // Attributes |
| 87 | + // Request start time for breadcrumbs |
| 88 | + val requestStartTimestampKey = AttributeKey<Long>("SentryRequestStartTimestamp") |
| 89 | + // Span associated with the request |
| 90 | + val requestSpanKey = AttributeKey<ISpan>("SentryRequestSpan") |
| 91 | + |
| 92 | + onRequest { request, _ -> |
| 93 | + request.attributes.put( |
| 94 | + requestStartTimestampKey, |
| 95 | + CurrentDateProvider.getInstance().currentTimeMillis, |
| 96 | + ) |
| 97 | + |
| 98 | + val parentSpan = if (Platform.isAndroid()) scopes.transaction else scopes.span |
| 99 | + val spanOp = "http.client" |
| 100 | + val spanDescription = "${request.method.value.toString()} ${request.url.buildString()}" |
| 101 | + val span = |
| 102 | + if (parentSpan != null) parentSpan.startChild(spanOp, spanDescription) |
| 103 | + else Sentry.startTransaction(spanDescription, spanOp) |
| 104 | + request.attributes.put(requestSpanKey, span) |
| 105 | + |
| 106 | + if (SpanUtils.isIgnored(scopes.getOptions().getIgnoredSpanOrigins(), TRACE_ORIGIN)) { |
| 107 | + TracingUtils.traceIfAllowed( |
| 108 | + scopes, |
| 109 | + request.url.buildString(), |
| 110 | + request.headers.getAll(BaggageHeader.BAGGAGE_HEADER), |
| 111 | + span, |
| 112 | + ) |
| 113 | + ?.let { tracingHeaders -> |
| 114 | + request.headers[tracingHeaders.sentryTraceHeader.name] = |
| 115 | + tracingHeaders.sentryTraceHeader.value |
| 116 | + tracingHeaders.baggageHeader?.let { |
| 117 | + request.headers.remove(BaggageHeader.BAGGAGE_HEADER) |
| 118 | + request.headers[it.name] = it.value |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + onResponse { response -> |
| 125 | + val request = response.request |
| 126 | + val startTimestamp = response.call.attributes.getOrNull(requestStartTimestampKey) |
| 127 | + val endTimestamp = CurrentDateProvider.getInstance().currentTimeMillis |
| 128 | + |
| 129 | + if ( |
| 130 | + captureFailedRequests && |
| 131 | + failedRequestStatusCodes.any { it.isInRange(response.status.value) } && |
| 132 | + PropagationTargetsUtils.contain(failedRequestTargets, request.url.toString()) |
| 133 | + ) { |
| 134 | + SentryKtorClientUtils.captureClientError(scopes, request, response) |
| 135 | + } |
| 136 | + |
| 137 | + SentryKtorClientUtils.addBreadcrumb(scopes, request, response, startTimestamp, endTimestamp) |
| 138 | + |
| 139 | + response.call.attributes.getOrNull(requestSpanKey)?.let { span -> |
| 140 | + val spanStatus = SpanStatus.fromHttpStatusCode(response.status.value) |
| 141 | + span.finish(spanStatus, SentryLongDate(endTimestamp * 1000)) |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + on(SentryKtorClientPluginContextHook()) { block -> block() } |
| 146 | + } |
| 147 | + |
| 148 | +public open class SentryKtorClientPluginContextHook : |
| 149 | + ClientHook<suspend (suspend () -> Unit) -> Unit> { |
| 150 | + private val phase = PipelinePhase("SentryKtorClientPluginContext") |
| 151 | + |
| 152 | + override fun install(client: HttpClient, handler: suspend (suspend () -> Unit) -> Unit) { |
| 153 | + client.requestPipeline.insertPhaseBefore(HttpRequestPipeline.Before, phase) |
| 154 | + client.requestPipeline.intercept(phase) { |
| 155 | + withContext(SentryContext(Sentry.forkedCurrentScope(SENTRY_KTOR_CLIENT_PLUGIN_KEY))) { |
| 156 | + proceed() |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | +} |
0 commit comments