Comments (5)
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.
@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)
}
}
from moko-network.
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.
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.
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)
- Support Windows target
- Support Linux targets
- query param name starts with a number
- Missing query param default value
- HI
- Allow UserAgent feature to have a dynamic source of its value HOT 1
- TokenFeature.TokenProvider should be a fun interface HOT 2
- Update Network Generator for Ktor 2.0.1 HOT 1
- Add ability for include/exclude tags for generation
- Network Generator Inline Objects Naming
- Is the way to change property type from Int to Long? HOT 1
- Broken iOS 12 support
- Invalid isNetworkConnectionError result on iOS
- Update moko-resources dependency without cinterop-pluralizedString HOT 1
- Update to later Ktor HOT 3
- Add method to Safeable to map null to a particular value
- Add the value being deserialized to Safeable wrapper
- Improper error handling for method with no return type HOT 3
- RefreshTokenPlugin: excecution is locked when updateTokenHandler gets 401 error HOT 1
- Deprecation warnings when upgrading ktor to 2.3.4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from moko-network.