class UnauthorizedException : Exception("401 Unauthorized") /** Holds the current tokens. The refresh token is rotated by the server: each one works for exactly one refresh. */ class TokenStore(var accessToken: String, var refreshToken: String) interface AuthApi { /** Exchanges a refresh token for a new (access token, refresh token) pair. Each refresh token can be used only once. */ suspend fun refresh(refreshToken: String): Pair } /** * Runs authenticated requests and refreshes the access token when the server answers 401. * * Contract agreed with the mobile team: * - A request gets the current access token. If it throws UnauthorizedException, the token is refreshed and the * request is retried once with the new token. A second UnauthorizedException is thrown to the caller. * - When several requests get 401 at the same time, the token is refreshed only once; the others wait for that * refresh and retry with its token. * - A request whose 401 came from a token that has already been replaced retries with the current token * without refreshing again. * - If a refresh fails, every request waiting for it fails with the refresh's exception. The next 401 after * that starts a new refresh. * - Cancelling one request must not cancel a refresh that other requests are waiting for. */ class AuthenticatedClient(private val store: TokenStore, private val api: AuthApi) { suspend fun call(request: suspend (accessToken: String) -> T): T { return try { request(store.accessToken) } catch (e: UnauthorizedException) { val (access, refresh) = api.refresh(store.refreshToken) store.accessToken = access store.refreshToken = refresh request(store.accessToken) } } }