StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
fix: harden provider observation cache
David Nashash7264a4dc29a7
diff --git a/app/src/androidTest/java/com/streamvault/app/ui/components/shell/ShellGoldenTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/components/shell/ShellGoldenTest.ktindex 72cac78d..d98bcf94 100644--- a/app/src/androidTest/java/com/streamvault/app/ui/components/shell/ShellGoldenTest.kt+++ b/app/src/androidTest/java/com/streamvault/app/ui/components/shell/ShellGoldenTest.kt@@ -2,17 +2,21 @@ package com.streamvault.app.ui.components.shellimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Homeimport androidx.compose.runtime.CompositionLocalProviderimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalLayoutDirectionimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.unit.LayoutDirectionimport androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescriptionimport androidx.compose.ui.test.onNodeWithTagimport androidx.test.ext.junit.runners.AndroidJUnit4import com.streamvault.app.navigation.Routesimport com.streamvault.app.ui.test.assertAgainstGoldenimport com.streamvault.core.ui.theme.StreamVaultTheme+import com.streamvault.core.ui.components.shell.UiDestinationimport com.streamvault.domain.model.Channelimport org.junit.Ruleimport org.junit.Test@@ -24,6 +28,34 @@ class ShellGoldenTest {@get:Ruleval composeRule = createComposeRule()+ @Test+ fun appScreenScaffold_usesProvidedNavigationDestinations() {+ composeRule.setContent {+ CompositionLocalProvider(+ LocalAppDestinationItems provides listOf(+ UiDestination(+ id = "injected",+ label = "Injected destination",+ icon = Icons.Default.Home+ )+ )+ ) {+ StreamVaultTheme {+ AppScreenScaffold(+ currentRoute = "injected",+ onNavigate = {},+ title = "Injected shell"+ ) {+ Box(modifier = Modifier.fillMaxSize())+ }+ }+ }+ }++ composeRule.onNodeWithContentDescription("Injected destination").assertExists()+ composeRule.onNodeWithContentDescription("Live TV").assertDoesNotExist()+ }+@Testfun browseHeroPanel_matchesGolden() {composeRule.setContent {diff --git a/data/src/main/java/com/streamvault/data/provider/ProviderObservationStreams.kt b/data/src/main/java/com/streamvault/data/provider/ProviderObservationStreams.ktindex f170e5d0..d08a2298 100644--- a/data/src/main/java/com/streamvault/data/provider/ProviderObservationStreams.kt+++ b/data/src/main/java/com/streamvault/data/provider/ProviderObservationStreams.kt@@ -59,6 +59,7 @@ internal class ProviderObservationStreams(rows: List<ProviderConfigEntity>): Map<Long, RedactedProviderConfigurationProjection> = synchronized(cacheLock) {val currentProviderIds = rows.asSequence().map(ProviderConfigEntity::providerId).toSet()+ projectionCache.keys.retainAll(currentProviderIds)val resolved = rows.associate { row ->val cached = projectionCache[row.providerId]val value = if (cached != null && cached.source == row) {@@ -70,7 +71,6 @@ internal class ProviderObservationStreams(}row.providerId to value}- projectionCache.keys.retainAll(currentProviderIds)resolved}}diff --git a/data/src/test/java/com/streamvault/data/provider/ProviderObservationStreamsTest.kt b/data/src/test/java/com/streamvault/data/provider/ProviderObservationStreamsTest.ktindex a2e6b028..13303318 100644--- a/data/src/test/java/com/streamvault/data/provider/ProviderObservationStreamsTest.kt+++ b/data/src/test/java/com/streamvault/data/provider/ProviderObservationStreamsTest.kt@@ -10,6 +10,11 @@ import com.streamvault.data.local.entity.StalkerPortalStateEntityimport com.streamvault.domain.model.CatalogLayoutimport com.streamvault.domain.model.LegacyProviderimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.model.StalkerDeviceIdentity+import com.streamvault.domain.model.StalkerObservation+import com.streamvault.domain.model.StalkerObservationSource+import com.streamvault.domain.model.StalkerPortalLearningimport com.streamvault.domain.model.XtreamConfigimport kotlinx.coroutines.CoroutineDispatcherimport kotlinx.coroutines.CoroutineStart@@ -20,6 +25,8 @@ import kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.flow.onEach+import kotlinx.coroutines.flow.onSubscriptionimport kotlinx.coroutines.flow.takeimport kotlinx.coroutines.flow.toListimport kotlinx.coroutines.launch@@ -32,6 +39,7 @@ import org.mockito.kotlin.mockimport org.mockito.kotlin.wheneverimport java.util.concurrent.atomic.AtomicIntegerimport java.util.concurrent.CountDownLatch+import java.util.concurrent.ConcurrentHashMapimport java.util.concurrent.TimeUnit@OptIn(ExperimentalCoroutinesApi::class)@@ -63,26 +71,49 @@ class ProviderObservationStreamsTest {@Testfun `concurrent collectors decode one row only`() = runTest {- val fixture = stateFixture()+ val identities = MutableStateFlow(listOf(providerEntity()))+ val configs = MutableSharedFlow<List<ProviderConfigEntity>>()+ val runtimes = MutableStateFlow(emptyList<ProviderAccountRuntimeEntity>())+ val portalStates = MutableStateFlow(emptyList<StalkerPortalStateEntity>())+ val configSubscriptions = CountDownLatch(2)+ val configDeliveries = CountDownLatch(2)val decodeStarted = CountDownLatch(1)val releaseDecode = CountDownLatch(1)- fixture.projection.decodeGate = DecodeGate(decodeStarted, releaseDecode)- val streams = fixture.streams(Dispatchers.Default)+ val projection = CountingProjection().apply {+ decodeGate = DecodeGate(decodeStarted, releaseDecode)+ }+ val streams = ProviderObservationStreams(+ providerDao = providerDao(identities),+ providerSnapshotDao = snapshotDao(+ configs = configs+ .onSubscription { configSubscriptions.countDown() }+ .onEach { configDeliveries.countDown() },+ runtimes = runtimes,+ portalStates = portalStates+ ),+ projection = projection,+ workDispatcher = Dispatchers.Default+ )val first = async(Dispatchers.Default) { streams.providers.first() }- assertThat(decodeStarted.await(2, TimeUnit.SECONDS)).isTrue()-val second = async(Dispatchers.Default) { streams.providers.first() }- Thread.sleep(100)+ assertThat(configSubscriptions.await(2, TimeUnit.SECONDS)).isTrue()++ val emitter = launch(Dispatchers.Default) {+ configs.emit(listOf(configEntity()))+ }+ assertThat(configDeliveries.await(2, TimeUnit.SECONDS)).isTrue()+ assertThat(decodeStarted.await(2, TimeUnit.SECONDS)).isTrue()assertThat(first.isCompleted).isFalse()assertThat(second.isCompleted).isFalse()- assertThat(fixture.projection.decodeCalls.get()).isEqualTo(1)+ assertThat(projection.decodeCalls.get()).isEqualTo(1)releaseDecode.countDown()+ emitter.join()assertThat(first.await()).hasSize(1)assertThat(second.await()).hasSize(1)- assertThat(fixture.projection.decodeCalls.get()).isEqualTo(1)+ assertThat(projection.decodeCalls.get()).isEqualTo(1)}@Test@@ -112,6 +143,91 @@ class ProviderObservationStreamsTest {assertThat(fixture.projection.decodeCalls.get()).isEqualTo(1)}+ @Test+ fun `Stalker learning-only changes assemble without another decode`() = runTest {+ val generation = 4L+ val identities = MutableStateFlow(+ listOf(providerEntity(id = 9L, isActive = true, type = ProviderType.STALKER_PORTAL))+ )+ val configs = MutableStateFlow(listOf(stalkerConfigEntity(generation)))+ val runtimes = MutableStateFlow(emptyList<ProviderAccountRuntimeEntity>())+ val portalStates = MutableStateFlow(emptyList<StalkerPortalStateEntity>())+ val projection = CountingProjection()+ val streams = ProviderObservationStreams(+ providerDao = providerDao(identities),+ providerSnapshotDao = snapshotDao(configs, runtimes, portalStates),+ projection = projection,+ workDispatcher = StandardTestDispatcher(testScheduler)+ )+ val results = mutableListOf<List<LegacyProvider>>()+ val collector = launch { streams.providers.take(2).toList(results) }+ advanceUntilIdle()++ portalStates.value = listOf(+ StalkerPortalStateEntity(+ providerId = 9L,+ configurationGeneration = generation,+ learningJson = com.google.gson.Gson().toJson(+ StalkerPortalLearning(+ configurationGeneration = generation,+ profileId = StalkerObservation(+ value = "learned-profile",+ configurationGeneration = generation,+ source = StalkerObservationSource.DISCOVERY,+ observedAt = 10L+ )+ )+ )+ )+ )+ advanceUntilIdle()+ collector.join()++ assertThat(results).hasSize(2)+ assertThat(results.last().single().stalkerLearnedProfileId).isEqualTo("learned-profile")+ assertThat(projection.decodeCalls.get()).isEqualTo(1)+ }++ @Test+ fun `generation-only configuration change triggers one new decode`() = runTest {+ val fixture = stateFixture()+ val streams = fixture.streams(StandardTestDispatcher(testScheduler))++ streams.providers.first()+ fixture.configs.value = listOf(+ fixture.config.copy(configurationGeneration = fixture.config.configurationGeneration + 1)+ )+ streams.providers.first()++ assertThat(fixture.projection.decodeCalls.get()).isEqualTo(2)+ }++ @Test+ fun `provider order and active selection follow identity rows`() = runTest {+ val identities = MutableStateFlow(+ listOf(+ providerEntity(id = 10L, isActive = false),+ providerEntity(id = 9L, isActive = true)+ )+ )+ val configs = MutableStateFlow(listOf(configEntity(9L), configEntity(10L)))+ val streams = ProviderObservationStreams(+ providerDao = providerDao(identities),+ providerSnapshotDao = snapshotDao(+ configs,+ MutableStateFlow(emptyList()),+ MutableStateFlow(emptyList())+ ),+ projection = CountingProjection(),+ workDispatcher = StandardTestDispatcher(testScheduler)+ )++ assertThat(streams.providers.first().map(LegacyProvider::id))+ .containsExactly(10L, 9L)+ .inOrder()+ assertThat(streams.activeProvider.first()?.id).isEqualTo(9L)+ }+@Testfun `changed configuration row decodes once and removed rows are evicted`() = runTest {val fixture = stateFixture()@@ -146,6 +262,43 @@ class ProviderObservationStreamsTest {assertThat(fixture.projection.decodeCalls.get()).isEqualTo(3)}+ @Test+ fun `removed rows are evicted even when another row fails to decode`() = runTest {+ val firstConfig = configEntity(providerId = 9L)+ val secondConfig = configEntity(providerId = 10L)+ val identities = MutableStateFlow(+ listOf(+ providerEntity(id = 9L, isActive = true),+ providerEntity(id = 10L, isActive = false)+ )+ )+ val configs = MutableStateFlow(listOf(firstConfig, secondConfig))+ val runtimes = MutableStateFlow(emptyList<ProviderAccountRuntimeEntity>())+ val portalStates = MutableStateFlow(emptyList<StalkerPortalStateEntity>())+ val projection = CountingProjection()+ val streams = ProviderObservationStreams(+ providerDao = providerDao(identities),+ providerSnapshotDao = snapshotDao(configs, runtimes, portalStates),+ projection = projection,+ workDispatcher = StandardTestDispatcher(testScheduler)+ )++ assertThat(streams.providers.first()).hasSize(2)+ assertThat(projection.decodeCallsFor(9L)).isEqualTo(1)++ val changedSecondConfig = secondConfig.copy(updatedAt = 2L)+ projection.failingProviderId = 10L+ configs.value = listOf(changedSecondConfig)+ val failure = runCatching { streams.providers.first() }.exceptionOrNull()+ assertThat(failure).isInstanceOf(IllegalStateException::class.java)++ projection.failingProviderId = null+ configs.value = listOf(firstConfig, changedSecondConfig)+ assertThat(streams.providers.first()).hasSize(2)++ assertThat(projection.decodeCallsFor(9L)).isEqualTo(2)+ }+@Testfun `first waits for real DAO emissions`() = runTest {val identities = MutableSharedFlow<List<ProviderEntity>>()@@ -194,6 +347,41 @@ class ProviderObservationStreamsTest {assertThat(fixture.projection.decodeCalls.get()).isEqualTo(2)}+ @Test+ fun `failed decode reaches every concurrent collector without partial output`() = runTest {+ val identities = MutableStateFlow(listOf(providerEntity()))+ val configs = MutableSharedFlow<List<ProviderConfigEntity>>()+ val configSubscriptions = CountDownLatch(2)+ val configDeliveries = CountDownLatch(2)+ val projection = CountingProjection().apply {+ failure = IllegalStateException("decode failed")+ }+ val streams = ProviderObservationStreams(+ providerDao = providerDao(identities),+ providerSnapshotDao = snapshotDao(+ configs = configs+ .onSubscription { configSubscriptions.countDown() }+ .onEach { configDeliveries.countDown() },+ runtimes = MutableStateFlow(emptyList()),+ portalStates = MutableStateFlow(emptyList())+ ),+ projection = projection,+ workDispatcher = Dispatchers.Default+ )++ val first = async(Dispatchers.Default) { runCatching { streams.providers.first() } }+ val second = async(Dispatchers.Default) { runCatching { streams.providers.first() } }+ assertThat(configSubscriptions.await(2, TimeUnit.SECONDS)).isTrue()++ val emitter = launch(Dispatchers.Default) { configs.emit(listOf(configEntity())) }+ assertThat(configDeliveries.await(2, TimeUnit.SECONDS)).isTrue()+ emitter.join()++ assertThat(first.await().exceptionOrNull()).isInstanceOf(IllegalStateException::class.java)+ assertThat(second.await().exceptionOrNull()).isInstanceOf(IllegalStateException::class.java)+ assertThat(projection.decodeCalls.get()).isEqualTo(2)+ }+@Testfun `cold provider flow completes when all DAO flows complete`() = runTest {val projection = CountingProjection()@@ -257,12 +445,20 @@ class ProviderObservationStreamsTest {gson = com.google.gson.Gson())val decodeCalls = AtomicInteger()+ private val decodeCallsByProvider = ConcurrentHashMap<Long, AtomicInteger>()var failure: RuntimeException? = null+ var failingProviderId: Long? = nullvar decodeGate: DecodeGate? = nulloverride fun decode(entity: ProviderConfigEntity): RedactedProviderConfigurationProjection {val call = decodeCalls.incrementAndGet()+ decodeCallsByProvider+ .computeIfAbsent(entity.providerId) { AtomicInteger() }+ .incrementAndGet()failure?.let { throw it }+ if (failingProviderId == entity.providerId) {+ throw IllegalStateException("decode failed for ${entity.providerId}")+ }decodeGate?.takeIf { call == 1 }?.let { gate ->gate.started.countDown()check(gate.release.await(2, TimeUnit.SECONDS)) {@@ -272,6 +468,9 @@ class ProviderObservationStreamsTest {return delegate.decode(entity)}+ fun decodeCallsFor(providerId: Long): Int =+ decodeCallsByProvider[providerId]?.get() ?: 0+override fun assemble(identity: ProviderEntity,configuration: RedactedProviderConfigurationProjection?,@@ -294,15 +493,19 @@ class ProviderObservationStreamsTest {whenever(it.observeStalkerPortalStates()).thenReturn(portalStates)}- private fun providerEntity() = ProviderEntity(- id = 9L,+ private fun providerEntity(+ id: Long = 9L,+ isActive: Boolean = true,+ type: ProviderType = ProviderType.XTREAM_CODES+ ) = ProviderEntity(+ id = id,name = "Living room",- type = ProviderType.XTREAM_CODES,- isActive = true+ type = type,+ isActive = isActive)- private fun configEntity() = ProviderConfigEntity(- providerId = 9L,+ private fun configEntity(providerId: Long = 9L) = ProviderConfigEntity(+ providerId = providerId,type = ProviderType.XTREAM_CODES,schemaVersion = 1,configurationGeneration = 7L,@@ -317,4 +520,19 @@ class ProviderObservationStreamsTest {updatedAt = 1L)+ private fun stalkerConfigEntity(generation: Long) = ProviderConfigEntity(+ providerId = 9L,+ type = ProviderType.STALKER_PORTAL,+ schemaVersion = 1,+ configurationGeneration = generation,+ identityKey = "stalker-identity",+ encryptedConfigJson = com.google.gson.Gson().toJson(+ StalkerConfig(+ portalUrl = "https://portal.example.test",+ device = StalkerDeviceIdentity("00:11:22:33:44:55")+ )+ ),+ updatedAt = 1L+ )+}diff --git a/data/src/test/java/com/streamvault/data/provider/RoomProviderSnapshotRepositoryTest.kt b/data/src/test/java/com/streamvault/data/provider/RoomProviderSnapshotRepositoryTest.ktindex 5e526eb6..27e4f953 100644--- a/data/src/test/java/com/streamvault/data/provider/RoomProviderSnapshotRepositoryTest.kt+++ b/data/src/test/java/com/streamvault/data/provider/RoomProviderSnapshotRepositoryTest.kt@@ -5,18 +5,30 @@ import com.google.gson.Gsonimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.StalkerPortalStateDao+import com.streamvault.data.local.entity.ProviderAccountRuntimeEntityimport com.streamvault.data.local.entity.ProviderConfigEntityimport com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.local.entity.StalkerPortalStateEntity+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.ProviderConfiguration+import com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.StalkerConfig+import com.streamvault.domain.model.StalkerDeviceIdentity+import com.streamvault.domain.model.StalkerObservation+import com.streamvault.domain.model.StalkerObservationSource+import com.streamvault.domain.model.StalkerPortalLearningimport com.streamvault.domain.model.XtreamConfigimport kotlinx.coroutines.CoroutineStartimport kotlinx.coroutines.asyncimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.UnconfinedTestDispatcherimport kotlinx.coroutines.test.advanceUntilIdleimport kotlinx.coroutines.test.runTestimport org.junit.Testimport org.mockito.kotlin.mock+import org.mockito.kotlin.neverimport org.mockito.kotlin.verifyimport org.mockito.kotlin.verifyNoInteractionsimport org.mockito.kotlin.whenever@@ -24,33 +36,20 @@ import org.mockito.kotlin.whenever@OptIn(ExperimentalCoroutinesApi::class)class RoomProviderSnapshotRepositoryTest {+ private val gson = Gson()+ private val codec = ProviderConfigurationCodec(+ gson = gson,+ credentialCrypto = object : com.streamvault.data.security.CredentialCrypto {+ override fun encryptIfNeeded(value: String): String = value+ override fun decryptIfNeeded(value: String): String = value+ }+ )+@Testfun `snapshot reads and decodes run on supplied dispatcher`() = runTest {val dispatcher = StandardTestDispatcher(testScheduler)- val gson = Gson()- val provider = ProviderEntity(- id = 9L,- name = "Living room",- type = ProviderType.XTREAM_CODES- )- val codec = ProviderConfigurationCodec(- gson = gson,- credentialCrypto = object : com.streamvault.data.security.CredentialCrypto {- override fun encryptIfNeeded(value: String): String = value- override fun decryptIfNeeded(value: String): String = value- }- )- val config = ProviderConfigEntity(- providerId = provider.id,- type = provider.type,- schemaVersion = 1,- configurationGeneration = 3L,- identityKey = "identity",- encryptedConfigJson = codec.encode(- XtreamConfig("https://example.test", "user", "password")- ),- updatedAt = 1L- )+ val provider = providerEntity()+ val config = configEntity(XtreamConfig("https://example.test", "user", "password"))val providerDao = mock<ProviderDao>()val snapshotDao = mock<ProviderSnapshotDao>()val stalkerPortalStateDao = mock<StalkerPortalStateDao>()@@ -59,14 +58,7 @@ class RoomProviderSnapshotRepositoryTest {whenever(snapshotDao.getRuntime(provider.id)).thenReturn(null)whenever(stalkerPortalStateDao.get(provider.id)).thenReturn(null)- val repository = RoomProviderSnapshotRepository(- providerDao = providerDao,- snapshotDao = snapshotDao,- stalkerPortalStateDao = stalkerPortalStateDao,- codec = codec,- gson = gson,- workDispatcher = dispatcher- )+ val repository = repository(providerDao, snapshotDao, stalkerPortalStateDao, dispatcher)val result = async(start = CoroutineStart.UNDISPATCHED) {repository.getSnapshot(provider.id)@@ -82,4 +74,199 @@ class RoomProviderSnapshotRepositoryTest {verify(snapshotDao).getConfig(provider.id)verify(snapshotDao).getRuntime(provider.id)}++ @Test+ fun `snapshot preserves credentials identity and runtime fields`() = runTest {+ val provider = providerEntity().copy(+ isActive = false,+ status = ProviderStatus.ACTIVE,+ lastSyncedAt = 41L,+ createdAt = 42L+ )+ val configuration = XtreamConfig(+ serverUrl = "https://example.test",+ username = "user",+ password = "secret"+ )+ val runtime = ProviderAccountRuntimeEntity(+ providerId = provider.id,+ maxConnections = 4,+ expirationDate = 1234L,+ apiVersion = "v2",+ allowedOutputFormatsJson = "[\"m3u8\",\"ts\"]",+ catalogLayout = CatalogLayout.UNIFIED_VOD,+ catalogLayoutDetectionVersion = 3,+ observedAt = 99L+ )+ val providerDao = mock<ProviderDao>()+ val snapshotDao = mock<ProviderSnapshotDao>()+ val stalkerPortalStateDao = mock<StalkerPortalStateDao>()+ whenever(providerDao.getById(provider.id)).thenReturn(provider)+ whenever(snapshotDao.getConfig(provider.id)).thenReturn(configEntity(configuration))+ whenever(snapshotDao.getRuntime(provider.id)).thenReturn(runtime)++ val result = repository(+ providerDao,+ snapshotDao,+ stalkerPortalStateDao,+ UnconfinedTestDispatcher(testScheduler)+ ).getSnapshot(provider.id)++ assertThat(result?.configuration).isEqualTo(configuration)+ assertThat((result?.configuration as XtreamConfig).password).isEqualTo("secret")+ assertThat(result.provider.isActive).isFalse()+ assertThat(result.provider.status).isEqualTo(ProviderStatus.ACTIVE)+ assertThat(result.provider.lastSyncedAt).isEqualTo(41L)+ assertThat(result.provider.createdAt).isEqualTo(42L)+ assertThat(result.accountRuntime.maxConnections).isEqualTo(4)+ assertThat(result.accountRuntime.expirationDate).isEqualTo(1234L)+ assertThat(result.accountRuntime.apiVersion).isEqualTo("v2")+ assertThat(result.accountRuntime.allowedOutputFormats).containsExactly("m3u8", "ts").inOrder()+ assertThat(result.accountRuntime.catalogLayout).isEqualTo(CatalogLayout.UNIFIED_VOD)+ assertThat(result.accountRuntime.catalogLayoutDetectionVersion).isEqualTo(3)+ assertThat(result.accountRuntime.observedAt).isEqualTo(99L)+ verifyNoInteractions(stalkerPortalStateDao)+ }++ @Test+ fun `missing provider returns null without reading snapshot rows`() = runTest {+ val providerDao = mock<ProviderDao>()+ val snapshotDao = mock<ProviderSnapshotDao>()+ val stalkerPortalStateDao = mock<StalkerPortalStateDao>()+ whenever(providerDao.getById(9L)).thenReturn(null)++ val result = repository(+ providerDao,+ snapshotDao,+ stalkerPortalStateDao,+ UnconfinedTestDispatcher(testScheduler)+ ).getSnapshot(9L)++ assertThat(result).isNull()+ verifyNoInteractions(snapshotDao, stalkerPortalStateDao)+ }++ @Test+ fun `missing configuration returns null without reading runtime or learning`() = runTest {+ val provider = providerEntity()+ val providerDao = mock<ProviderDao>()+ val snapshotDao = mock<ProviderSnapshotDao>()+ val stalkerPortalStateDao = mock<StalkerPortalStateDao>()+ whenever(providerDao.getById(provider.id)).thenReturn(provider)+ whenever(snapshotDao.getConfig(provider.id)).thenReturn(null)++ val result = repository(+ providerDao,+ snapshotDao,+ stalkerPortalStateDao,+ UnconfinedTestDispatcher(testScheduler)+ ).getSnapshot(provider.id)++ assertThat(result).isNull()+ verify(snapshotDao, never()).getRuntime(provider.id)+ verifyNoInteractions(stalkerPortalStateDao)+ }++ @Test+ fun `provider and configuration type mismatch fails before decoding`() = runTest {+ val provider = providerEntity(type = ProviderType.M3U)+ val providerDao = mock<ProviderDao>()+ val snapshotDao = mock<ProviderSnapshotDao>()+ val stalkerPortalStateDao = mock<StalkerPortalStateDao>()+ whenever(providerDao.getById(provider.id)).thenReturn(provider)+ whenever(snapshotDao.getConfig(provider.id)).thenReturn(+ configEntity(XtreamConfig("https://example.test", "user", "secret"))+ )++ val failure = runCatching {+ repository(+ providerDao,+ snapshotDao,+ stalkerPortalStateDao,+ UnconfinedTestDispatcher(testScheduler)+ ).getSnapshot(provider.id)+ }.exceptionOrNull()++ assertThat(failure).isInstanceOf(IllegalStateException::class.java)+ assertThat(failure).hasMessageThat().contains("type mismatch")+ verify(snapshotDao, never()).getRuntime(provider.id)+ verifyNoInteractions(stalkerPortalStateDao)+ }++ @Test+ fun `generation-valid Stalker learning is preserved in snapshot`() = runTest {+ val generation = 7L+ val provider = providerEntity(type = ProviderType.STALKER_PORTAL)+ val configuration = StalkerConfig(+ portalUrl = "https://portal.example.test",+ device = StalkerDeviceIdentity("00:11:22:33:44:55"),+ password = "secret"+ )+ val learning = StalkerPortalLearning(+ configurationGeneration = generation,+ workingEndpoint = StalkerObservation(+ value = "/stalker_portal/server/load.php",+ configurationGeneration = generation,+ source = StalkerObservationSource.DISCOVERY,+ observedAt = 81L+ )+ )+ val providerDao = mock<ProviderDao>()+ val snapshotDao = mock<ProviderSnapshotDao>()+ val stalkerPortalStateDao = mock<StalkerPortalStateDao>()+ whenever(providerDao.getById(provider.id)).thenReturn(provider)+ whenever(snapshotDao.getConfig(provider.id)).thenReturn(configEntity(configuration, generation))+ whenever(snapshotDao.getRuntime(provider.id)).thenReturn(null)+ whenever(stalkerPortalStateDao.get(provider.id)).thenReturn(+ StalkerPortalStateEntity(+ providerId = provider.id,+ configurationGeneration = generation,+ learningJson = gson.toJson(learning)+ )+ )++ val result = repository(+ providerDao,+ snapshotDao,+ stalkerPortalStateDao,+ UnconfinedTestDispatcher(testScheduler)+ ).getSnapshot(provider.id)++ assertThat(result?.configuration).isEqualTo(configuration)+ assertThat(result?.configurationGeneration).isEqualTo(generation)+ assertThat(result?.stalkerLearning).isEqualTo(learning)+ }++ private fun providerEntity(type: ProviderType = ProviderType.XTREAM_CODES) = ProviderEntity(+ id = 9L,+ name = "Living room",+ type = type+ )++ private fun configEntity(+ configuration: ProviderConfiguration,+ generation: Long = 3L+ ) = ProviderConfigEntity(+ providerId = 9L,+ type = configuration.type,+ schemaVersion = configuration.schemaVersion,+ configurationGeneration = generation,+ identityKey = "identity",+ encryptedConfigJson = codec.encode(configuration),+ updatedAt = 1L+ )++ private fun repository(+ providerDao: ProviderDao,+ snapshotDao: ProviderSnapshotDao,+ stalkerPortalStateDao: StalkerPortalStateDao,+ dispatcher: kotlinx.coroutines.CoroutineDispatcher+ ) = RoomProviderSnapshotRepository(+ providerDao = providerDao,+ snapshotDao = snapshotDao,+ stalkerPortalStateDao = stalkerPortalStateDao,+ codec = codec,+ gson = gson,+ workDispatcher = dispatcher+ )}