-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Bytter ut thread-safe token cache med en som er coroutine-safe
Co-authored-by: Richard Borge <[email protected]> Co-authored-by: Vetle Hollund <[email protected]> Co-authored-by: Sturle Helland <[email protected]>
- Loading branch information
1 parent
e5606c0
commit 488c07e
Showing
3 changed files
with
37 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,43 @@ | ||
package no.nav.aap.ktor.client | ||
|
||
import no.nav.aap.cache.Cache | ||
import kotlinx.coroutines.sync.Mutex | ||
import kotlinx.coroutines.sync.withLock | ||
import java.time.Instant | ||
|
||
internal data class Token(val expires_in: Long, val access_token: String) { | ||
private val expiry: Instant = Instant.now().plusSeconds(expires_in - LEEWAY_SECONDS) | ||
|
||
internal fun addToCache(cache: Cache<String, Token>, cacheKey: String) { | ||
cache.set(cacheKey, this, expiry) | ||
} | ||
internal fun expired() = Instant.now().isAfter(expiry) | ||
|
||
private companion object { | ||
const val LEEWAY_SECONDS = 60 | ||
} | ||
} | ||
|
||
internal class TokenCache<K> { | ||
private val tokens: HashMap<K, Token> = hashMapOf() | ||
private val mutex = Mutex() | ||
|
||
internal suspend fun add(key: K, token: Token) { | ||
mutex.withLock { | ||
tokens[key] = token | ||
} | ||
} | ||
|
||
internal suspend fun get(key: K): Token? { | ||
tokens[key]?.let { | ||
if (it.expired()) { | ||
rm(key) | ||
} | ||
} | ||
return mutex.withLock { | ||
tokens[key] | ||
} | ||
} | ||
|
||
private suspend fun rm(key: K) { | ||
mutex.withLock { | ||
tokens.remove(key) | ||
} | ||
} | ||
} |