Skip to content

Commit 612cbcb

Browse files
vonovakclaude
andcommitted
Fix stale inspector connections on Android
DevServerHelper opened and closed the inspector connection in separate AsyncTasks, and the connection lives across reloads. After the dev server host changed, the next open saw an existing connection and did nothing, so the debugger stayed attached through the old Metro server. - Run openInspectorConnection and closeInspectorConnection on the same single-threaded executor as the packager connection. - Remember the host of the open inspector connection. If an open finds a connection for a different host, close it and connect to the new host. - Make inspectorPackagerConnection volatile, because disableDebugger() reads it from other threads. - DevServerHelper no longer uses AsyncTask: remove the import, the related comments, and @SuppressLint("StaticFieldLeak"). Lint reports no StaticFieldLeak issue without it. - Add inspector tests to DevServerHelperTest, with a test factory that avoids the native connection class. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 99a157b commit 612cbcb

2 files changed

Lines changed: 91 additions & 43 deletions

File tree

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.kt‎

Lines changed: 34 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,13 @@
55
* LICENSE file in the root directory of this source tree.
66
*/
77

8-
// Conflicting okhttp versions + This class needs to be rewritten to don't
9-
// use AsyncTasks
8+
// Conflicting okhttp versions
109
@file:Suppress("DEPRECATION", "DEPRECATION_ERROR")
1110

1211
package com.facebook.react.devsupport
1312

