diff --git a/cache/build.gradle.kts b/cache/build.gradle.kts index 48da38d..8e3976a 100644 --- a/cache/build.gradle.kts +++ b/cache/build.gradle.kts @@ -33,5 +33,7 @@ dependencies { junit5() testImplementation(libs.kotlinx.coroutines.test) + testImplementation(libs.mockk) testImplementation(libs.truth) + testImplementation(libs.turbine) } diff --git a/cache/src/main/java/com/kroger/cache/internal/CacheFlowWrapper.kt b/cache/src/main/java/com/kroger/cache/internal/CacheFlowWrapper.kt new file mode 100644 index 0000000..a3ab76d --- /dev/null +++ b/cache/src/main/java/com/kroger/cache/internal/CacheFlowWrapper.kt @@ -0,0 +1,97 @@ +package com.kroger.cache.internal + +import com.kroger.cache.SnapshotPersistentCache +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch + +/** + * MIT License + * + * Copyright (c) 2023 The Kroger Co. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +/** + * A Wrapper class for a SnapshotPersistentCache that exposes changes to the cache via a flow. + * + * **Note this works best when used as a singleton + * + * @param cache the [com.kroger.cache.SnapshotPersistentCache] holding the value(s) on disk + * @param scope the [kotlinx.coroutines.CoroutineScope] to run the flow on + * + */ +public class CacheFlowWrapper( + private val cache: SnapshotPersistentCache, + private val scope: CoroutineScope, +) { + /** + * A reference to the coroutine job used for reading the first value from the [cache] and emitting it on [_cacheValueState] + */ + private val initializerJob: Job + + /** + * The private mutable state flow for the current value + */ + private val _cacheValueState = MutableStateFlow(null) + + /** + * publicly exposed read-only flow on which to read and observe changes to the current value + */ + public val cacheValueFlow: StateFlow = _cacheValueState.asStateFlow() + + /** + * Initialization block reads the value the [cache] and emits it on [_cacheValueState] + * + * This job also updates the value in [cache] for each new value emitted on the flow + * except for the first, which is read from [cache] + */ + init { + initializerJob = scope.launch { + _cacheValueState.value = cache.read() + + cacheValueFlow + .drop(1) + .onEach { + cache.save(it) + }.launchIn(scope) + } + } + + /** + * Updates the value of the StateFlow + * Any update to the state flow will be persisted to the [cache] + * Waits for initialization to finish reading the first value from the [cache] + * before emitting a new value on the flow + * + * @param newValue The new value to be both emitted on the flow, and saved in the [cache] + */ + public suspend fun setValue(newValue: T) { + if (initializerJob.isActive) { + initializerJob.join() + } + _cacheValueState.emit(newValue) + } +} diff --git a/cache/src/test/java/com/kroger/cache/internal/CacheFlowWrapperTest.kt b/cache/src/test/java/com/kroger/cache/internal/CacheFlowWrapperTest.kt new file mode 100644 index 0000000..a8503ed --- /dev/null +++ b/cache/src/test/java/com/kroger/cache/internal/CacheFlowWrapperTest.kt @@ -0,0 +1,111 @@ +package com.kroger.cache.internal + +import app.cash.turbine.test +import com.google.common.truth.Truth.assertThat +import com.kroger.cache.SnapshotPersistentCache +import io.mockk.coEvery +import io.mockk.coVerifySequence +import io.mockk.just +import io.mockk.mockk +import io.mockk.runs +import kotlinx.coroutines.CoroutineName +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class CacheFlowWrapperTest { + private val testDispatcher = UnconfinedTestDispatcher() + val testScope = CoroutineScope(CoroutineName("CacheFlowWrapperTest") + testDispatcher) + val fileCache: SnapshotPersistentCache = mockk() + + lateinit var cacheWrapper: CacheFlowWrapper + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `GIVEN cache is still reading WHEN new value is set THEN set value will wait for read to finish`() = runTest { + val fileCacheValue = "File cache value" + val newValue = "new value" + coEvery { fileCache.read() } coAnswers { + delay(1000) + fileCacheValue + } + coEvery { fileCache.save(any()) } just runs + cacheWrapper = CacheFlowWrapper(fileCache, testScope) + cacheWrapper.cacheValueFlow.test { + assertThat(awaitItem()).isEqualTo(null) + cacheWrapper.setValue(newValue) + assertThat(awaitItem()).isEqualTo(fileCacheValue) + advanceTimeBy(1000) + assertThat(awaitItem()).isEqualTo(newValue) + cancelAndIgnoreRemainingEvents() + } + + coVerifySequence { + fileCache.read() + fileCache.save(eq(newValue)) + } + } + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `GIVEN cache is done reading WHEN new value is set THEN set value will happen immediately`() = runTest { + val fileCacheValue = "File cache value" + val newValue = "new value" + coEvery { fileCache.read() } coAnswers { + fileCacheValue + } + coEvery { fileCache.save(any()) } just runs + cacheWrapper = CacheFlowWrapper(fileCache, testScope) + cacheWrapper.cacheValueFlow.test { + assertThat(awaitItem()).isEqualTo(fileCacheValue) + advanceTimeBy(1000) + cacheWrapper.setValue(newValue) + assertThat(awaitItem()).isEqualTo(newValue) + cancelAndIgnoreRemainingEvents() + } + + coVerifySequence { + fileCache.read() + fileCache.save(eq(newValue)) + } + } + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `GIVEN cache is writing values slowly WHEN new values are set in quick succession THEN all values are emitted on flow, and last value is saved to disk`() = runTest { + val firstValue = "first new value" + val secondValue = "second new value" + val thirdValue = "third new value" + val fourthValue = "Fourth new value" + coEvery { fileCache.read() } returns null + coEvery { fileCache.save(any()) } coAnswers { + delay(1000) + } + cacheWrapper = CacheFlowWrapper(fileCache, testScope) + cacheWrapper.cacheValueFlow.test { + assertThat(awaitItem()).isEqualTo(null) + cacheWrapper.setValue(firstValue) + cacheWrapper.setValue(secondValue) + cacheWrapper.setValue(thirdValue) + cacheWrapper.setValue(fourthValue) + advanceTimeBy(2000) + assertThat(awaitItem()).isEqualTo(firstValue) + assertThat(awaitItem()).isEqualTo(secondValue) + assertThat(awaitItem()).isEqualTo(thirdValue) + assertThat(awaitItem()).isEqualTo(fourthValue) + cancelAndIgnoreRemainingEvents() + } + + coVerifySequence { + fileCache.read() + fileCache.save(eq(firstValue)) // start writing the first value + // second and third should be skipped since first isn't done writing yet + fileCache.save(eq(fourthValue)) // fourth and final value is written + } + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7fc2eaa..f6f5f0b 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -39,6 +39,7 @@ ksp = "1.9.23-1.0.20" mockk = "1.12.5" telemetry = "1.0.0" truth = "1.1.3" +turbine = "1.0.0" [libraries] androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "androidxActivity" } @@ -73,6 +74,7 @@ moshi-ksp = { module = "com.squareup.moshi:moshi-kotlin-codegen", version.ref = truth = { module = "com.google.truth:truth", version.ref = "truth" } telemetry = { module = "com.kroger.telemetry:telemetry", version.ref = "telemetry" } telemetry-android = { module = "com.kroger.telemetry:android", version.ref = "telemetry" } +turbine = { module = "app.cash.turbine:turbine", version.ref = "turbine" } [plugins] android-application = { id = "com.android.application", version.ref = "androidGradlePlugin" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e644113..1b33c55 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index b82aa23..aaaabb3 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.4-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew b/gradlew index 1aa94a4..23d15a9 100755 --- a/gradlew +++ b/gradlew @@ -15,6 +15,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -84,7 +86,7 @@ done # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -112,7 +114,7 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar +CLASSPATH="\\\"\\\"" # Determine the Java command to use to start the JVM. @@ -203,7 +205,7 @@ fi DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, # and any embedded shellness will be escaped. # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be # treated as '${Hostname}' itself on the command line. @@ -211,7 +213,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" # Stop when "xargs" is not available. diff --git a/gradlew.bat b/gradlew.bat index 25da30d..5eed7ee 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,92 +1,94 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega