|
| 1 | +package io.sentry.apollo3 |
| 2 | + |
| 3 | +import com.apollographql.apollo3.api.http.HttpHeader |
| 4 | +import com.apollographql.apollo3.api.http.HttpRequest |
| 5 | +import com.apollographql.apollo3.api.http.HttpResponse |
| 6 | +import com.apollographql.apollo3.exception.ApolloHttpException |
| 7 | +import com.apollographql.apollo3.exception.ApolloNetworkException |
| 8 | +import com.apollographql.apollo3.network.http.HttpInterceptor |
| 9 | +import com.apollographql.apollo3.network.http.HttpInterceptorChain |
| 10 | +import io.sentry.Breadcrumb |
| 11 | +import io.sentry.Hint |
| 12 | +import io.sentry.HubAdapter |
| 13 | +import io.sentry.IHub |
| 14 | +import io.sentry.ISpan |
| 15 | +import io.sentry.SentryLevel |
| 16 | +import io.sentry.SpanStatus |
| 17 | +import io.sentry.TracingOrigins |
| 18 | +import io.sentry.TypeCheckHint |
| 19 | + |
| 20 | +class SentryApollo3HttpInterceptor @JvmOverloads constructor(private val hub: IHub = HubAdapter.getInstance(), private val beforeSpan: BeforeSpanCallback? = null) : |
| 21 | + HttpInterceptor { |
| 22 | + |
| 23 | + override suspend fun intercept( |
| 24 | + request: HttpRequest, |
| 25 | + chain: HttpInterceptorChain |
| 26 | + ): HttpResponse { |
| 27 | + val activeSpan = hub.span |
| 28 | + return if (activeSpan == null) { |
| 29 | + chain.proceed(request) |
| 30 | + } else { |
| 31 | + val span = startChild(request, activeSpan) |
| 32 | + |
| 33 | + val cleanedHeaders = removeSentryInternalHeaders(request.headers) |
| 34 | + |
| 35 | + val requestBuilder = request.newBuilder().apply { |
| 36 | + headers(cleanedHeaders) |
| 37 | + } |
| 38 | + |
| 39 | + if (TracingOrigins.contain(hub.options.tracingOrigins, request.url)) { |
| 40 | + val sentryTraceHeader = span.toSentryTrace() |
| 41 | + val baggageHeader = span.toBaggageHeader() |
| 42 | + requestBuilder.addHeader(sentryTraceHeader.name, sentryTraceHeader.value) |
| 43 | + |
| 44 | + baggageHeader?.let { |
| 45 | + requestBuilder.addHeader(it.name, it.value) |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + val modifiedRequest = requestBuilder.build() |
| 50 | + var httpResponse: HttpResponse? = null |
| 51 | + var statusCode: Int? = null |
| 52 | + |
| 53 | + try { |
| 54 | + httpResponse = chain.proceed(modifiedRequest) |
| 55 | + statusCode = httpResponse.statusCode |
| 56 | + span.status = SpanStatus.fromHttpStatusCode(statusCode, SpanStatus.UNKNOWN) |
| 57 | + return httpResponse |
| 58 | + } catch (e: Throwable) { |
| 59 | + when (e) { |
| 60 | + is ApolloHttpException -> { |
| 61 | + statusCode = e.statusCode |
| 62 | + span.status = SpanStatus.fromHttpStatusCode(statusCode, SpanStatus.INTERNAL_ERROR) |
| 63 | + } |
| 64 | + is ApolloNetworkException -> span.status = SpanStatus.INTERNAL_ERROR |
| 65 | + else -> SpanStatus.INTERNAL_ERROR |
| 66 | + } |
| 67 | + span.throwable = e |
| 68 | + throw e |
| 69 | + } finally { |
| 70 | + finish(span, modifiedRequest, httpResponse, statusCode) |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + private fun removeSentryInternalHeaders(headers: List<HttpHeader>): List<HttpHeader> { |
| 76 | + return headers.filterNot { it.name == SENTRY_APOLLO_3_VARIABLES || it.name == SENTRY_APOLLO_3_OPERATION_NAME || it.name == SENTRY_APOLLO_3_OPERATION_TYPE } |
| 77 | + } |
| 78 | + |
| 79 | + private fun startChild(request: HttpRequest, activeSpan: ISpan): ISpan { |
| 80 | + val url = request.url |
| 81 | + val method = request.method |
| 82 | + |
| 83 | + val operationName = operationNameFromHeaders(request) |
| 84 | + val operation = operationName ?: "apollo.client" |
| 85 | + val operationType = request.valueForHeader(SENTRY_APOLLO_3_OPERATION_TYPE) ?: method |
| 86 | + val operationId = request.valueForHeader("X-APOLLO-OPERATION-ID") |
| 87 | + val variables = request.valueForHeader(SENTRY_APOLLO_3_VARIABLES) |
| 88 | + val description = "$operationType ${operationName ?: url}" |
| 89 | + |
| 90 | + return activeSpan.startChild(operation, description).apply { |
| 91 | + operationId?.let { |
| 92 | + setData("operationId", it) |
| 93 | + } |
| 94 | + |
| 95 | + variables?.let { |
| 96 | + setData("variables", it) |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + private fun operationNameFromHeaders(request: HttpRequest): String? { |
| 102 | + return request.valueForHeader(SENTRY_APOLLO_3_OPERATION_NAME) ?: request.valueForHeader("X-APOLLO-OPERATION-NAME") |
| 103 | + } |
| 104 | + |
| 105 | + private fun HttpRequest.valueForHeader(key: String) = headers.firstOrNull { it.name == key }?.value |
| 106 | + |
| 107 | + private fun finish(span: ISpan, request: HttpRequest, response: HttpResponse? = null, statusCode: Int?) { |
| 108 | + if (beforeSpan != null) { |
| 109 | + try { |
| 110 | + val result = beforeSpan.execute(span, request, response) |
| 111 | + if (result == null) { |
| 112 | + // Span is dropped |
| 113 | + span.spanContext.sampled = false |
| 114 | + } |
| 115 | + } catch (e: Throwable) { |
| 116 | + hub.options.logger.log(SentryLevel.ERROR, "An error occurred while executing beforeSpan on ApolloInterceptor", e) |
| 117 | + } |
| 118 | + } |
| 119 | + span.finish() |
| 120 | + |
| 121 | + val breadcrumb = |
| 122 | + Breadcrumb.http(request.url, request.method.name, statusCode) |
| 123 | + |
| 124 | + request.body?.contentLength.ifHasValidLength { contentLength -> |
| 125 | + breadcrumb.setData("request_body_size", contentLength) |
| 126 | + } |
| 127 | + |
| 128 | + val hint = Hint().also { |
| 129 | + it.set(TypeCheckHint.APOLLO_REQUEST, request) |
| 130 | + } |
| 131 | + |
| 132 | + response?.let { httpResponse -> |
| 133 | + // Content-Length header is not present on batched operations |
| 134 | + httpResponse.headersContentLength().ifHasValidLength { contentLength -> |
| 135 | + breadcrumb.setData("response_body_size", contentLength) |
| 136 | + } |
| 137 | + |
| 138 | + if (!breadcrumb.data.containsKey("response_body_size")) { |
| 139 | + httpResponse.body?.buffer?.size?.ifHasValidLength { contentLength -> |
| 140 | + breadcrumb.setData("response_body_size", contentLength) |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + hint.set(TypeCheckHint.APOLLO_RESPONSE, httpResponse) |
| 145 | + } |
| 146 | + |
| 147 | + hub.addBreadcrumb(breadcrumb, hint) |
| 148 | + } |
| 149 | + |
| 150 | + // Extensions |
| 151 | + |
| 152 | + private fun HttpResponse.headersContentLength(): Long { |
| 153 | + return headers.firstOrNull { it.name == "Content-Length" }?.value?.toLongOrNull() ?: -1L |
| 154 | + } |
| 155 | + |
| 156 | + private fun Long?.ifHasValidLength(fn: (Long) -> Unit) { |
| 157 | + if (this != null && this != -1L) { |
| 158 | + fn.invoke(this) |
| 159 | + } |
| 160 | + } |
| 161 | + |
| 162 | + /** |
| 163 | + * The BeforeSpan callback |
| 164 | + */ |
| 165 | + fun interface BeforeSpanCallback { |
| 166 | + /** |
| 167 | + * Mutates span before being added. |
| 168 | + * |
| 169 | + * @param span the span to mutate or drop |
| 170 | + * @param request the Apollo request object |
| 171 | + * @param response the Apollo response object |
| 172 | + */ |
| 173 | + fun execute(span: ISpan, request: HttpRequest, response: HttpResponse?): ISpan? |
| 174 | + } |
| 175 | + |
| 176 | + companion object { |
| 177 | + const val SENTRY_APOLLO_3_VARIABLES = "SENTRY-APOLLO-3-VARIABLES" |
| 178 | + const val SENTRY_APOLLO_3_OPERATION_NAME = "SENTRY-APOLLO-3-OPERATION-NAME" |
| 179 | + const val SENTRY_APOLLO_3_OPERATION_TYPE = "SENTRY-APOLLO-3-OPERATION-TYPE" |
| 180 | + } |
| 181 | +} |
0 commit comments