net.niebes.retrofit.metrics.MeasuredCall.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of retrofit-metrics Show documentation
Show all versions of retrofit-metrics Show documentation
Implementation to retry retrofit calls with resilience4j
The newest version!
package net.niebes.retrofit.metrics
import com.google.common.base.Stopwatch
import okhttp3.Request
import okio.Timeout
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MeasuredCall internal constructor(
private val wrappedCall: Call,
private val metrics: RetrofitCallMetricsCollector,
) : Call {
override fun execute(): Response {
val stopwatch = Stopwatch.createStarted()
val request = wrappedCall.request()
try {
val response = wrappedCall.execute()
metrics.measureRequestDuration(stopwatch.elapsed(), request, response, false)
return response
} catch (exception: Exception) {
metrics.measureRequestException(stopwatch.elapsed(), request, exception, false)
throw exception
}
}
override fun enqueue(callback: Callback) = wrappedCall.enqueue(measuredCallback(wrappedCall.request(), callback))
private fun measuredCallback(request: Request, callback: Callback): Callback = object : Callback {
val stopwatch = Stopwatch.createStarted()
override fun onResponse(call: Call, response: Response) {
metrics.measureRequestDuration(stopwatch.elapsed(), request, response, true)
callback.onResponse(call, response)
}
override fun onFailure(call: Call, throwable: Throwable) {
metrics.measureRequestException(stopwatch.elapsed(), request, throwable, true)
callback.onFailure(call, throwable)
}
}
override fun isExecuted(): Boolean = wrappedCall.isExecuted
override fun isCanceled(): Boolean = wrappedCall.isCanceled
override fun cancel() = wrappedCall.cancel()
override fun clone(): Call = MeasuredCall(wrappedCall.clone(), metrics)
override fun request(): Request = wrappedCall.request()
override fun timeout(): Timeout = wrappedCall.timeout()
}