-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Use Web Cache API for string resources caching #5379
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
eymar
wants to merge
3
commits into
master
Choose a base branch
from
ok/use_web_caches_for_string_resources_response
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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
70 changes: 70 additions & 0 deletions
70
...esources/library/src/jsMain/kotlin/org/jetbrains/compose/resources/ResourceWebCache.js.kt
This file contains hidden or 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 |
---|---|---|
@@ -0,0 +1,70 @@ | ||
package org.jetbrains.compose.resources | ||
|
||
import kotlinx.browser.window | ||
import kotlinx.coroutines.await | ||
import kotlinx.coroutines.sync.Mutex | ||
import kotlinx.coroutines.sync.withLock | ||
import org.w3c.fetch.Response | ||
import org.w3c.workers.Cache | ||
|
||
/** | ||
* We use [Cache] and [org.w3c.dom.WindowSessionStorage] APIs to cache the successful strings.cvr responses. | ||
* We can't rely on the default browser cache because it makes http requests to check if the cached value is not expired, | ||
* which may take long if the connection is slow. | ||
* | ||
* With session storage, we avoid resetting the cache on page refresh. | ||
* The cache is reset only when a tab is re-opened. | ||
* TODO: Do we need to provide a way to reset the cache on the user side? | ||
* (it's already possible, but relying on the implementation details such as CACHE_NAME value) | ||
* | ||
* NOTE: due to unavailability of k/js + k/wasm shared w3c API, | ||
* we duplicate this implementation between k/js and k/wasm with minor differences. | ||
*/ | ||
internal object JsResourceWebCache { | ||
// This cache will be shared between all Compose instances (independent ComposeViewport) in the same session | ||
private const val CACHE_NAME = "compose_web_resources_cache" | ||
|
||
// A collection of mutexes to prevent the concurrent requests for the same resource but allow such requests for | ||
// distinct resources | ||
private val mutexes = mutableMapOf<String, Mutex>() | ||
|
||
// A mutex to avoid multiple cache reset | ||
private val resetMutex = Mutex() | ||
|
||
suspend fun load(path: String, onNoCacheHit: suspend (path: String) -> Response): Response { | ||
if (isNewSession()) { | ||
// There can be many load requests, and there must be 1 reset max. Therefore, using `resetMutex`. | ||
resetMutex.withLock { | ||
// Checking isNewSession() again in case it was just changed by another load request. | ||
// I avoid wrapping withLock in if (isNewSession()) check to avoid unnecessary locking on every load request | ||
if (isNewSession()) { | ||
resetCache() | ||
} | ||
} | ||
} | ||
|
||
|
||
val mutex = mutexes.getOrPut(path) { Mutex() } | ||
return mutex.withLock { | ||
val cache = window.caches.open(CACHE_NAME).await() | ||
val response = cache.match(path).await() as Response? | ||
|
||
response?.clone() ?: onNoCacheHit(path).also { | ||
if (it.ok) { | ||
cache.put(path, it.clone()).await() | ||
} | ||
} | ||
}.also { | ||
mutexes.remove(path) | ||
} | ||
} | ||
|
||
suspend fun resetCache() { | ||
window.caches.delete(CACHE_NAME).await() | ||
window.sessionStorage.setItem(CACHE_NAME, "1") | ||
} | ||
|
||
private fun isNewSession(): Boolean { | ||
return window.sessionStorage.getItem(CACHE_NAME) == null | ||
} | ||
} |
3 changes: 3 additions & 0 deletions
3
...rary/src/jsTest/kotlin/org/jetbrains/compose/resources/DefaultWebResourceReaderTest.js.kt
This file contains hidden or 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 |
---|---|---|
@@ -0,0 +1,3 @@ | ||
package org.jetbrains.compose.resources | ||
|
||
internal actual fun DefaultWebResourceReader(): ResourceReader = DefaultJsResourceReader |
This file contains hidden or 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
70 changes: 70 additions & 0 deletions
70
...library/src/wasmJsMain/kotlin/org/jetbrains/compose/resources/ResourceWebCache.wasm.kt.kt
This file contains hidden or 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 |
---|---|---|
@@ -0,0 +1,70 @@ | ||
package org.jetbrains.compose.resources | ||
|
||
import kotlinx.browser.window | ||
import kotlinx.coroutines.await | ||
import kotlinx.coroutines.sync.Mutex | ||
import kotlinx.coroutines.sync.withLock | ||
import org.w3c.fetch.Response | ||
import org.w3c.workers.Cache | ||
|
||
/** | ||
* We use [Cache] and [org.w3c.dom.WindowSessionStorage] APIs to cache the successful strings.cvr responses. | ||
* We can't rely on the default browser cache because it makes http requests to check if the cached value is not expired, | ||
* which may take long if the connection is slow. | ||
* | ||
* With session storage, we avoid resetting the cache on page refresh. | ||
* The cache is reset only when a tab is re-opened. | ||
* TODO: Do we need to provide a way to reset the cache on the user side? | ||
* (it's already possible, but relying on the implementation details such as CACHE_NAME value) | ||
* | ||
* NOTE: due to unavailability of k/js + k/wasm shared w3c API, | ||
* we duplicate this implementation between k/js and k/wasm with minor differences. | ||
*/ | ||
internal object WasmResourceWebCache { | ||
// This cache will be shared between all Compose instances (independent ComposeViewport) in the same session | ||
private const val CACHE_NAME = "compose_web_resources_cache" | ||
|
||
// A collection of mutexes to prevent the concurrent requests for the same resource but allow such requests for | ||
// distinct resources | ||
private val mutexes = mutableMapOf<String, Mutex>() | ||
|
||
// A mutex to avoid multiple cache reset | ||
private val resetMutex = Mutex() | ||
|
||
suspend fun load(path: String, onNoCacheHit: suspend (path: String) -> Response): Response { | ||
if (isNewSession()) { | ||
// There can be many load requests, and there must be 1 reset max. Therefore, using `resetMutex`. | ||
resetMutex.withLock { | ||
// Checking isNewSession() again in case it was just changed by another load request. | ||
// I avoid wrapping withLock in if (isNewSession()) check to avoid unnecessary locking on every load request | ||
if (isNewSession()) { | ||
resetCache() | ||
} | ||
} | ||
} | ||
|
||
|
||
val mutex = mutexes.getOrPut(path) { Mutex() } | ||
return mutex.withLock { | ||
val cache = window.caches.open(CACHE_NAME).await<Cache>() | ||
val response = cache.match(path).await<Response?>() | ||
|
||
response?.clone() ?: onNoCacheHit(path).also { | ||
if (it.ok) { | ||
cache.put(path, it.clone()).await<JsBoolean>() | ||
} | ||
} | ||
}.also { | ||
mutexes.remove(path) | ||
} | ||
} | ||
|
||
suspend fun resetCache() { | ||
window.caches.delete(CACHE_NAME).await<JsBoolean>() | ||
window.sessionStorage.setItem(CACHE_NAME, "1") | ||
} | ||
|
||
private fun isNewSession(): Boolean { | ||
return window.sessionStorage.getItem(CACHE_NAME) == null | ||
} | ||
} |
3 changes: 3 additions & 0 deletions
3
.../wasmJsTest/kotlin/org/jetbrains/compose/resources/DefaultWebResourceReaderTest.wasmJs.kt
This file contains hidden or 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 |
---|---|---|
@@ -0,0 +1,3 @@ | ||
package org.jetbrains.compose.resources | ||
|
||
internal actual fun DefaultWebResourceReader(): ResourceReader = DefaultWasmResourceReader |
62 changes: 62 additions & 0 deletions
62
...ibrary/src/webTest/kotlin/org/jetbrains/compose/resources/DefaultWebResourceReaderTest.kt
This file contains hidden or 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 |
---|---|---|
@@ -0,0 +1,62 @@ | ||
package org.jetbrains.compose.resources | ||
|
||
import androidx.compose.material3.Text | ||
import androidx.compose.runtime.* | ||
import androidx.compose.ui.test.ComposeUiTest | ||
import androidx.compose.ui.test.ExperimentalTestApi | ||
import androidx.compose.ui.test.runComposeUiTest | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.delay | ||
import kotlinx.coroutines.withContext | ||
import kotlinx.coroutines.withTimeout | ||
import kotlin.test.Test | ||
import kotlin.test.assertEquals | ||
import kotlin.time.Duration | ||
import kotlin.time.Duration.Companion.milliseconds | ||
|
||
@OptIn(ExperimentalTestApi::class) | ||
class DefaultWebResourceReaderTest { | ||
|
||
private val reader = DefaultWebResourceReader() | ||
|
||
private val appNameStringRes = TestStringResource("app_name") | ||
|
||
@Test | ||
fun stringResource() = runComposeUiTest { | ||
|
||
var appName: String by mutableStateOf("") | ||
|
||
setContent { | ||
CompositionLocalProvider( | ||
LocalResourceReader provides reader, | ||
LocalComposeEnvironment provides TestComposeEnvironment | ||
) { | ||
appName = stringResource(appNameStringRes) | ||
Text(appName) | ||
} | ||
} | ||
|
||
awaitUntil { | ||
appName == "Compose Resources App" | ||
} | ||
|
||
assertEquals("Compose Resources App", appName) | ||
} | ||
|
||
private suspend fun ComposeUiTest.awaitUntil( | ||
timeout: Duration = 100.milliseconds, | ||
block: suspend () -> Boolean | ||
) { | ||
withContext(Dispatchers.Default) { | ||
withTimeout(timeout) { | ||
while (!block()) { | ||
delay(10) | ||
awaitIdle() | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
// Until we have common w3c api between k/js and k/wasm we need to have this expect/actual | ||
internal expect fun DefaultWebResourceReader(): ResourceReader |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we use it specifically for Strings.CVR then let's rename it to StringsWebCache. Otherwise, we mustn't mention cvr in the kdoc