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")))
}
@@ -3,6 +3,7 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'network_telemetry.dart';
import 'ui_lifecycle.dart';
class LiveDetailPage extends StatefulWidget {
final String title;
@@ -12,11 +13,25 @@ class LiveDetailPage extends StatefulWidget {
State<LiveDetailPage> createState() => _LiveDetailPageState();
}
class _LiveDetailPageState extends State<LiveDetailPage> {
class _LiveDetailPageState extends State<LiveDetailPage>
with WidgetsBindingObserver {
Timer? timer;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
updateTimer(WidgetsBinding.instance.lifecycleState);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (usesMobileLifecycle) updateTimer(state);
}
void updateTimer(AppLifecycleState? state) {
timer?.cancel();
timer = null;
if (!shouldRefreshUi(state)) return;
timer = Timer.periodic(const Duration(seconds: 2), (_) {
if (mounted) setState(() {});
});
@@ -24,6 +39,7 @@ class _LiveDetailPageState extends State<LiveDetailPage> {
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
timer?.cancel();
super.dispose();
}
+51 -16
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart' show defaultTargetPlatform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
@@ -12,6 +13,7 @@ import 'configuration_pages.dart';
import 'detail_pages.dart';
import 'runtime_diagnostics.dart';
import 'proxy_speed_test.dart';
import 'ui_lifecycle.dart';
class LabScreen extends StatefulWidget {
const LabScreen({super.key, this.initializeNative = true});
@@ -20,7 +22,7 @@ class LabScreen extends StatefulWidget {
State<LabScreen> createState() => _LabScreenState();
}
class _LabScreenState extends State<LabScreen> {
class _LabScreenState extends State<LabScreen> with WidgetsBindingObserver {
MeshPortClient? client, applicationClient, systemClient;
MacSystemVpnSession? macVpnSession;
bool legacyMigrationPending = false;
@@ -48,6 +50,11 @@ class _LabScreenState extends State<LabScreen> {
String? loadedConfig, loadedForm;
static const vpnChannel = MethodChannel('meshport/system_vpn');
Timer? timer, subscriptionTimer;
bool initialized = false;
bool get uiActive => shouldRefreshUi(WidgetsBinding.instance.lifecycleState);
bool get detailedDiagnostics =>
!(Platform.isAndroid || Platform.isIOS) ||
const bool.fromEnvironment('MESHPORT_DETAILED_DIAGNOSTICS');
bool subscriptionUpdating = false;
String? savedProxyJson;
final subscriptionRetry = <String, DateTime>{};
@@ -98,6 +105,7 @@ class _LabScreenState extends State<LabScreen> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
if (widget.initializeNative) {
unawaited(initialize());
}
@@ -105,7 +113,7 @@ class _LabScreenState extends State<LabScreen> {
Future<void> initialize() async {
try {
log('客户端启动 · ${Platform.operatingSystem} · 代理诊断日志已开启');
log('客户端启动 · ${Platform.operatingSystem}');
// A --dart-define wins; the process environment serves `flutter test`
// and development runs. Release builds use the bundled library.
const defined = String.fromEnvironment('MESHPORT_LIBRARY');
@@ -193,8 +201,12 @@ class _LabScreenState extends State<LabScreen> {
proxyProfile.entry = runtimeMode;
}
singBoxEnabled = proxyProfile.proxyEnabled;
final diagnostics = await opened.enableDiagnostics();
log(diagnostics['enabled'] == true ? '穿透详细日志采集已开启' : '穿透日志未接管:宿主已有日志订阅器');
if (detailedDiagnostics) {
final diagnostics = await opened.enableDiagnostics();
log(
diagnostics['enabled'] == true ? '穿透详细日志采集已开启' : '穿透日志未接管:宿主已有日志订阅器',
);
}
if (profileSupported) await checkLocalProfileMigration();
if (Platform.isAndroid) {
final snapshot = await androidVpnRequest({'op': 'status'});
@@ -214,10 +226,6 @@ class _LabScreenState extends State<LabScreen> {
await refresh();
}
}
subscriptionTimer = Timer.periodic(
const Duration(minutes: 1),
(_) => unawaited(updateDueSubscriptions()),
);
if (Platform.isMacOS || Platform.isAndroid) {
try {
final preferences = await vpnChannel.invokeMapMethod<String, dynamic>(
@@ -244,12 +252,9 @@ class _LabScreenState extends State<LabScreen> {
log('自动连接未完成,请手动连接并检查授权');
}
}
unawaited(updateDueSubscriptions());
timer = Timer.periodic(const Duration(seconds: 2), (_) {
if (!busy) {
unawaited(refresh());
}
});
if (!mounted) return;
initialized = true;
updateUiTimers();
} catch (e) {
if (mounted) {
setState(() => error = '原生库未加载,请先构建并指定 MESHPORT_LIBRARY。$e');
@@ -257,6 +262,34 @@ class _LabScreenState extends State<LabScreen> {
}
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (defaultTargetPlatform == TargetPlatform.iOS &&
(state == AppLifecycleState.hidden ||
state == AppLifecycleState.paused ||
state == AppLifecycleState.detached)) {
cancel = true;
if (speedTesting) proxySpeedTest.cancel();
}
if (usesMobileLifecycle && initialized) updateUiTimers();
}
void updateUiTimers() {
timer?.cancel();
subscriptionTimer?.cancel();
timer = subscriptionTimer = null;
if (!uiActive) return;
if (!busy) unawaited(refresh());
unawaited(updateDueSubscriptions());
timer = Timer.periodic(const Duration(seconds: 2), (_) {
if (!busy) unawaited(refresh());
});
subscriptionTimer = Timer.periodic(
const Duration(minutes: 1),
(_) => unawaited(updateDueSubscriptions()),
);
}
Future<Map<String, dynamic>> androidVpnRequest(
Map<String, dynamic> request,
) async {
@@ -309,7 +342,7 @@ class _LabScreenState extends State<LabScreen> {
}
Future<void> refresh() async {
if (refreshing) return;
if (refreshing || !uiActive) return;
refreshing = true;
try {
final next = client == applicationClient && proxySession != null
@@ -624,7 +657,7 @@ class _LabScreenState extends State<LabScreen> {
),
)).acquire();
try {
await opened.enableDiagnostics();
if (detailedDiagnostics) await opened.enableDiagnostics();
if (unified) {
await diagnosticStage(
'启动统一 VPN 代理',
@@ -859,6 +892,7 @@ class _LabScreenState extends State<LabScreen> {
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
cancel = true;
proxySpeedTest.cancel();
timer?.cancel();
@@ -1496,6 +1530,7 @@ class _LabScreenState extends State<LabScreen> {
);
Future<void> updateDueSubscriptions() async {
if (!mounted ||
!uiActive ||
busy ||
subscriptionUpdating ||
proxySavesPending > 0 ||
@@ -0,0 +1,9 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
bool get usesMobileLifecycle =>
defaultTargetPlatform == TargetPlatform.android ||
defaultTargetPlatform == TargetPlatform.iOS;
bool shouldRefreshUi(AppLifecycleState? state) =>
!usesMobileLifecycle || state == null || state == AppLifecycleState.resumed;
@@ -0,0 +1,33 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/detail_pages.dart';
void main() {
testWidgets(
'iOS detail polling pauses when hidden and resumes on return',
(tester) async {
final binding = tester.binding;
binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
var builds = 0;
await tester.pumpWidget(
MaterialApp(
home: LiveDetailPage(title: '详情', builder: () => Text('${++builds}')),
),
);
final initial = builds;
await tester.pump(const Duration(seconds: 2));
expect(builds, initial + 1);
binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden);
final beforeHidden = builds;
await tester.pump(const Duration(seconds: 10));
expect(builds, beforeHidden);
binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pump(const Duration(seconds: 2));
expect(builds, beforeHidden + 1);
await tester.pumpWidget(const SizedBox.shrink());
},
variant: const TargetPlatformVariant({TargetPlatform.iOS}),
);
}
+4
View File
@@ -478,6 +478,10 @@ impl Engine {
route_task: Mutex::new(Some(route_task)),
})
}
pub fn is_running(&self) -> bool {
self.instance.state() == easytier_core::instance::CoreInstanceState::Running
}
/// Notifies on every change of the destinations to route through the mesh.
pub fn watch_mesh_routes(&self) -> tokio::sync::watch::Receiver<MeshRoutes> {
self.routes.subscribe()
+27 -1
View File
@@ -17,7 +17,7 @@ use tokio::runtime::Runtime;
static NEXT: AtomicU64 = AtomicU64::new(1);
/// Additive JSON operation set within ABI v1. Bump when hosts must rely on a
/// newly added operation or field; hosts reject libraries below what they need.
const CAPABILITY_REVISION: u32 = 2;
const CAPABILITY_REVISION: u32 = 3;
const OPERATIONS: &[&str] = &[
"abi_info",
"build_config",
@@ -27,6 +27,7 @@ const OPERATIONS: &[&str] = &[
"start_bridged",
"stop",
"status",
"health",
"wait_routes",
"socks_start",
"socks_stop",
@@ -374,6 +375,23 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
None => json!({"running": false, "active_sessions": 0}),
})
}
"health" => {
let engine_running = network.as_ref().is_some_and(|n| n.is_running());
let bridge_running = context
.socks
.lock()
.unwrap()
.as_ref()
.is_some_and(|bridge| bridge.snapshot().running);
let routes = network
.as_ref()
.map(|n| n.watch_mesh_routes().borrow().clone());
Ok(json!({
"engine_running": engine_running,
"mesh_routable": engine_running && bridge_running,
"routes": routes,
}))
}
"status" => match network.as_ref() {
Some(n) => {
let mut snapshot = context.runtime.block_on(n.snapshot());
@@ -769,6 +787,9 @@ mod tests {
call(id, r#"{"op":"status"}"#)["data"]["health"]["mesh_routable"],
false
);
let health = call(id, r#"{"op":"health"}"#);
assert_eq!(health["data"]["engine_running"], false);
assert_eq!(health["data"]["routes"], Value::Null);
// Freeing without stop also stops the network and wakes a waiter.
let started = call(
id,
@@ -776,6 +797,11 @@ mod tests {
);
assert_eq!(started["ok"], true, "{started}");
let generation = started["data"]["route_generation"].as_u64().unwrap();
let health = call(id, r#"{"op":"health"}"#);
assert_eq!(health["data"]["engine_running"], true);
assert_eq!(health["data"]["mesh_routable"], true);
assert_eq!(health["data"]["routes"]["generation"], generation);
assert!(health["data"].get("diagnostic_traces").is_none());
let waiter = std::thread::spawn(move || {
let at = std::time::Instant::now();
let reply = call(
+5
View File
@@ -30,6 +30,11 @@ impl Network {
pub async fn stop(&self) {
self.engine.stop().await;
}
/// Reports engine lifecycle without collecting telemetry.
pub fn is_running(&self) -> bool {
self.engine.is_running()
}
/// Destinations to route through this network; changes as advertisements
/// are accepted or withdrawn. Use instead of polling `snapshot`.
pub fn watch_mesh_routes(&self) -> tokio::sync::watch::Receiver<MeshRoutes> {
+1 -1
View File
@@ -16,7 +16,7 @@
- `start` 同样接受 `check_local_overlap`。系统模式启动时 SDK 总是执行该检查,宿主不再自行预检。
- `build_config`(profile)由结构化表单草稿生成 SDK 接受的 TOML,返回 `toml`。`runtime_mode` 不是 `system_vpn`(包括宿主的 `unified_vpn`)时生成应用模式;`no_tun`/`use_smoltcp`、`enable_encryption=true`、`latency_first` 由 SDK 决定,宿主不再拼接 TOML。结果已通过 validate 同等校验。
- `migrate_config`(toml)移除旧版保存过、当前不接受的字段(顶层或 runtime 中的 `subnet_routes`),返回 `toml` 与 `changed`;无需迁移时原样返回。
- `abi_info` 返回 `{abi, revision, operations}`。`abi` 仍为 1;`revision` 是同一 ABI 内的能力修订号(当前 2:带 `build_config`/`migrate_config`/`start_bridged`/`wait_routes`/`health` 等),`operations` 列出支持的操作。宿主打开库后先调用它,修订号不足时给出明确错误,而不是在某个操作上才失败。旧库没有该操作,同样视为不满足。
- `abi_info` 返回 `{abi, revision, operations}`。`abi` 仍为 1;`revision` 是同一 ABI 内的能力修订号(当前 3:新增独立的 `health` 查询,返回引擎与组网桥接是否可用以及路由快照,不采集流量统计或诊断日志),`operations` 列出支持的操作。宿主打开库后先调用它,修订号不足时给出明确错误,而不是在某个操作上才失败。旧库没有该操作,同样视为不满足。
- `start_bridged`(toml,可选 port、max_sessions、check_local_overlap、require_static_overlay)一步完成:校验应用模式、静态地址须可路由、可选要求静态地址与本机冲突检查,再启动网络与 SOCKS 桥接;任一步失败两者都不保留。返回 `engine_started`、`listen`、`overlay`、`mesh_cidrs`、`route_generation`。
`status` 的 `platform_network` 增加 `mesh_cidrs`(虚拟网段(可路由时)加已接受公告子网,规范化、排序,/32 也带后缀)、`route_generation`(`mesh_cidrs` 每次变化递增,宿主只需比较这个数)与 `overlay`。`subnet_routes` 保留,表示已接受公告子网本身。`health` 为 `{engine_running, bridge_running, mesh_routable}`,`mesh_routable` 表示宿主此刻可把 `mesh_cidrs` 流量交给桥接;停止时全部为 false。宿主不再自行计算前缀或判断组网是否可用。
+22 -8
View File
@@ -89,14 +89,24 @@ type Engine struct {
func (e *Engine) Snapshot() Snapshot {
e.mu.Lock()
defer e.mu.Unlock()
state := e.state
if state == "" {
state = "Stopped"
return Snapshot{State: e.stateLocked(), Version: "1.14.3", RuntimeEvents: e.runtimeLogs.snapshot()}
}
func (e *Engine) State() string {
e.mu.Lock()
defer e.mu.Unlock()
return e.stateLocked()
}
func (e *Engine) stateLocked() string {
switch {
case e.state == "":
return "Stopped"
case e.state == "Running" && e.ctx.Err() != nil:
return "Failed"
default:
return e.state
}
if state == "Running" && e.ctx.Err() != nil {
state = "Failed"
}
return Snapshot{State: state, Version: "1.14.3", RuntimeEvents: e.runtimeLogs.snapshot()}
}
func (e *Engine) Start(parent context.Context, config Config) error {
@@ -155,7 +165,11 @@ func (e *Engine) Start(parent context.Context, config Config) error {
// Collect bounded, credential-redacted warning/error events in memory.
// Raw upstream logs must never go to stderr or a user's log file.
if !e.selfTestTrace {
options.Log = &option.LogOptions{Level: "info", Output: os.DevNull}
level := "info"
if runtime.GOOS == "android" {
level = "warn"
}
options.Log = &option.LogOptions{Level: level, Output: os.DevNull}
}
instance, err := box.New(box.Options{Options: options, Context: ctx})
if err != nil {
@@ -91,6 +91,8 @@ func dispatch(id uint64, data []byte) (any, error) {
if err := slot.engine.Stop(); err != nil {
return nil, err
}
case "health":
return map[string]string{"state": slot.engine.State()}, nil
case "status":
default:
return nil, errors.New("unknown engine operation")
@@ -27,6 +27,13 @@ func TestABIRequestLifecycle(t *testing.T) {
if _, err := dispatch(id, input); err != nil {
t.Fatal(err)
}
health, err := dispatch(id, []byte(`{"op":"health"}`))
if err != nil {
t.Fatal(err)
}
if state, ok := health.(map[string]string); !ok || len(state) != 1 || state["state"] != "Running" {
t.Fatalf("unexpected health payload: %#v", health)
}
if _, err := dispatch(id, input); err == nil {
t.Fatal("duplicate start accepted")
}