|
| 1 | +package io.sentry.ktorClient |
| 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.BuildConfig |
| 12 | +import io.sentry.HttpStatusCodeRange |
| 13 | +import io.sentry.IScopes |
| 14 | +import io.sentry.ISpan |
| 15 | +import io.sentry.ScopesAdapter |
| 16 | +import io.sentry.Sentry |
| 17 | +import io.sentry.SentryDate |
| 18 | +import io.sentry.SentryIntegrationPackageStorage |
| 19 | +import io.sentry.SentryOptions |
| 20 | +import io.sentry.SpanStatus |
| 21 | +import io.sentry.kotlin.SentryContext |
| 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: HttpRequest): ISpan? |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Forcefully use the passed in scope instead of relying on the one injected by [SentryContext]. |
| 67 | + * Used for testing. |
| 68 | + */ |
| 69 | + internal var forceScopes: Boolean = false |
| 70 | +} |
| 71 | + |
| 72 | +internal const val SENTRY_KTOR_CLIENT_PLUGIN_KEY = "SentryKtorClientPlugin" |
| 73 | +internal const val TRACE_ORIGIN = "auto.http.ktor-client" |
| 74 | + |
| 75 | +/** |
| 76 | + * Sentry plugin for Ktor HTTP client that provides automatic instrumentation for HTTP requests, |
| 77 | + * including error capturing, request/response breadcrumbs, and distributed tracing. |
| 78 | + */ |
| 79 | +public val SentryKtorClientPlugin: ClientPlugin<SentryKtorClientPluginConfig> = |
| 80 | + createClientPlugin(SENTRY_KTOR_CLIENT_PLUGIN_KEY, ::SentryKtorClientPluginConfig) { |
| 81 | + // Init |
| 82 | + SentryIntegrationPackageStorage.getInstance() |
| 83 | + .addPackage("maven:io.sentry:sentry-ktor-client", BuildConfig.VERSION_NAME) |
| 84 | + addIntegrationToSdkVersion("KtorClient") |
| 85 | + |
| 86 | + // Options |
| 87 | + val scopes = pluginConfig.scopes |
| 88 | + val beforeSpan = pluginConfig.beforeSpan |
| 89 | + val captureFailedRequests = pluginConfig.captureFailedRequests |
| 90 | + val failedRequestStatusCodes = pluginConfig.failedRequestStatusCodes |
| 91 | + val failedRequestTargets = pluginConfig.failedRequestTargets |
| 92 | + val forceScopes = pluginConfig.forceScopes |
| 93 | + |
| 94 | + // Attributes |
| 95 | + // Request start time for breadcrumbs |
| 96 | + val requestStartTimestampKey = AttributeKey<SentryDate>("SentryRequestStartTimestamp") |
| 97 | + // Span associated with the request |
| 98 | + val requestSpanKey = AttributeKey<ISpan>("SentryRequestSpan") |
| 99 | + |
| 100 | + onRequest { request, _ -> |
| 101 | + request.attributes.put( |
| 102 | + requestStartTimestampKey, |
| 103 | + (if (forceScopes) scopes else Sentry.getCurrentScopes()).options.dateProvider.now(), |
| 104 | + ) |
| 105 | + |
| 106 | + val parentSpan: ISpan? = |
| 107 | + if (forceScopes) scopes.getSpan() |
| 108 | + else { |
| 109 | + if (Platform.isAndroid()) scopes.transaction else scopes.span |
| 110 | + } |
| 111 | + |
| 112 | + val spanOp = "http.client" |
| 113 | + val spanDescription = "${request.method.value.toString()} ${request.url.buildString()}" |
| 114 | + val span: ISpan? = parentSpan?.startChild(spanOp, spanDescription) |
| 115 | + if (span != null) { |
| 116 | + span.spanContext.origin = TRACE_ORIGIN |
| 117 | + request.attributes.put(requestSpanKey, span) |
| 118 | + } |
| 119 | + |
| 120 | + if ( |
| 121 | + !SpanUtils.isIgnored( |
| 122 | + (if (forceScopes) scopes else Sentry.getCurrentScopes()).options.getIgnoredSpanOrigins(), |
| 123 | + TRACE_ORIGIN, |
| 124 | + ) |
| 125 | + ) { |
| 126 | + TracingUtils.traceIfAllowed( |
| 127 | + if (forceScopes) scopes else Sentry.getCurrentScopes(), |
| 128 | + request.url.buildString(), |
| 129 | + request.headers.getAll(BaggageHeader.BAGGAGE_HEADER), |
| 130 | + span, |
| 131 | + ) |
| 132 | + ?.let { tracingHeaders -> |
| 133 | + request.headers[tracingHeaders.sentryTraceHeader.name] = |
| 134 | + tracingHeaders.sentryTraceHeader.value |
| 135 | + tracingHeaders.baggageHeader?.let { |
| 136 | + request.headers.remove(BaggageHeader.BAGGAGE_HEADER) |
| 137 | + request.headers[it.name] = it.value |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + client.requestPipeline.intercept(HttpRequestPipeline.Before) { |
| 144 | + try { |
| 145 | + proceed() |
| 146 | + } catch (t: Throwable) { |
| 147 | + context.attributes.getOrNull(requestSpanKey)?.apply { |
| 148 | + throwable = t |
| 149 | + status = SpanStatus.INTERNAL_ERROR |
| 150 | + finish() |
| 151 | + } |
| 152 | + throw t |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + onResponse { response -> |
| 157 | + val request = response.request |
| 158 | + val startTimestamp = response.call.attributes.getOrNull(requestStartTimestampKey) |
| 159 | + val endTimestamp = |
| 160 | + (if (forceScopes) scopes else Sentry.getCurrentScopes()).options.dateProvider.now() |
| 161 | + |
| 162 | + if ( |
| 163 | + captureFailedRequests && |
| 164 | + failedRequestStatusCodes.any { it.isInRange(response.status.value) } && |
| 165 | + PropagationTargetsUtils.contain(failedRequestTargets, request.url.toString()) |
| 166 | + ) { |
| 167 | + SentryKtorClientUtils.captureClientError(scopes, request, response) |
| 168 | + } |
| 169 | + |
| 170 | + SentryKtorClientUtils.addBreadcrumb(scopes, request, response, startTimestamp, endTimestamp) |
| 171 | + |
| 172 | + response.call.attributes.getOrNull(requestSpanKey)?.let { span -> |
| 173 | + var result: ISpan? = span |
| 174 | + |
| 175 | + if (beforeSpan != null) { |
| 176 | + result = beforeSpan.execute(span, request) |
| 177 | + } |
| 178 | + |
| 179 | + if (result == null) { |
| 180 | + // span is dropped |
| 181 | + span.spanContext.sampled = false |
| 182 | + } |
| 183 | + |
| 184 | + val spanStatus = SpanStatus.fromHttpStatusCode(response.status.value) |
| 185 | + span.finish(spanStatus, endTimestamp) |
| 186 | + } |
| 187 | + } |
| 188 | + |
| 189 | + on(SentryKtorClientPluginContextHook(scopes)) { block -> block() } |
| 190 | + } |
| 191 | + |
| 192 | +/** |
| 193 | + * Context hook to manage scopes during request handling. Forks the current scope and uses |
| 194 | + * [SentryContext] to ensure that the whole pipeline runs within the correct scopes. |
| 195 | + */ |
| 196 | +public open class SentryKtorClientPluginContextHook(protected val scopes: IScopes) : |
| 197 | + ClientHook<suspend (suspend () -> Unit) -> Unit> { |
| 198 | + private val phase = PipelinePhase("SentryKtorClientPluginContext") |
| 199 | + |
| 200 | + override fun install(client: HttpClient, handler: suspend (suspend () -> Unit) -> Unit) { |
| 201 | + client.requestPipeline.insertPhaseBefore(HttpRequestPipeline.Before, phase) |
| 202 | + client.requestPipeline.intercept(phase) { |
| 203 | + val scopes = |
| 204 | + this@SentryKtorClientPluginContextHook.scopes.forkedCurrentScope( |
| 205 | + SENTRY_KTOR_CLIENT_PLUGIN_KEY |
| 206 | + ) |
| 207 | + withContext(SentryContext(scopes)) { proceed() } |
| 208 | + } |
| 209 | + } |
| 210 | +} |
0 commit comments