14-
import android.annotation.SuppressLint
1513
import android.content.Context
1614
import android.net.Uri
17-
import android.os.AsyncTask
1815
import android.provider.Settings.Secure
1916
import androidx.annotation.VisibleForTesting
2017
import com.facebook.common.logging.FLog
@@ -61,9 +58,6 @@ import okio.Okio
6158
* - Android stock emulator with standard non-configurable local loopback alias: 10.0.2.2
6259
* - Genymotion emulator with default settings: 10.0.3.2
6360
*/
64-
@SuppressLint(
65-
"StaticFieldLeak",
66-
) // TODO: This entire class should be rewritten to don't use AsyncTask
6761
public open class DevServerHelper(
6862
private val settings: DeveloperSettings,
6963
private val applicationContext: Context,
@@ -101,7 +95,19 @@ public open class DevServerHelper(
10195
}
10296
private var packagerClient: JSPackagerClient? = null
10397
private var packagerClientHost: String? = null
104-
private var inspectorPackagerConnection: IInspectorPackagerConnection? = null
98+
// Written on the executor thread; disableDebugger() reads it from other threads.
99+
@Volatile private var inspectorPackagerConnection: IInspectorPackagerConnection? = null
100+
private var inspectorPackagerConnectionHost: String? = null
101+
@VisibleForTesting
102+
internal var inspectorConnectionFactory: () -> IInspectorPackagerConnection? = {
103+
val deviceName = getInspectorHostMetadata(applicationContext)["deviceName"]
104+
if (deviceName == null) {
105+
FLog.w(ReactConstants.TAG, "Could not get device name from Inspector Host Metadata.")
106+
null
107+
} else {
108+
CxxInspectorPackagerConnection(inspectorDeviceUrl, deviceName, packageName)
109+
}
110+
}
105111

106112
/** Returns an opaque ID which is stable for the current combination of device and app, stable */
107113
private val inspectorDeviceId: String
@@ -210,46 +216,34 @@ public open class DevServerHelper(
210216
}
211217

212218
public fun openInspectorConnection() {
213-
if (inspectorPackagerConnection != null) {
214-
FLog.w(ReactConstants.TAG, "Inspector connection already open, nooping.")
215-
return
216-
}
217-
object : AsyncTask<Void, Void, Void>() {
218-
@Deprecated("This class needs to be rewritten to don't use AsyncTasks")
219-
override fun doInBackground(vararg params: Void): Void? {
220-
val metadata = getInspectorHostMetadata(applicationContext)
221-
val deviceName = metadata["deviceName"]
222-
if (deviceName == null) {
223-
FLog.w(ReactConstants.TAG, "Could not get device name from Inspector Host Metadata.")
224-
return null
225-
}
226-
inspectorPackagerConnection =
227-
CxxInspectorPackagerConnection(
228-
this@DevServerHelper.inspectorDeviceUrl,
229-
deviceName,
230-
packageName,
231-
)
232-
.apply { connect() }
233-
return null
234-
}
219+
packagerConnectionExecutor.execute {
220+
val host = packagerConnectionSettings.debugServerHost
221+
inspectorPackagerConnection?.let { connection ->
222+
if (host == inspectorPackagerConnectionHost) {
223+
FLog.w(ReactConstants.TAG, "Inspector connection already open, nooping.")
224+
return@execute
235225
}
236-
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
226+
// The dev server host changed without a close.
227+
connection.closeQuietly()
228+
inspectorPackagerConnection = null
229+
}
230+
val connection = inspectorConnectionFactory() ?: return@execute
231+
connection.connect()
232+
inspectorPackagerConnection = connection
233+
inspectorPackagerConnectionHost = host
234+
}
237235
}
238236

239237
public fun disableDebugger() {
240238
inspectorPackagerConnection?.sendEventToAllConnections(DEBUGGER_MSG_DISABLE)
241239
}
242240

243241
public fun closeInspectorConnection() {
244-
object : AsyncTask<Void, Void, Void>() {
245-
@Deprecated("This class needs to be rewritten to don't use AsyncTasks")
246-
override fun doInBackground(vararg params: Void): Void? {
247-
inspectorPackagerConnection?.closeQuietly()
248-
inspectorPackagerConnection = null
249-
return null
250-
}
251-
}
252-
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
242+
packagerConnectionExecutor.execute {
243+
inspectorPackagerConnection?.closeQuietly()
244+
inspectorPackagerConnection = null
245+
inspectorPackagerConnectionHost = null
246+
}
253247
}
254248

255249
@JvmOverloads

‎packages/react-native/ReactAndroid/src/test/java/com/facebook/react/devsupport/DevServerHelperTest.kt‎

Lines changed: 57 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ class DevServerHelperTest {
4040
private val listener: PackagerCommandListener = mock()
4141
private val pending = ArrayDeque<Runnable>()
4242
private var onConnect: () -> Unit = {}
43+
private val inspectors = mutableListOf<FakeInspector>()
4344

4445
@Before
4546
fun setUp() {
@@ -48,13 +49,20 @@ class DevServerHelperTest {
4849
sockets = mockSockets()
4950
helper = DevServerHelper(mock(), RuntimeEnvironment.getApplication(), settings)
5051
helper.packagerConnectionExecutor = Executor { pending.add(it) }
52+
helper.inspectorConnectionFactory = {
53+
FakeInspector(settings.debugServerHost).also { inspectors.add(it) }
54+
}
5155
}
5256

5357
@After
5458
fun tearDown() {
55-
helper.closePackagerConnection()
56-
runPending()
57-
sockets.close()
59+
try {
60+
helper.closePackagerConnection()
61+
helper.closeInspectorConnection()
62+
runPending()
63+
} finally {
64+
sockets.close()
65+
}
5866
}
5967

6068
@Test
@@ -128,6 +136,38 @@ class DevServerHelperTest {
128136
verify(listener).onPackagerReloadCommand()
129137
}
130138

139+
@Test
140+
fun repeatedInspectorOpenCreatesOnlyOneConnection() {
141+
helper.openInspectorConnection()
142+
helper.openInspectorConnection()
143+
runPending()
144+
145+
assertThat(inspectors).hasSize(1)
146+
assertThat(inspectors.single().connected).isTrue()
147+
}
148+
149+
@Test
150+
fun inspectorCloseQueuedAfterOpenRetiresTheConnection() {
151+
helper.openInspectorConnection()
152+
helper.closeInspectorConnection()
153+
runPending()
154+
155+
assertThat(inspectors).hasSize(1)
156+
assertThat(inspectors.single().connected).isFalse()
157+
}
158+
159+
@Test
160+
fun inspectorOpenAfterHostChangeUsesOnlyTheNewServer() {
161+
helper.openInspectorConnection()
162+
runPending()
163+
whenever(settings.debugServerHost).thenReturn("127.0.0.1:8082")
164+
helper.openInspectorConnection()
165+
runPending()
166+
167+
assertThat(inspectors.map { it.host }).containsExactly("127.0.0.1:8083", "127.0.0.1:8082")
168+
assertThat(inspectors.filter { it.connected }.map { it.host }).containsExactly("127.0.0.1:8082")
169+
}
170+
131171
private fun runPending() {
132172
while (true) {
133173
val task = pending.poll() ?: return
@@ -161,6 +201,20 @@ class DevServerHelperTest {
161201

162202
private fun connectedPeers(): List<Peer> = peers.filter { it.connected }
163203

204+
private class FakeInspector(val host: String) : IInspectorPackagerConnection {
205+
var connected = false
206+
207+
override fun connect() {
208+
connected = true
209+
}
210+
211+
override fun closeQuietly() {
212+
connected = false
213+
}
214+
215+
override fun sendEventToAllConnections(event: String?) = Unit
216+
}
217+
164218
private class Peer(val url: String, val callback: ReconnectingWebSocket.MessageCallback) {
165219
@Volatile var connected = false
166220
val port: Int

0 commit comments

Comments
 (0)