Giter VIP home page Giter VIP logo

Comments (5)

eliekarouz avatar eliekarouz commented on June 15, 2024

Hello, I was going to open an issue right now but I found this one as it looks very similar:

On iOS and Android, the refresh token API is being triggered. I get the new token and save it but when the RefreshTokenFeature retries the request, I never get a result as if some "deadlock" occurred inside Ktor.

val requestBuilder = HttpRequestBuilder().takeFrom(context.request)
val result: HttpResponse = context.client!!.request(requestBuilder) // This call never returns...

I tried to debug a little bit inside Ktor but it's a bit hard to know what could cause this behavior as I am still new to coroutines.

I am using the coroutines 1.3.9-native-mt on Kotlin 1.4.10.

from moko-network.

Alex009 avatar Alex009 commented on June 15, 2024

@kovalandrew maybe help:

Gael Ribes:fr:  1 hour ago
I created a Ktor Client Feature for that.
override fun install(feature: AuthFeature, scope: HttpClient) {
    scope.requestPipeline.intercept(HttpRequestPipeline.State) {
        if (context.usesAuthentication) {
            val token = feature.authTokenService.getToken() ?: return@intercept
            context.headers[HttpHeaders.Authorization] = "Bearer $token"
        }
    }
    val circuitBreaker = AttributeKey<Unit>("my-auth-request")
    scope.feature(HttpSend)!!.intercept { origin, context ->
        if (origin.response.status != HttpStatusCode.Unauthorized) return@intercept origin
        if (origin.request.attributes.contains(circuitBreaker)) return@intercept origin
        if (!feature.authTokenService.refreshToken()) return@intercept origin
        val token = feature.authTokenService.getToken() ?: return@intercept origin
        val request = HttpRequestBuilder()
        request.takeFromWithExecutionContext(context)
        request.headers[HttpHeaders.Authorization] = "Bearer $token"
        request.attributes.put(circuitBreaker, Unit)
        return@intercept execute(request)
    }
}

https://kotlinlang.slack.com/archives/C3PQML5NU/p1602772889407200?thread_ts=1602772763.407000&cid=C3PQML5NU

from moko-network.

eliekarouz avatar eliekarouz commented on June 15, 2024

I confirm the code above works. Thanks.
The idea is that HttpSend Feature tracks the current network call and cancels it when it is modified… Canceling it is necessary otherwise the new network call with the new token doesn’t kickstart.
It looks like the Authorization feature will be added by default to Ktor but not sure when exactly...

from moko-network.

RezMike avatar RezMike commented on June 15, 2024

The following code solves the issue. It replaces 2 features in moko-network - TokenFeature and RefreshTokenFeature. But it calls 3 functions with KtorExperimentalAPI and 1 function with InternalAPI. So updating to a new ktor version may become problematic.

class TokenFeature(
    private val tokenHeaderName: String,
    private val tokenProvider: () -> String?,
    private val tokenUpdater: suspend () -> Boolean,
    private val sameTokenChecker: (HttpRequest) -> Boolean
) {

    class Config {
        var tokenHeaderName: String? = null
        var tokenProvider: (() -> String?)? = null
        var tokenUpdater: (suspend () -> Boolean)? = null
        var sameTokenChecker: ((HttpRequest) -> Boolean)? = null

        fun build() = TokenFeature(
            tokenHeaderName ?: throw IllegalArgumentException("headerName should be passed"),
            tokenProvider ?: throw IllegalArgumentException("tokenProvider should be passed"),
            tokenUpdater ?: throw IllegalArgumentException("tokenUpdater should be passed"),
            sameTokenChecker ?: throw IllegalArgumentException("sameTokenChecker should be passed")
        )
    }

    companion object Feature : HttpClientFeature<Config, TokenFeature> {

        private val refreshTokenMutex = Mutex()

        override val key = AttributeKey<TokenFeature>("TokenFeature")

        override fun prepare(block: Config.() -> Unit) = Config().apply(block).build()

        @OptIn(InternalAPI::class)
        override fun install(feature: TokenFeature, scope: HttpClient) {
            scope.requestPipeline.intercept(HttpRequestPipeline.State) {
                feature.tokenProvider.invoke().let { token ->
                    context.headers.remove(feature.tokenHeaderName)
                    context.header(feature.tokenHeaderName, token)
                }
            }
            val circuitBreaker = AttributeKey<Unit>("TokenFeature_circuitBreaker")
            scope.feature(HttpSend)!!.intercept { origin, context ->
                // If there is no token error, don't do anything
                if (origin.response.status != HttpStatusCode.Unauthorized) return@intercept origin
                // If this interceptor has already been called, don't do anything
                if (origin.request.attributes.contains(circuitBreaker)) return@intercept origin

                // Lock here, so other requests will wait until the token is updated
                refreshTokenMutex.lock()

                // If the token of the request is the same, then the token
                // hasn't been updated yet and we should update it
                if (feature.sameTokenChecker.invoke(origin.request)) {
                    val refreshSuccess = feature.tokenUpdater.invoke()
                    // If token refresh failed, then just let the token error occur
                    if (!refreshSuccess) {
                        refreshTokenMutex.unlock()
                        return@intercept origin
                    }
                }

                val token = feature.tokenProvider.invoke()
                // If the token was removed, then just let the token error occur
                if (token == null) {
                    refreshTokenMutex.unlock()
                    return@intercept origin
                }

                // Execute the same request with a new token
                val request = HttpRequestBuilder()
                request.takeFrom(context)
                request.headers[feature.tokenHeaderName] = token
                request.attributes.put(circuitBreaker, Unit)

                refreshTokenMutex.unlock()

                return@intercept execute(request)
            }
        }
    }
}

from moko-network.

Alex009 avatar Alex009 commented on June 15, 2024

after merge #88 i see that on ktor 1.5.2 and coroutines 1.4.2-native-mt problem not actual - tests of feature passed.
if after 0.11.0 release problem will be actual - feel free to reopen

from moko-network.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.