Reduce Android and iOS background work

This commit is contained in:
shen
2026-12-03 16:46:29 -08:00
parent 9e05f1ad93
commit e68cb6c909
12 changed files with 189 additions and 60 deletions
@@ -19,12 +19,10 @@ import java.util.concurrent.TimeUnit
// All service state is confined to `worker`: requests from the activity, the
// health tick, network callbacks and route updates run there one at a time.
// Status reads a snapshot refreshed after every worker task, so a slow TUN
// rebuild never stalls the UI poll.
// Full telemetry is collected only when requested by the UI.
class MeshVpnService : VpnService() {
companion object { @Volatile var current: MeshVpnService? = null; private set }
private val worker = ScheduledThreadPoolExecutor(1)
@Volatile private var statusSnapshot: String? = null
// Invalidates the route watcher thread of a previous session.
@Volatile private var watchSession = 0
private var handle = 0L
@@ -56,18 +54,15 @@ class MeshVpnService : VpnService() {
.setSmallIcon(R.drawable.ic_stat_meshport).setContentIntent(open).setOngoing(true).build())
// Health tick. Route changes normally arrive from the watcher thread;
// the generation check here only covers a watcher that has exited.
worker.scheduleWithFixedDelay({
try { tick() } finally { refreshStatus() }
}, 2, 2, TimeUnit.SECONDS)
worker.scheduleWithFixedDelay({ tick() }, 2, 2, TimeUnit.SECONDS)
}
private fun tick() {
if (running) try {
if (unified) {
check(proxyCall(JSONObject().put("op","status")).getJSONObject("data").getString("state") == "Running")
check(proxyCall(JSONObject().put("op","health")).getJSONObject("data").getString("state") == "Running")
if (!meshEnabled) return
}
val data = native(JSONObject().put("op", "status")).getJSONObject("data")
val health = data.optJSONObject("health") ?: JSONObject()
val health = native(JSONObject().put("op", "health")).getJSONObject("data")
val routable = health.optBoolean(if (unified) "mesh_routable" else "engine_running")
if (!routable) {
// Combined mode keeps the proxy and drops mesh routes;
@@ -79,18 +74,14 @@ class MeshVpnService : VpnService() {
}
return
}
val platform = data.getJSONObject("platform_network")
applyRoutes(handle, platform.getLong("route_generation"), strings(platform.getJSONArray("mesh_cidrs")))
val routes = health.getJSONObject("routes")
applyRoutes(handle, routes.getLong("generation"), strings(routes.getJSONArray("cidrs")))
} catch (_: Exception) { failure = "VPN 路由更新失败,请重新连接"; shutdown() }
}
/** Runs [block] on `worker`, then republishes the status snapshot. */
private fun onWorker(block: () -> Unit) = worker.execute { try { block() } finally { refreshStatus() } }
private fun refreshStatus() {
statusSnapshot = try { dispatch(JSONObject().put("op", "status")).toString() } catch (_: Exception) { null }
}
private fun onWorker(block: () -> Unit) = worker.execute { block() }
/** Runs on `worker`. Ignores stale updates from a previous context. */
private fun applyRoutes(context: Long, generation: Long, cidrs: List<String>) {
if (!running || context != handle || generation == routeGeneration) return
if (!running || context != handle || generation <= routeGeneration) return
if (cidrs != meshCidrs) { if (unified) restartProxy(cidrs) else rebuild(cidrs) }
routeGeneration = generation
}
@@ -102,7 +93,7 @@ class MeshVpnService : VpnService() {
while (session == watchSession) {
val reply = try {
JSONObject(NativeBridge.call(context, JSONObject().put("op", "wait_routes")
.put("after_generation", generation).put("timeout_ms", 10000).toString()))
.put("after_generation", generation).put("timeout_ms", 30000).toString()))
} catch (_: Exception) { return@Thread }
// An error means the context is gone; a stopped network is
// left to the health tick, which knows the session's mode.
@@ -135,23 +126,10 @@ class MeshVpnService : VpnService() {
check(response.optBoolean("ok")) { response.optString("error", "Native request failed") }
return response
}
/**
* Callable from any thread; [reply] runs on `worker`, or immediately for a
* status answered from the snapshot. Never blocks the caller.
*/
/** Queues a request without blocking the caller. [reply] runs on the worker. */
fun request(request: JSONObject, reply: (Result<JSONObject>) -> Unit) {
val snapshot = statusSnapshot
if (request.optString("op") == "status" && snapshot != null) {
reply(Result.success(JSONObject(snapshot))); return
}
try {
// Republish the snapshot before replying, so the caller's next
// status already reflects this operation.
worker.execute {
val result = runCatching { dispatch(request) }
refreshStatus()
reply(result)
}
worker.execute { reply(runCatching { dispatch(request) }) }
} catch (error: java.util.concurrent.RejectedExecutionException) {
reply(Result.failure(IllegalStateException("VPN service is stopping")))
}