From aca12e894af6580a3b4024be6c0aa799479c0317 Mon Sep 17 00:00:00 2001 From: mx57 <38256814+mx57@users.noreply.github.com> Date: Fri, 9 Oct 2026 23:16:49 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=20Perf:=20optimize=20NetworkEgressVer?= =?UTF-8?q?ifier=20fallback=20IP=20checks=20with=20concurrent=20coroutines?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Optimize tryCloudflareTrace and tryIpify by querying fallback endpoints concurrently with coroutines, CompletableDeferred, and scope cancellation to return as soon as the first successful response arrives. --- .../data/remote/NetworkEgressVerifier.kt | 159 +++++++++++------- .../data/remote/NetworkEgressVerifierTest.kt | 134 +++++++++++++++ 2 files changed, 236 insertions(+), 57 deletions(-) create mode 100644 app/src/test/java/com/example/data/remote/NetworkEgressVerifierTest.kt diff --git a/app/src/main/java/com/example/data/remote/NetworkEgressVerifier.kt b/app/src/main/java/com/example/data/remote/NetworkEgressVerifier.kt index 064bc4c..4fec052 100644 --- a/app/src/main/java/com/example/data/remote/NetworkEgressVerifier.kt +++ b/app/src/main/java/com/example/data/remote/NetworkEgressVerifier.kt @@ -1,7 +1,11 @@ package com.example.data.remote import com.example.domain.model.NetworkEgressResult +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.cancelChildren +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import okhttp3.OkHttpClient import okhttp3.Request @@ -9,6 +13,7 @@ import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetAddress import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger /** * Verifies outbound network reachability and internet exit (egress) through the active VPN / Root tunnel. @@ -89,76 +94,101 @@ class NetworkEgressVerifier( } } - private fun tryCloudflareTrace(): NetworkEgressResult? { - val endpoints = listOf( - "https://1.1.1.1/cdn-cgi/trace", - "https://www.cloudflare.com/cdn-cgi/trace", - "https://cloudflare-dns.com/cdn-cgi/trace" - ) + suspend fun tryCloudflareTrace(endpoints: List = DEFAULT_CLOUDFLARE_ENDPOINTS): NetworkEgressResult? = coroutineScope { + if (endpoints.isEmpty()) return@coroutineScope null + val deferred = CompletableDeferred() + val failureCount = AtomicInteger(0) - for (url in endpoints) { - try { - val request = Request.Builder() - .url(url) - .header("User-Agent", "AWGMutator-EgressProbe/1.0") - .build() - - client.newCall(request).execute().use { response -> - if (response.isSuccessful) { - val body = response.body?.string().orEmpty() - val lines = body.lines().associate { line -> - val parts = line.split("=", limit = 2) - if (parts.size == 2) parts[0].trim() to parts[1].trim() else "" to "" - } + endpoints.forEach { url -> + launch(Dispatchers.IO) { + try { + val request = Request.Builder() + .url(url) + .header("User-Agent", "AWGMutator-EgressProbe/1.0") + .build() + + client.newCall(request).execute().use { response -> + if (response.isSuccessful) { + val body = response.body?.string().orEmpty() + val lines = body.lines().associate { line -> + val parts = line.split("=", limit = 2) + if (parts.size == 2) parts[0].trim() to parts[1].trim() else "" to "" + } + + val ip = lines["ip"] + val loc = lines["loc"] + val warp = lines["warp"] - val ip = lines["ip"] - val loc = lines["loc"] - val warp = lines["warp"] - - if (!ip.isNullOrBlank()) { - com.example.App.instance.tunnelManager.log("EGRESS_PROBE", "Cloudflare Trace Probe Success ($url) -> Public IP=$ip, Loc=$loc, WARP=$warp") - return NetworkEgressResult( - isFunctional = true, - publicIp = ip, - countryCode = loc ?: "CF", - cityOrIsp = "Cloudflare Edge ($loc)", - warpStatus = warp, - isWarpActive = warp == "on" || warp == "plus", - testedAt = System.currentTimeMillis() - ) + if (!ip.isNullOrBlank()) { + com.example.App.instance.tunnelManager.log("EGRESS_PROBE", "Cloudflare Trace Probe Success ($url) -> Public IP=$ip, Loc=$loc, WARP=$warp") + val egressResult = NetworkEgressResult( + isFunctional = true, + publicIp = ip, + countryCode = loc ?: "CF", + cityOrIsp = "Cloudflare Edge ($loc)", + warpStatus = warp, + isWarpActive = warp == "on" || warp == "plus", + testedAt = System.currentTimeMillis() + ) + if (deferred.complete(egressResult)) { + this@coroutineScope.coroutineContext.cancelChildren() + } + return@launch + } + } else { + com.example.App.instance.tunnelManager.log("EGRESS_PROBE", "Cloudflare Trace Probe HTTP ${response.code} from $url") } - } else { - com.example.App.instance.tunnelManager.log("EGRESS_PROBE", "Cloudflare Trace Probe HTTP ${response.code} from $url") } + } catch (e: Exception) { + com.example.App.instance.tunnelManager.log("EGRESS_PROBE", "Cloudflare Trace Probe failed for $url: ${e.message}") + } + + if (failureCount.incrementAndGet() == endpoints.size) { + deferred.completeExceptionally(NoSuchElementException("All trace endpoints failed")) } - } catch (e: Exception) { - com.example.App.instance.tunnelManager.log("EGRESS_PROBE", "Cloudflare Trace Probe failed for $url: ${e.message}") } } - return null + + try { + deferred.await() + } catch (_: Exception) { + null + } } - private fun tryIpify(): String? { - val ipEndpoints = listOf( - "https://api.ipify.org", - "https://icanhazip.com", - "https://checkip.amazonaws.com", - "https://ifconfig.me/ip" - ) - for (url in ipEndpoints) { - try { - val request = Request.Builder().url(url).build() - client.newCall(request).execute().use { resp -> - if (resp.isSuccessful) { - val ip = resp.body?.string()?.trim() - if (!ip.isNullOrBlank() && (ip.contains(".") || ip.contains(":"))) { - return ip + suspend fun tryIpify(endpoints: List = DEFAULT_IPIFY_ENDPOINTS): String? = coroutineScope { + if (endpoints.isEmpty()) return@coroutineScope null + val deferred = CompletableDeferred() + val failureCount = AtomicInteger(0) + + endpoints.forEach { url -> + launch(Dispatchers.IO) { + try { + val request = Request.Builder().url(url).build() + client.newCall(request).execute().use { resp -> + if (resp.isSuccessful) { + val ip = resp.body?.string()?.trim() + if (!ip.isNullOrBlank() && (ip.contains(".") || ip.contains(":"))) { + if (deferred.complete(ip)) { + this@coroutineScope.coroutineContext.cancelChildren() + } + return@launch + } } } + } catch (_: Exception) {} + + if (failureCount.incrementAndGet() == endpoints.size) { + deferred.completeExceptionally(NoSuchElementException("All IP endpoints failed")) } - } catch (_: Exception) {} + } + } + + try { + deferred.await() + } catch (_: Exception) { + null } - return null } private fun checkDnsResolution(): Boolean { @@ -191,4 +221,19 @@ class NetworkEgressVerifier( } return false } + + companion object { + val DEFAULT_CLOUDFLARE_ENDPOINTS = listOf( + "https://1.1.1.1/cdn-cgi/trace", + "https://www.cloudflare.com/cdn-cgi/trace", + "https://cloudflare-dns.com/cdn-cgi/trace" + ) + + val DEFAULT_IPIFY_ENDPOINTS = listOf( + "https://api.ipify.org", + "https://icanhazip.com", + "https://checkip.amazonaws.com", + "https://ifconfig.me/ip" + ) + } } diff --git a/app/src/test/java/com/example/data/remote/NetworkEgressVerifierTest.kt b/app/src/test/java/com/example/data/remote/NetworkEgressVerifierTest.kt new file mode 100644 index 0000000..ff97da0 --- /dev/null +++ b/app/src/test/java/com/example/data/remote/NetworkEgressVerifierTest.kt @@ -0,0 +1,134 @@ +package com.example.data.remote + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Before +import org.junit.Test +import java.util.concurrent.TimeUnit +import kotlin.system.measureTimeMillis + +class NetworkEgressVerifierTest { + + private lateinit var server1: MockWebServer + private lateinit var server2: MockWebServer + private lateinit var server3: MockWebServer + private lateinit var okHttpClient: OkHttpClient + private lateinit var verifier: NetworkEgressVerifier + + @Before + fun setUp() { + server1 = MockWebServer() + server2 = MockWebServer() + server3 = MockWebServer() + + server1.start() + server2.start() + server3.start() + + okHttpClient = OkHttpClient.Builder() + .connectTimeout(2, TimeUnit.SECONDS) + .readTimeout(2, TimeUnit.SECONDS) + .build() + + verifier = NetworkEgressVerifier(okHttpClient) + } + + @After + fun tearDown() { + server1.shutdown() + server2.shutdown() + server3.shutdown() + } + + @Test + fun benchmarkSequentialVsConcurrentIpify() = runBlocking { + // Server 1 delays 300ms and fails (500) + server1.enqueue(MockResponse().setResponseCode(500).setBodyDelay(300, TimeUnit.MILLISECONDS)) + // Server 2 delays 300ms and fails (500) + server2.enqueue(MockResponse().setResponseCode(500).setBodyDelay(300, TimeUnit.MILLISECONDS)) + // Server 3 delays 100ms and succeeds (200 OK) + server3.enqueue(MockResponse().setResponseCode(200).setBody("203.0.113.195").setBodyDelay(100, TimeUnit.MILLISECONDS)) + + val endpoints = listOf( + server1.url("/").toString(), + server2.url("/").toString(), + server3.url("/").toString() + ) + + // Measure sequential execution + val sequentialTime = measureTimeMillis { + var result: String? = null + for (url in endpoints) { + try { + val request = Request.Builder().url(url).build() + okHttpClient.newCall(request).execute().use { resp -> + if (resp.isSuccessful) { + val ip = resp.body?.string()?.trim() + if (!ip.isNullOrBlank()) { + result = ip + break + } + } + } + } catch (_: Exception) {} + } + assertEquals("203.0.113.195", result) + } + + // Setup mock responses again for concurrent test + server1.enqueue(MockResponse().setResponseCode(500).setBodyDelay(300, TimeUnit.MILLISECONDS)) + server2.enqueue(MockResponse().setResponseCode(500).setBodyDelay(300, TimeUnit.MILLISECONDS)) + server3.enqueue(MockResponse().setResponseCode(200).setBody("203.0.113.195").setBodyDelay(100, TimeUnit.MILLISECONDS)) + + // Measure concurrent execution using NetworkEgressVerifier + val concurrentTime = measureTimeMillis { + val result = verifier.tryIpify(endpoints) + assertEquals("203.0.113.195", result) + } + + println("Sequential fallback IP check time: $sequentialTime ms") + println("Concurrent fallback IP check time: $concurrentTime ms") + println("Latency improvement: ${sequentialTime - concurrentTime} ms") + } + + @Test + fun testTryCloudflareTraceConcurrent() = runBlocking { + val traceBody = """ + fl=12f34 + h=1.1.1.1 + ip=198.51.100.42 + ts=1700000000 + visit_scheme=https + uag=AWGMutator-EgressProbe/1.0 + colo=HEL + sliver=none + loc=FI + warp=plus + gateway=off + r2=off + kex=X25519 + """.trimIndent() + + server1.enqueue(MockResponse().setResponseCode(500).setBodyDelay(200, TimeUnit.MILLISECONDS)) + server2.enqueue(MockResponse().setResponseCode(200).setBody(traceBody).setBodyDelay(50, TimeUnit.MILLISECONDS)) + + val endpoints = listOf( + server1.url("/trace").toString(), + server2.url("/trace").toString() + ) + + val result = verifier.tryCloudflareTrace(endpoints) + assertNotNull(result) + assertEquals("198.51.100.42", result?.publicIp) + assertEquals("FI", result?.countryCode) + assertEquals(true, result?.isWarpActive) + } +}