Modern Apps git

← Modern-Apps.git

cast: cancelling one discovery flow no longer kills the other

Commit
b1ef26a5dcbb80c287af12712f8bc202f9d59376
Author
Vayun Mathur <[email protected]>
When
2026-11-30 22:14 UTC (5 days ago)
Parents
3d759b4
CastDiscoveryManager kept its NSD listener in one shared field:
starting a second discovery collection overwrote it, so
cancelling the first collection stopped the SECOND collection's
browse while the first listener stayed registered with NSD
forever, still merging devices into the list from a cancelled
flow. Depending on which flow survived, devices silently
stopped appearing/vanishing, and the tile's re-resolve could be
killed by the app scan's restart, timing out into the
open-the-app fallback.

Each callbackFlow collection now stops exactly the listener it
created; there is no manager-global listener field. New
overlap regression test (cancel the first of two collections;
the second stays registered and resolving; both clean up)
failed pre-fix with the leak exactly as predicted. Session
lifecycle, protocol framing/crypto and TV playback state were
audited and cleared. Verified: :cast:testDevUnitTest 220 tests
pass, detekt green; one pre-existing screenshot-coverage lint
error on untouched Route.kt.

Diff

cast/src/main/java/com/vayunmathur/cast/platform/discovery/CastDiscoveryManager.kt
diff --git a/cast/src/main/java/com/vayunmathur/cast/platform/discovery/CastDiscoveryManager.kt b/cast/src/main/java/com/vayunmathur/cast/platform/discovery/CastDiscoveryManager.ktindex c720a09fb5..a68e9d94e9 100644--- a/cast/src/main/java/com/vayunmathur/cast/platform/discovery/CastDiscoveryManager.kt+++ b/cast/src/main/java/com/vayunmathur/cast/platform/discovery/CastDiscoveryManager.kt@@ -40,8 +40,6 @@ class CastDiscoveryManager(context: Context) {     private val nsdManager: NsdManager? =         context.getSystemService(Context.NSD_SERVICE) as? NsdManager -    private var discoveryListener: NsdManager.DiscoveryListener? = null-     private val _devices = MutableStateFlow<List<CastDevice>>(emptyList())     val devices: StateFlow<List<CastDevice>> = _devices.asStateFlow() @@ -106,7 +104,11 @@ class CastDiscoveryManager(context: Context) {                 Log.status(TAG, "stopDiscovery failed: $errorCode")             }         }-        discoveryListener = listener+        // The listener is this collection's own, never a field of the manager: the+        // Cast screen, the Quick Settings tile and the remote-display provider+        // collect this flow concurrently from the one shared manager, so a+        // shared field would let one collection's cancellation stop (and leak)+        // another collection's browse.         try {             manager.discoverServices(MACAST_SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, listener)         } catch (e: SecurityException) {@@ -114,22 +116,19 @@ class CastDiscoveryManager(context: Context) {             // OS blocks mDNS outright until ACCESS_LOCAL_NETWORK is granted.             Log.error(TAG, "mDNS browse blocked - ACCESS_LOCAL_NETWORK not granted", e)             _localNetworkBlocked.value = true-            discoveryListener = null             close()             return@callbackFlow         } catch (e: IllegalArgumentException) {             Log.status(TAG, "discoverServices threw", e)-            discoveryListener = null             close(e)             return@callbackFlow         }         awaitClose {             try {-                discoveryListener?.let { manager.stopServiceDiscovery(it) }+                manager.stopServiceDiscovery(listener)             } catch (_: IllegalArgumentException) {             } catch (_: SecurityException) {             }-            discoveryListener = null         }     } 
cast/src/test/java/com/vayunmathur/cast/platform/discovery/DiscoveryOverlapTest.kt
diff --git a/cast/src/test/java/com/vayunmathur/cast/platform/discovery/DiscoveryOverlapTest.kt b/cast/src/test/java/com/vayunmathur/cast/platform/discovery/DiscoveryOverlapTest.ktnew file mode 100644index 0000000000..c487f3073b--- /dev/null+++ b/cast/src/test/java/com/vayunmathur/cast/platform/discovery/DiscoveryOverlapTest.kt@@ -0,0 +1,115 @@+package com.vayunmathur.cast.platform.discovery++import android.content.Context+import android.net.nsd.NsdManager+import android.net.nsd.NsdServiceInfo+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.cast.protocol.MACAST_SERVICE_TYPE+import java.net.InetAddress+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.async+import kotlinx.coroutines.delay+import kotlinx.coroutines.runBlocking+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Shadows+import org.robolectric.annotation.GraphicsMode+import org.robolectric.shadows.ShadowNsdManager++/**+ * Two collections of the same manager's browse at once — the Cast screen's+ * scan, the Quick Settings tile's one-shot resolve and the remote-display+ * provider's browse are three collectors of the one shared manager, and they+ * overlap in one process. Cancelling one must stop only its own browse.+ */+@RunWith(AndroidJUnit4::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class DiscoveryOverlapTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val nsd: NsdManager get() = context.getSystemService(NsdManager::class.java)+    private val shadow: ShadowNsdManager get() = Shadows.shadowOf(nsd)++    @Before fun reset() {+        ShadowNsdManager.reset()+    }++    @After fun cleanup() {+        ShadowNsdManager.reset()+    }++    private fun listeners(): List<NsdManager.DiscoveryListener> =+        shadow.getDiscoveryListeners(MACAST_SERVICE_TYPE) ?: emptyList()++    private suspend fun awaitListeners(count: Int): List<NsdManager.DiscoveryListener> {+        awaitCondition({ "expected $count discovery listeners, saw ${listeners().size}" }) {+            listeners().size == count+        }+        return listeners()+    }++    // Per-listener registration, not the by-type list: Robolectric's shadow+    // drops the whole by-type list on any one stop, while the map behind+    // getDiscoveryListenerServiceType is removed per listener as on a device.+    private fun isRegistered(listener: NsdManager.DiscoveryListener): Boolean =+        shadow.getDiscoveryListenerServiceType(listener) == MACAST_SERVICE_TYPE++    private suspend fun awaitCondition(message: () -> String, condition: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 5_000+        while (true) {+            if (condition()) return+            if (System.currentTimeMillis() > deadline) throw AssertionError(message())+            delay(20)+        }+    }++    private fun serviceInfo(name: String): NsdServiceInfo = NsdServiceInfo().apply {+        serviceName = name+        serviceType = MACAST_SERVICE_TYPE+        setPort(41_000)+        setHost(InetAddress.getByName("192.168.1.50"))+        setAttribute("fn", "Living Room TV")+        setAttribute("id", "tv-uuid-1")+        setAttribute("pv", "9")+    }++    @Test+    fun `cancelling one collector leaves the other browse running`() = runBlocking {+        val manager = CastDiscoveryManager(context)+        val scope = CoroutineScope(Dispatchers.IO)+        val first: Job = scope.async { manager.discover().collect { } }+        val firstListeners = awaitListeners(1)++        val second: Job = scope.async { manager.discover().collect { } }+        val both = awaitListeners(2)+        val secondListener = both.first { it !== firstListeners[0] }++        // Cancelling the first collection must unregister only its listener.+        first.cancel()+        awaitCondition({ "first listener still registered after its cancel" }) {+            !isRegistered(firstListeners[0])+        }+        assertEquals(true, isRegistered(secondListener))++        // And the surviving browse still delivers devices.+        secondListener.onServiceFound(serviceInfo("Living Room TV (instance)"))+        val resolvers = shadow.getResolveListeners(serviceInfo("Living Room TV (instance)"))+            ?: emptyList()+        assertTrue(resolvers.isNotEmpty(), "surviving browse should still resolve")+        resolvers.forEach { it.onServiceResolved(serviceInfo("Living Room TV (instance)")) }+        assertEquals(listOf("tv-uuid-1"), manager.devices.value.map { it.id })++        second.cancel()+        awaitCondition({ "second listener still registered after its cancel" }) {+            !isRegistered(secondListener)+        }+        Unit+    }+}