https://kotlinlang.org logo
#ktor
Title
# ktor
g

gotoOla

07/08/2019, 3:39 PM
@tseisel don’t know about any such built in behavior but when we’ve come across such use cases in my team we have used kotlins repeat and in some cases just written extensions
t

tseisel

07/08/2019, 3:42 PM
Based on the implementation of
HttpRedirect
, I wrote a feature that automatically retry a request after the given delay if it received the Http Code "Too Many Requests" :
Copy code
class RetryAfter {
    companion object : HttpClientFeature<Unit, RetryAfter> {
        override val key: AttributeKey<RetryAfter> = AttributeKey("RetryFeature")

        override fun prepare(block: Unit.() -> Unit): RetryAfter = RetryAfter()

        override fun install(feature: RetryAfter, scope: HttpClient) {
            scope.feature(HttpSend)!!.intercept { origin ->
                val status = origin.response.status
                val retryAfterSeconds = origin.response.headers[HttpHeaders.RetryAfter]?.toLongOrNull()

                if (status != HttpStatusCode.TooManyRequests || retryAfterSeconds == null) {
                    origin
                } else {
                    origin.close()
                    delay((retryAfterSeconds + 1) * 1000)

                    execute(HttpRequestBuilder().apply {
                        takeFrom(origin.request)
                    })
                }
            }
        }
    }
}
5 Views