-
-
Notifications
You must be signed in to change notification settings - Fork 468
Expand file tree
/
Copy pathSentryOkHttpInterceptor.kt
More file actions
389 lines (338 loc) · 12.8 KB
/
SentryOkHttpInterceptor.kt
File metadata and controls
389 lines (338 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package io.sentry.okhttp
import io.sentry.BaggageHeader
import io.sentry.Breadcrumb
import io.sentry.Hint
import io.sentry.HttpStatusCodeRange
import io.sentry.IScopes
import io.sentry.ISpan
import io.sentry.ScopesAdapter
import io.sentry.SentryIntegrationPackageStorage
import io.sentry.SentryOptions.DEFAULT_PROPAGATION_TARGETS
import io.sentry.SpanDataConvention
import io.sentry.SpanStatus
import io.sentry.TypeCheckHint.OKHTTP_REQUEST
import io.sentry.TypeCheckHint.OKHTTP_RESPONSE
import io.sentry.okhttp.SentryOkHttpInterceptor.BeforeSpanCallback
import io.sentry.transport.CurrentDateProvider
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 io.sentry.util.UrlUtils
import io.sentry.util.network.NetworkRequestData
import io.sentry.util.network.ReplayNetworkRequestOrResponse
import java.io.IOException
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
/**
* The Sentry's [SentryOkHttpInterceptor], it will automatically add a breadcrumb and start a span
* out of the active span bound to the scope for each HTTP Request. If [captureFailedRequests] is
* enabled, the SDK will capture HTTP Client errors as well.
*
* @param scopes The [IScopes], internal and only used for testing.
* @param beforeSpan The [ISpan] can be customized or dropped with the [BeforeSpanCallback].
* @param captureFailedRequests The SDK will only capture HTTP Client errors if it is enabled,
* Defaults to true.
* @param failedRequestStatusCodes The SDK will only capture HTTP Client errors if the HTTP Response
* status code is within the defined ranges.
* @param failedRequestTargets The SDK will only capture HTTP Client errors if the HTTP Request URL
* is a match for any of the defined targets.
*/
public open class SentryOkHttpInterceptor(
private val scopes: IScopes = ScopesAdapter.getInstance(),
private val beforeSpan: BeforeSpanCallback? = null,
private val captureFailedRequests: Boolean = true,
private val failedRequestStatusCodes: List<HttpStatusCodeRange> =
listOf(HttpStatusCodeRange(HttpStatusCodeRange.DEFAULT_MIN, HttpStatusCodeRange.DEFAULT_MAX)),
private val failedRequestTargets: List<String> = listOf(DEFAULT_PROPAGATION_TARGETS),
) : Interceptor {
private companion object {
init {
SentryIntegrationPackageStorage.getInstance()
.addPackage("maven:io.sentry:sentry-okhttp", BuildConfig.VERSION_NAME)
}
}
public constructor() : this(ScopesAdapter.getInstance())
public constructor(scopes: IScopes) : this(scopes, null)
public constructor(beforeSpan: BeforeSpanCallback) : this(ScopesAdapter.getInstance(), beforeSpan)
init {
addIntegrationToSdkVersion("OkHttp")
}
@Suppress("LongMethod")
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
val urlDetails = UrlUtils.parse(request.url.toString())
val url = urlDetails.urlOrFallback
val method = request.method
val span: ISpan?
val okHttpEvent: SentryOkHttpEvent?
if (SentryOkHttpEventListener.eventMap.containsKey(chain.call())) {
// read the span from the event listener
okHttpEvent = SentryOkHttpEventListener.eventMap[chain.call()]
span = okHttpEvent?.callSpan
} else {
// read the span from the bound scope
okHttpEvent = null
val parentSpan = if (Platform.isAndroid()) scopes.transaction else scopes.span
span = parentSpan?.startChild("http.client", "$method $url")
}
val startTimestamp = CurrentDateProvider.getInstance().currentTimeMillis
span?.spanContext?.origin = TRACE_ORIGIN
urlDetails.applyToSpan(span)
val isFromEventListener = okHttpEvent != null
var response: Response? = null
var code: Int? = null
try {
val requestBuilder = request.newBuilder()
if (!isIgnored()) {
TracingUtils.traceIfAllowed(
scopes,
request.url.toString(),
request.headers(BaggageHeader.BAGGAGE_HEADER),
span,
)
?.let { tracingHeaders ->
requestBuilder.addHeader(
tracingHeaders.sentryTraceHeader.name,
tracingHeaders.sentryTraceHeader.value,
)
tracingHeaders.baggageHeader?.let {
requestBuilder.removeHeader(BaggageHeader.BAGGAGE_HEADER)
requestBuilder.addHeader(it.name, it.value)
}
tracingHeaders.w3cTraceparentHeader?.let { requestBuilder.addHeader(it.name, it.value) }
}
}
request = requestBuilder.build()
response = chain.proceed(request)
code = response.code
span?.setData(SpanDataConvention.HTTP_STATUS_CODE_KEY, code)
span?.status = SpanStatus.fromHttpStatusCode(code)
// OkHttp errors (4xx, 5xx) don't throw, so it's safe to call within this block.
// breadcrumbs are added on the finally block because we'd like to know if the device
// had an unstable connection or something similar
if (shouldCaptureClientError(request, response)) {
// If we capture the client error directly, it could be associated with the
// currently running span by the backend. In case the listener is in use, that is
// an inner span. So, if the listener is in use, we let it capture the client
// error, to shown it in the http root call span in the dashboard.
if (isFromEventListener && okHttpEvent != null) {
okHttpEvent.setClientErrorResponse(response)
} else {
SentryOkHttpUtils.captureClientError(scopes, request, response)
}
}
return response
} catch (e: IOException) {
span?.apply {
this.throwable = e
this.status = SpanStatus.INTERNAL_ERROR
}
throw e
} finally {
// interceptors may change the request details, so let's update it here
// this only works correctly if SentryOkHttpInterceptor is the last one in the chain
okHttpEvent?.setRequest(request)
finishSpan(span, request, response, isFromEventListener, okHttpEvent)
// The SentryOkHttpEventListener will send the breadcrumb itself if used for this call
if (!isFromEventListener) {
sendBreadcrumb(request, code, response, startTimestamp)
}
}
}
private fun isIgnored(): Boolean =
SpanUtils.isIgnored(scopes.getOptions().getIgnoredSpanOrigins(), TRACE_ORIGIN)
private fun sendBreadcrumb(
request: Request,
code: Int?,
response: Response?,
startTimestamp: Long,
) {
val breadcrumb = Breadcrumb.http(request.url.toString(), request.method, code)
// Track request and response body sizes for the breadcrumb
var requestBodySize: Long? = null
var responseBodySize: Long? = null
request.body?.contentLength().ifHasValidLength {
breadcrumb.setData("http.request_content_length", it)
requestBodySize = it
}
response?.body?.contentLength().ifHasValidLength {
breadcrumb.setData(SpanDataConvention.HTTP_RESPONSE_CONTENT_LENGTH_KEY, it)
responseBodySize = it
}
val hint = Hint().also {
// Set the structured network data for replay
val networkData = createNetworkRequestData(request, response, requestBodySize, responseBodySize)
it.set("replay:networkDetails", networkData)
// it.set(OKHTTP_REQUEST, request)
// response?.let { resp -> it[OKHTTP_RESPONSE] = resp }
}
// needs this as unix timestamp for rrweb
breadcrumb.setData(SpanDataConvention.HTTP_START_TIMESTAMP, startTimestamp)
breadcrumb.setData(
SpanDataConvention.HTTP_END_TIMESTAMP,
CurrentDateProvider.getInstance().currentTimeMillis,
)
scopes.addBreadcrumb(breadcrumb, hint)
}
/**
* Extracts headers from OkHttp Headers object into a map
*/
private fun okhttp3.Headers.toMap(): Map<String, String> {
val headers = mutableMapOf<String, String>()
for (name in names()) {
headers[name] = get(name) ?: ""
}
return headers
}
/**
* Extracts body metadata from OkHttp RequestBody or ResponseBody
* Note: We don't consume the actual body stream to avoid interfering with the request/response
*/
private fun extractBodyMetadata(
contentLength: Long?,
contentType: okhttp3.MediaType?
): Pair<Long?, Any?> {
val bodySize = contentLength?.takeIf { it >= 0 }
val bodyInfo = if (contentLength != null && contentLength != 0L) {
mapOf(
"contentType" to contentType?.toString(),
"hasBody" to true
)
} else null
return bodySize to bodyInfo
}
/**
* Creates a NetworkRequestData object from the request and response
*/
private fun createNetworkRequestData(
request: Request,
response: Response?,
requestBodySize: Long?,
responseBodySize: Long?
): NetworkRequestData {
// Log the incoming request details
println("SentryNetwork: Creating NetworkRequestData for: ${request.method} ${request.url}")
scopes.options.logger.log(
io.sentry.SentryLevel.INFO,
"SentryNetwork: Creating NetworkRequestData for: ${request.method} ${request.url}"
)
// Extract request data
val requestHeaders = request.headers.toMap()
val (reqBodySize, reqBodyInfo) = extractBodyMetadata(
request.body?.contentLength(),
request.body?.contentType()
)
scopes.options.logger.log(
io.sentry.SentryLevel.INFO,
"SentryNetwork: Request - Headers count: ${requestHeaders.size}, Body size: $reqBodySize, Body info: $reqBodyInfo"
)
val requestData = ReplayNetworkRequestOrResponse(
reqBodySize,
reqBodyInfo,
requestHeaders
)
// Extract response data if available
val responseData = response?.let {
val responseHeaders = it.headers.toMap()
val (respBodySize, respBodyInfo) = extractBodyMetadata(
it.body?.contentLength(),
it.body?.contentType()
)
scopes.options.logger.log(
io.sentry.SentryLevel.INFO,
"SentryNetwork: Response - Status: ${it.code}, Headers count: ${responseHeaders.size}, Body size: $respBodySize, Body info: $respBodyInfo"
)
ReplayNetworkRequestOrResponse(
respBodySize,
respBodyInfo,
responseHeaders
)
}
// Determine final body sizes (prefer the explicit sizes passed in)
val finalResponseBodySize = response?.let {
val (respBodySize, _) = extractBodyMetadata(
it.body?.contentLength(),
it.body?.contentType()
)
responseBodySize ?: respBodySize
}
val networkData = NetworkRequestData(
request.method,
response?.code,
requestBodySize ?: reqBodySize,
finalResponseBodySize,
requestData,
responseData
)
scopes.options.logger.log(
io.sentry.SentryLevel.INFO,
"SentryNetwork: Created NetworkRequestData: $networkData"
)
return networkData
}
private fun finishSpan(
span: ISpan?,
request: Request,
response: Response?,
isFromEventListener: Boolean,
okHttpEvent: SentryOkHttpEvent?,
) {
if (span == null) {
// tracing can be disabled, or there can be no active span, but we still want to finalize the
// OkHttpEvent when both SentryOkHttpInterceptor and SentryOkHttpEventListener are used
okHttpEvent?.finish()
return
}
if (beforeSpan != null) {
val result = beforeSpan.execute(span, request, response)
if (result == null) {
// span is dropped
span.spanContext.sampled = false
}
}
if (!isFromEventListener) {
span.finish()
}
// The SentryOkHttpEventListener waits until the response is closed (which may never happen), so
// we close it here
okHttpEvent?.finish()
}
private fun Long?.ifHasValidLength(fn: (Long) -> Unit) {
if (this != null && this != -1L) {
fn.invoke(this)
}
}
private fun shouldCaptureClientError(request: Request, response: Response): Boolean {
// return if the feature is disabled or its not within the range
if (!captureFailedRequests || !containsStatusCode(response.code)) {
return false
}
// return if its not a target match
if (!PropagationTargetsUtils.contain(failedRequestTargets, request.url.toString())) {
return false
}
return true
}
private fun containsStatusCode(statusCode: Int): Boolean {
for (item in failedRequestStatusCodes) {
if (item.isInRange(statusCode)) {
return true
}
}
return false
}
/** The BeforeSpan callback */
public fun interface BeforeSpanCallback {
/**
* Mutates or drops span before being added
*
* @param span the span to mutate or drop
* @param request the HTTP request executed by okHttp
* @param response the HTTP response received by okHttp
*/
public fun execute(span: ISpan, request: Request, response: Response?): ISpan?
}
}