Skip to content

Commit 4d3f0ba

Browse files
committed
Ensure that proxy tests run in parallel
1 parent 8e7cce4 commit 4d3f0ba

File tree

2 files changed

+12
-16
lines changed

2 files changed

+12
-16
lines changed

app/src/main/java/tech/httptoolkit/android/AwaitFirst.kt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ suspend fun <T>Collection<Deferred<T>>.awaitFirst(): T {
1919

2020
if (error == null) {
2121
@Suppress("EXPERIMENTAL_API_USAGE")
22+
this.forEach { item -> item.cancel() } // Cancel all remaining tasks
2223
result.complete(item.getCompleted())
2324
} else {
2425
val remaining = stillRunningCount.decrementAndGet()

app/src/main/java/tech/httptoolkit/android/ProxySetup.kt

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@ import android.util.Base64
88
import android.util.Log
99
import androidx.core.content.ContextCompat.getSystemService
1010
import com.beust.klaxon.Klaxon
11-
import kotlinx.coroutines.Dispatchers
12-
import kotlinx.coroutines.async
13-
import kotlinx.coroutines.supervisorScope
14-
import kotlinx.coroutines.withContext
11+
import kotlinx.coroutines.*
1512
import okhttp3.OkHttpClient
1613
import okhttp3.Request
1714
import java.io.ByteArrayInputStream
@@ -45,10 +42,9 @@ fun parseConnectUri(uri: Uri): ProxyInfo {
4542

4643
suspend fun getProxyConfig(proxyInfo: ProxyInfo): ProxyConfig {
4744
return withContext(Dispatchers.IO) {
48-
Log.v(TAG, "Validating proxy info $proxyInfo")
49-
50-
val proxyTests = proxyInfo.addresses.map { address ->
51-
supervisorScope {
45+
return@withContext supervisorScope {
46+
Log.v(TAG, "Validating proxy info $proxyInfo")
47+
val proxyTests = proxyInfo.addresses.map { address ->
5248
async {
5349
testProxyAddress(
5450
address,
@@ -57,16 +53,13 @@ suspend fun getProxyConfig(proxyInfo: ProxyInfo): ProxyConfig {
5753
)
5854
}
5955
}
60-
}
6156

62-
// Returns with the first working proxy config (cert & address),
63-
// or throws if all possible addresses are unreachable/invalid
64-
// Once the first test succeeds, we cancel any others
65-
val result = proxyTests.awaitFirst()
66-
proxyTests.forEach { test ->
67-
test.cancel()
57+
Log.v(TAG, "Proxy tests started")
58+
59+
// Return with the first working proxy config (cert & address)
60+
// (or throw if all addresses are unreachable/invalid)
61+
return@supervisorScope proxyTests.awaitFirst()
6862
}
69-
return@withContext result
7063
}
7164
}
7265

@@ -84,6 +77,8 @@ private suspend fun testProxyAddress(
8477
.readTimeout(2, TimeUnit.SECONDS)
8578
.build()
8679

80+
Log.i(TAG, "Testing proxy $address:$port")
81+
8782
val request = Request.Builder()
8883
.url("http://android.httptoolkit.tech/config")
8984
.build()

0 commit comments

Comments
 (0)