Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions store/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ kotlin {
implementation(libs.turbine)
}
}

val androidDeviceTest by getting {
dependencies {
implementation(libs.junit)
implementation(libs.kotlinx.coroutines.test)
implementation(kotlin("test"))
implementation("androidx.test:runner:1.6.2")
}
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package org.mobilenativefoundation.store.store5

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.test.runTest
import org.mobilenativefoundation.store.core5.ExperimentalStoreApi
import org.mobilenativefoundation.store.store5.impl.extensions.asMutableStore
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs

@OptIn(ExperimentalStoreApi::class)
class PushFailurePolicyDeviceTest {

@Test
fun pushFailurePolicyFailFastOnDevice() = runTest {
val storage = mutableMapOf<String, String>()
val dataFlow = MutableStateFlow<String?>("local_val")
storage["key1"] = "local_val"

val sot = SourceOfTruth.of<String, String, String>(
reader = { dataFlow },
writer = { k, v ->
storage[k] = v
dataFlow.value = v
}
)

val delegateStore = StoreBuilder.from<String, String, String>(
fetcher = Fetcher.of { key -> "remote_$key" },
sourceOfTruth = sot
).disableCache()
.build()

val updater = Updater.by<String, String, String>(
post = { key, value ->
UpdaterResult.Error.Message("Update failed on device")
}
)

val failedKeys = mutableSetOf<String>("key1")
val bookkeeper = object : Bookkeeper<String> {
override suspend fun getLastFailedSync(key: String): Long? = if (failedKeys.contains(key)) 12345L else null
override suspend fun setLastFailedSync(key: String, timestamp: Long): Boolean = true
override suspend fun clear(key: String): Boolean = failedKeys.remove(key)
override suspend fun clearAll(): Boolean {
failedKeys.clear()
return true
}
}

val failFastStore = delegateStore.asMutableStore<String, String, String, String, String>(
updater = updater,
bookkeeper = bookkeeper,
pushFailurePolicy = PushFailurePolicy.FAIL_FAST
)

val responses = failFastStore.stream<String>(
StoreReadRequest.cached("key1", refresh = true)
).toList()

assertEquals(1, responses.size)
assertIs<StoreReadResponse.Error.Message>(responses[0])
assertEquals("Update failed on device", (responses[0] as StoreReadResponse.Error.Message).message)
}

@Test
fun pushFailurePolicySkipFetchKeepLocalOnDevice() = runTest {
val storage = mutableMapOf<String, String>()
val dataFlow = MutableStateFlow<String?>("local_val")
storage["key1"] = "local_val"

val sot = SourceOfTruth.of<String, String, String>(
reader = { dataFlow },
writer = { k, v ->
storage[k] = v
dataFlow.value = v
}
)

val delegateStore = StoreBuilder.from<String, String, String>(
fetcher = Fetcher.of { key -> "remote_$key" },
sourceOfTruth = sot
).disableCache()
.build()

val updater = Updater.by<String, String, String>(
post = { key, value ->
UpdaterResult.Error.Message("Update failed on device")
}
)

val failedKeys = mutableSetOf<String>("key1")
val bookkeeper = object : Bookkeeper<String> {
override suspend fun getLastFailedSync(key: String): Long? = if (failedKeys.contains(key)) 12345L else null
override suspend fun setLastFailedSync(key: String, timestamp: Long): Boolean = true
override suspend fun clear(key: String): Boolean = failedKeys.remove(key)
override suspend fun clearAll(): Boolean {
failedKeys.clear()
return true
}
}

val skipFetchStore = delegateStore.asMutableStore<String, String, String, String, String>(
updater = updater,
bookkeeper = bookkeeper,
pushFailurePolicy = PushFailurePolicy.SKIP_FETCH_KEEP_LOCAL
)

val responses = skipFetchStore.stream<String>(
StoreReadRequest.cached("key1", refresh = true)
).take(1).toList()

assertEquals(1, responses.size)
assertIs<StoreReadResponse.Data<String>>(responses[0])
assertEquals("local_val", (responses[0] as StoreReadResponse.Data<String>).value)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ interface MutableStoreBuilder<Key : Any, Network : Any, Local : Any, Output : An

fun validator(validator: Validator<Output>): MutableStoreBuilder<Key, Network, Local, Output>

fun pushFailurePolicy(policy: PushFailurePolicy): MutableStoreBuilder<Key, Network, Local, Output>

companion object {
/**
* Creates a new [MutableStoreBuilder] from a [Fetcher] and a [SourceOfTruth].
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package org.mobilenativefoundation.store.store5

/**
* Defines the strategy to execute when an eager push to remote fails during a stream request.
*/
enum class PushFailurePolicy {
/**
* Stop the stream and emit a [StoreReadResponse.Error] immediately without fetching from network.
*/
FAIL_FAST,

/**
* Suppress remote network fetch and serve only local data, preserving unpushed local changes.
*/
SKIP_FETCH_KEEP_LOCAL,

/**
* Log the error and proceed with the read request, which may fetch remote data (legacy default).
*/
IGNORE_AND_FETCH,
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ import org.mobilenativefoundation.store.store5.Bookkeeper
import org.mobilenativefoundation.store.store5.Clear
import org.mobilenativefoundation.store.store5.Logger
import org.mobilenativefoundation.store.store5.MutableStore
import org.mobilenativefoundation.store.store5.PushFailurePolicy
import org.mobilenativefoundation.store.store5.StoreReadRequest
import org.mobilenativefoundation.store.store5.StoreReadResponse
import org.mobilenativefoundation.store.store5.StoreReadResponseOrigin
import org.mobilenativefoundation.store.store5.StoreWriteRequest
import org.mobilenativefoundation.store.store5.StoreWriteResponse
import org.mobilenativefoundation.store.store5.Updater
Expand All @@ -27,6 +29,7 @@ internal class RealMutableStore<Key : Any, Network : Any, Output : Any, Local :
private val updater: Updater<Key, Output, *>,
private val bookkeeper: Bookkeeper<Key>?,
private val logger: Logger = DefaultLogger(),
private val pushFailurePolicy: PushFailurePolicy = PushFailurePolicy.IGNORE_AND_FETCH,
private val beforeAcknowledgementCommit: suspend () -> Unit = {},
) : MutableStore<Key, Output>, Clear.All {
private val storeLock = Mutex()
Expand All @@ -36,10 +39,45 @@ internal class RealMutableStore<Key : Any, Network : Any, Output : Any, Local :
flow {
checkMutableStoreEntry(this@RealMutableStore, request.key)
val state = stateFor(request.key)
// TODO(#678): Allow configuring whether a failed push should prevent a subsequent fetch.
when (val result = tryEagerlyResolveConflicts<Response>(request.key, state)) {
is EagerConflictResolutionResult.Error.Exception -> logger.error(result.error.toString())
is EagerConflictResolutionResult.Error.Message -> logger.error(result.message)
is EagerConflictResolutionResult.Error.Exception -> {
logger.error(result.error.toString())
when (pushFailurePolicy) {
PushFailurePolicy.FAIL_FAST -> {
emit(
StoreReadResponse.Error.Exception(
error = result.error,
origin = StoreReadResponseOrigin.SourceOfTruth,
),
)
return@flow
}
PushFailurePolicy.SKIP_FETCH_KEEP_LOCAL -> {
delegate.stream(StoreReadRequest.cached(request.key, refresh = false)).collect { emit(it) }
return@flow
}
PushFailurePolicy.IGNORE_AND_FETCH -> Unit
}
}
is EagerConflictResolutionResult.Error.Message -> {
logger.error(result.message)
when (pushFailurePolicy) {
PushFailurePolicy.FAIL_FAST -> {
emit(
StoreReadResponse.Error.Message(
message = result.message,
origin = StoreReadResponseOrigin.SourceOfTruth,
),
)
return@flow
}
PushFailurePolicy.SKIP_FETCH_KEEP_LOCAL -> {
delegate.stream(StoreReadRequest.cached(request.key, refresh = false)).collect { emit(it) }
return@flow
}
PushFailurePolicy.IGNORE_AND_FETCH -> Unit
}
}
is EagerConflictResolutionResult.Success.ConflictsResolved -> logger.debug(result.value.toString())
EagerConflictResolutionResult.Success.NoConflicts -> logger.debug("No conflicts.")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import org.mobilenativefoundation.store.store5.Fetcher
import org.mobilenativefoundation.store.store5.MemoryPolicy
import org.mobilenativefoundation.store.store5.MutableStore
import org.mobilenativefoundation.store.store5.MutableStoreBuilder
import org.mobilenativefoundation.store.store5.PushFailurePolicy
import org.mobilenativefoundation.store.store5.SourceOfTruth
import org.mobilenativefoundation.store.store5.Store
import org.mobilenativefoundation.store.store5.StoreDefaults
Expand Down Expand Up @@ -45,6 +46,7 @@ internal class RealMutableStoreBuilder<Key : Any, Network : Any, Local : Any, Ou
private var scope: CoroutineScope? = null
private var cachePolicy: MemoryPolicy<Key, Output>? = StoreDefaults.memoryPolicy
private var validator: Validator<Output>? = null
private var pushFailurePolicy: PushFailurePolicy = PushFailurePolicy.IGNORE_AND_FETCH

override fun scope(scope: CoroutineScope): MutableStoreBuilder<Key, Network, Local, Output> {
this.scope = scope
Expand All @@ -66,6 +68,11 @@ internal class RealMutableStoreBuilder<Key : Any, Network : Any, Local : Any, Ou
return this
}

override fun pushFailurePolicy(policy: PushFailurePolicy): MutableStoreBuilder<Key, Network, Local, Output> {
this.pushFailurePolicy = policy
return this
}

fun build(): Store<Key, Output> =
RealStore(
scope = scope ?: GlobalScope,
Expand Down Expand Up @@ -105,5 +112,6 @@ internal class RealMutableStoreBuilder<Key : Any, Network : Any, Local : Any, Ou
build().asMutableStore<Key, Network, Output, Local, UpdaterResult>(
updater = updater,
bookkeeper = bookkeeper,
pushFailurePolicy = pushFailurePolicy,
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import kotlinx.coroutines.flow.first
import org.mobilenativefoundation.store.core5.ExperimentalStoreApi
import org.mobilenativefoundation.store.store5.Bookkeeper
import org.mobilenativefoundation.store.store5.MutableStore
import org.mobilenativefoundation.store.store5.PushFailurePolicy
import org.mobilenativefoundation.store.store5.Store
import org.mobilenativefoundation.store.store5.StoreReadRequest
import org.mobilenativefoundation.store.store5.StoreReadResponse
Expand Down Expand Up @@ -88,6 +89,7 @@ suspend fun <Key : Any, Output : Any> Store<Key, Output>.fresh(key: Key) =
fun <Key : Any, Network : Any, Output : Any, Local : Any, Response : Any> Store<Key, Output>.asMutableStore(
updater: Updater<Key, Output, Response>,
bookkeeper: Bookkeeper<Key>?,
pushFailurePolicy: PushFailurePolicy = PushFailurePolicy.IGNORE_AND_FETCH,
): MutableStore<Key, Output> {
val delegate =
this as? RealStore<Key, Network, Output, Local>
Expand All @@ -97,6 +99,7 @@ fun <Key : Any, Network : Any, Output : Any, Local : Any, Response : Any> Store<
delegate = delegate,
updater = updater,
bookkeeper = bookkeeper,
pushFailurePolicy = pushFailurePolicy,
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.test.runTest
import org.mobilenativefoundation.store.core5.ExperimentalStoreApi
import org.mobilenativefoundation.store.store5.FetcherResult
import org.mobilenativefoundation.store.store5.PushFailurePolicy
import org.mobilenativefoundation.store.store5.SourceOfTruth
import org.mobilenativefoundation.store.store5.StoreReadRequest
import org.mobilenativefoundation.store.store5.StoreReadResponse
Expand Down Expand Up @@ -155,6 +156,54 @@ class RealMutableStoreTest {
assertNotNull(testBookkeeper.getLastFailedSync("key3"))
}

@Test
fun stream_givenConflictResolutionFailsAndFailFast_whenReading_thenEmitsErrorAndAborts() =
runTest {
val failFastStore =
RealMutableStore(
delegate = delegateStore,
updater = testUpdater,
bookkeeper = testBookkeeper,
logger = testLogger,
pushFailurePolicy = PushFailurePolicy.FAIL_FAST,
)
val request = StoreReadRequest.Companion.cached("keyFailFast", refresh = true)
val errorMessage = "Conflict resolution failure"
delegateStore.write("keyFailFast", Note("localId", "localContent"))
testBookkeeper.setLastFailedSync("keyFailFast")
testUpdater.errorMessage = errorMessage

val results = failFastStore.stream<Unit>(request).toList()

assertEquals(1, results.size)
assertIs<StoreReadResponse.Error.Message>(results[0])
assertEquals(errorMessage, (results[0] as StoreReadResponse.Error.Message).message)
}

@Test
fun stream_givenConflictResolutionFailsAndSkipFetchKeepLocal_whenReading_thenEmitsLocalOnly() =
runTest {
val skipFetchStore =
RealMutableStore(
delegate = delegateStore,
updater = testUpdater,
bookkeeper = testBookkeeper,
logger = testLogger,
pushFailurePolicy = PushFailurePolicy.SKIP_FETCH_KEEP_LOCAL,
)
val request = StoreReadRequest.Companion.cached("keySkipFetch", refresh = true)
val errorMessage = "Conflict resolution failure"
delegateStore.write("keySkipFetch", Note("localId", "localContent"))
testBookkeeper.setLastFailedSync("keySkipFetch")
testUpdater.errorMessage = errorMessage

val results = skipFetchStore.stream<Unit>(request).take(1).toList()

assertEquals(1, results.size)
assertIs<StoreReadResponse.Data<Note>>(results[0])
assertEquals("localContent", (results[0] as StoreReadResponse.Data<Note>).value.content)
}

@Test
fun stream_givenWriteFlowAndNoConflicts_whenCollecting_thenLocalAndNetworkAreUpdated() =
runTest {
Expand Down