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,87 @@
package org.mobilenativefoundation.store.store5

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.mobilenativefoundation.store.core5.ExperimentalStoreApi
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

@OptIn(ExperimentalStoreApi::class)
class ClearBarrierDeviceTest {

@Test
fun clearKeyEvictsSourceOfTruthOnDevice() = runTest {
val storage = mutableMapOf<String, String>()
val dataFlow = MutableStateFlow<String?>("initial_device_val")
storage["item"] = "initial_device_val"

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

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

// Read initial data from SourceOfTruth
val initial = store.stream(StoreReadRequest.cached("item", refresh = false))
.filterIsInstance<StoreReadResponse.Data<String>>()
.first()
assertEquals("initial_device_val", initial.value)

// Clear key should trigger delete on SOT
store.clear("item")
assertNull(storage["item"])
assertNull(dataFlow.value)
}

@Test
fun clearAllEvictsAllSourceOfTruthEntriesOnDevice() = runTest {
val storage = mutableMapOf<String, String>()
val dataFlow = MutableStateFlow<String?>("initial_all")
storage["k1"] = "initial_all"

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

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

store.clear()
assertNull(storage["k1"])
assertNull(dataFlow.value)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@ internal class RefCountedResource<Key, T>(
}
}

suspend fun activeKeys(): List<Key> =
lock.withLock {
items.keys.toList()
}

// used in tests
suspend fun size() =
lock.withLock {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ internal class SourceOfTruthWithBarrier<Key : Any, Network : Any, Output : Any,
when (barrierMessage) {
is BarrierMsg.Open ->
delegate.reader(key).mapIndexed { index, local: Output? ->
if (index == 0 && messageArrivedAfterMe) {
if (index == 0 && messageArrivedAfterMe && !barrierMessage.isDelete) {
val firstMsgOrigin =
if (writeError == null) {
// restarted barrier without an error means write succeeded
Expand Down Expand Up @@ -191,19 +191,73 @@ internal class SourceOfTruthWithBarrier<Key : Any, Network : Any, Output : Any,
}

suspend fun delete(key: Key) {
delegate.delete(key)
val barrier = barriers.acquire(key)
var deleteException: Throwable? = null
try {
barrier.value = BarrierMsg.Blocked(versionCounter.incrementAndGet())
try {
delegate.delete(key)
} catch (cancellation: CancellationException) {
throw cancellation
} catch (throwable: Throwable) {
deleteException = throwable
}
} finally {
barrier.value =
BarrierMsg.Open(
version = versionCounter.incrementAndGet(),
writeError = deleteException,
isDelete = true,
)
withContext(NonCancellable) {
barriers.release(key, barrier)
}
}
}

suspend fun deleteAll() {
delegate.deleteAll()
val keys = barriers.activeKeys()
val acquired = keys.map { it to barriers.acquire(it) }
var deleteException: Throwable? = null
try {
acquired.forEach { (_, barrier) ->
barrier.value = BarrierMsg.Blocked(versionCounter.incrementAndGet())
}
try {
delegate.deleteAll()
} catch (cancellation: CancellationException) {
throw cancellation
} catch (throwable: Throwable) {
deleteException = throwable
}
} finally {
val nextVersion = versionCounter.incrementAndGet()
acquired.forEach { (_, barrier) ->
barrier.value =
BarrierMsg.Open(
version = nextVersion,
writeError = deleteException,
isDelete = true,
)
}
withContext(NonCancellable) {
acquired.forEach { (key, barrier) ->
barriers.release(key, barrier)
}
}
}
}

private sealed class BarrierMsg(
val version: Long,
) {
class Blocked(version: Long) : BarrierMsg(version)

class Open(version: Long, val writeError: Throwable? = null) : BarrierMsg(version) {
class Open(
version: Long,
val writeError: Throwable? = null,
val isDelete: Boolean = false,
) : BarrierMsg(version) {
companion object {
val INITIAL = Open(INITIAL_VERSION)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,4 +334,49 @@ class SourceOfTruthWithBarrierTests {
collection.cancelAndJoin()
}
}

@Test
fun deleteNotifiesActiveReaderFlow() =
testScope.runTest {
val lock = CompletableDeferred<Unit>()
lock.complete(Unit)
val reader = source.reader(1, lock)
val collected = mutableListOf<StoreReadResponse<String?>>()
val collection =
launch {
reader.collect {
collected.add(it)
}
}
source.write(1, "initial")
advanceUntilIdle()

assertEquals(
listOf<StoreReadResponse<String?>>(
StoreReadResponse.Data(
origin = StoreReadResponseOrigin.SourceOfTruth,
value = "initial",
),
),
collected,
)

source.delete(1)
advanceUntilIdle()

assertEquals(
listOf<StoreReadResponse<String?>>(
StoreReadResponse.Data(
origin = StoreReadResponseOrigin.SourceOfTruth,
value = "initial",
),
StoreReadResponse.Data(
origin = StoreReadResponseOrigin.SourceOfTruth,
value = null,
),
),
collected,
)
collection.cancelAndJoin()
}
}