Files
shenleiandClaude Opus 5.5 dc1bfc99d2 Move mesh networking logic into the SDK and fix lifecycle bugs
SDK:
- Add build_config/migrate_config, mesh_cidrs, route_generation, health
  and start_bridged; expose abi_info (capability revision 2).
- Add wait_routes long-poll; stop wakes waiters, and context_free now
  stops the network immediately instead of waiting for waiters to time out.

Hosts:
- Dart: waitRoutes(), MeshProxySession route watcher, ABI capability check.
- Android: fix a deadlock where every VPN request waited on its own
  single-thread worker; requests are now async, status is served from a
  snapshot, and combined mode reports Partial when the mesh stops.
- macOS helper: mesh-only unified mode stops when the mesh is lost;
  installed_subnet_routes excludes the overlay.
- Lab: restore Partial sessions, write migrated profiles back, remove the
  unreachable TOML import dialog; native test now connects via the form.

Docs updated accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:17:42 +09:00

388 lines
12 KiB
Dart

import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:singbox_flutter/singbox_flutter.dart';
class FakeProxy implements ProxyEngine {
final List<String> events;
String state = 'Stopped';
bool failStart = false;
Map<String, dynamic>? lastProfile;
FakeProxy(this.events);
@override
Future<Map<String, dynamic>> start({
required int port,
required String meshSocks,
required List<String> prefixes,
Map<String, dynamic>? profile,
}) async {
lastProfile = profile;
events.add('proxy.start:${prefixes.join(',')}');
if (failStart) throw StateError('occupied port');
state = 'Running';
return {'state': state};
}
@override
Future<Map<String, dynamic>> status() async => {'state': state};
@override
Future<void> stop() async {
events.add('proxy.stop');
state = 'Stopped';
}
@override
Future<void> close() async {
events.add('proxy.close');
}
}
class Fixture {
final events = <String>[];
late final proxy = FakeProxy(events);
late final mesh = MeshPortClient.fromTransport(
request: request,
close: () async {},
);
late final session = MeshProxySession(mesh: mesh, proxy: proxy);
String state = 'Stopped', mode = 'application';
bool bridge = false;
// SDK projection: canonical overlay network plus accepted subnets.
String? overlay = '10.77.0.0/24';
List<String> routes = ['192.168.21.0/24'];
List<String> get cidrs => {?overlay, ...routes}.toList()..sort();
int generation = 1;
var _routesChanged = Completer<void>();
void _wake() {
_routesChanged.complete();
_routesChanged = Completer<void>();
}
/// Publishes a route change the way the SDK watch does.
void announceRoutes(List<String> next) {
routes = next;
generation++;
_wake();
}
Future<Map<String, dynamic>> request(Map<String, dynamic> input) async {
final op = input['op'] as String;
if (op == 'wait_routes') {
// Long poll: not logged so lifecycle event assertions stay exact.
if (state == 'Running' && input['after_generation'] == generation) {
await _routesChanged.future;
}
final running = state == 'Running';
return {
'ok': true,
'data': {
'running': running,
'changed': !running || input['after_generation'] != generation,
'route_generation': running ? generation : null,
'mesh_cidrs': running ? cidrs : [],
},
};
}
events.add('mesh.$op');
if (op == 'start_bridged') {
if (mode != 'application') {
return {'ok': false, 'error': 'bridged routing requires application'};
}
if (state != 'Stopped') return {'ok': false, 'error': 'already started'};
}
final data = switch (op) {
'start_bridged' => (() {
state = 'Running';
bridge = true;
return <String, dynamic>{
'listen': '127.0.0.1:50001',
'route_generation': generation,
};
})(),
'stop' => (() {
state = 'Stopped';
_wake();
return <String, dynamic>{};
})(),
'socks_stop' => (() {
bridge = false;
return <String, dynamic>{};
})(),
'status' => {
'state': state,
'platform_network': {'mesh_cidrs': state == 'Running' ? cidrs : []},
'health': {
'engine_running': state == 'Running',
'bridge_running': state == 'Running' && bridge,
'mesh_routable': state == 'Running' && bridge,
},
},
_ => <String, dynamic>{},
};
return {'ok': true, 'data': data};
}
}
void main() {
test(
'joint lifecycle, canonical routes, update and ordered cleanup',
() async {
final f = Fixture();
await f.session.start('test');
expect(f.session.state, 'Running');
expect(f.session.endpoint, '127.0.0.1:10818');
final starts = f.events.where((e) => e.startsWith('proxy.start')).length;
await f.session.refresh();
expect(f.events.where((e) => e.startsWith('proxy.start')).length, starts);
f.routes = ['192.168.22.0/24'];
await f.session.refresh();
expect(f.events.last, 'proxy.start:10.77.0.0/24,192.168.22.0/24');
expect(f.proxy.lastProfile?['protected_cidrs'], [
'10.77.0.0/24',
'192.168.21.0/24',
'192.168.22.0/24',
]);
f.events.clear();
await f.session.stop();
expect(f.events, ['proxy.stop', 'mesh.socks_stop', 'mesh.stop']);
await f.session.start('test');
await f.session.close();
expect(f.events.last, 'proxy.close');
await expectLater(f.session.start('test'), throwsStateError);
},
);
test('route changes are applied from the SDK watch without a poll', () async {
final f = Fixture();
await f.session.start('test');
expect(f.events.last, 'proxy.start:10.77.0.0/24,192.168.21.0/24');
f.announceRoutes(['192.168.23.0/24']);
for (var i = 0; i < 50 && !f.events.last.contains('192.168.23.0'); i++) {
await Future<void>.delayed(const Duration(milliseconds: 10));
}
expect(f.events.last, 'proxy.start:10.77.0.0/24,192.168.23.0/24');
expect(f.session.state, 'Running');
f.events.clear();
await f.session.stop();
expect(f.events, ['proxy.stop', 'mesh.socks_stop', 'mesh.stop']);
await f.session.close();
});
test('failed engine startup rolls back and permits retry', () async {
final f = Fixture();
f.proxy.failStart = true;
await expectLater(f.session.start('test'), throwsStateError);
expect(f.session.state, 'Failed');
expect(f.state, 'Stopped');
expect(f.events.sublist(f.events.length - 3), [
'proxy.stop',
'mesh.socks_stop',
'mesh.stop',
]);
f.proxy.failStart = false;
await f.session.start('test');
await f.session.close();
});
test(
'queue prevents concurrent duplicate starts; system mode is refused',
() async {
final f = Fixture();
final first = f.session.start('test');
final duplicate = f.session.start('test');
await expectLater(duplicate, throwsStateError);
await first;
expect(f.events.where((e) => e == 'mesh.start_bridged').length, 1);
await f.session.stop();
f.mode = 'system_vpn';
await expectLater(f.session.start('test'), throwsStateError);
await f.session.close();
},
);
test(
'wait for DHCP then start; unexpected engine failure cleans mesh',
() async {
final f = Fixture();
f.overlay = null;
f.routes = [];
await f.session.start('test');
expect(f.session.state, 'AwaitingAddress');
f.overlay = '10.77.0.0/24';
await f.session.refresh();
expect(f.session.state, 'Running');
f.proxy.state = 'Failed';
await expectLater(f.session.refresh(), throwsStateError);
expect(f.session.state, 'Failed');
expect(f.state, 'Stopped');
await f.session.close();
},
);
test('mesh prefixes are read from the SDK projection only', () {
expect(
meshPrefixes({
'ipv4': '10.77.0.11/24',
'platform_network': {
'subnet_routes': ['0.0.0.0/0'],
'mesh_cidrs': ['10.77.0.0/24', '192.168.21.0/24'],
},
}),
['10.77.0.0/24', '192.168.21.0/24'],
);
expect(meshPrefixes({'ipv4': '10.77.0.11/24'}), isEmpty);
expect(
() => meshPrefixes({
'platform_network': {
'mesh_cidrs': [7],
},
}),
throwsStateError,
);
});
test('a busy context is refused without stopping its network', () async {
final f = Fixture();
f.state = 'Running';
await expectLater(f.session.start('test'), throwsStateError);
expect(f.events.where((e) => e == 'mesh.stop'), isEmpty);
expect(f.state, 'Running');
await f.session.close();
});
test(
'mesh-only session fails when the SDK reports the bridge down',
() async {
final f = Fixture();
await f.session.start('test');
f.bridge = false;
await expectLater(
f.session.refresh(),
throwsA(
isA<StateError>().having(
(e) => e.message,
'message',
'Mesh bridge stopped unexpectedly',
),
),
);
expect(f.session.state, 'Failed');
expect(f.state, 'Stopped');
await f.session.close();
},
);
test(
'proxy-only session does not start mesh or require network credentials',
() async {
final f = Fixture();
final session = MeshProxySession(
mesh: f.mesh,
proxy: f.proxy,
profile: {'feature': 'proxy', 'mode': 'direct'},
);
await session.start('invalid mesh config');
expect(session.state, 'Running');
expect(
f.events.where(
(e) => e.startsWith('mesh.start') || e == 'mesh.validate',
),
isEmpty,
);
expect(f.proxy.lastProfile?['feature'], 'proxy');
await session.close();
},
);
test(
'combined keeps proxy available and protects mesh when native network stops',
() async {
final f = Fixture();
final session = MeshProxySession(
mesh: f.mesh,
proxy: f.proxy,
profile: {'feature': 'combined', 'mode': 'global'},
);
await session.start('test');
f.state = 'Stopped';
await session.refresh();
expect(session.state, 'Partial');
expect(session.endpoint, isNotNull);
expect(f.proxy.lastProfile?['protected_cidrs'], [
'10.77.0.0/24',
'192.168.21.0/24',
]);
await session.close();
},
);
final path = Platform.environment['MESHPORT_PROXY_LIBRARY'];
test(
'native Go ABI loads from Dart, releases listeners and closes context',
() async {
final listener = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = listener.port;
await listener.close();
final engine = await NativeProxyEngine.open(libraryPath: path);
expect((await engine.status())['state'], 'Stopped');
await engine.start(
port: port,
meshSocks: '127.0.0.1:9',
prefixes: ['10.77.0.0/24'],
);
expect((await engine.status())['state'], 'Running');
final socket = await Socket.connect('127.0.0.1', port);
await engine.close();
expect(
await socket
.fold<int>(0, (count, bytes) => count + bytes.length)
.timeout(const Duration(seconds: 2)),
0,
);
socket.destroy();
final reused = await ServerSocket.bind(
InternetAddress.loopbackIPv4,
port,
);
await reused.close();
await expectLater(engine.status(), throwsStateError);
},
skip: path == null
? 'Set MESHPORT_PROXY_LIBRARY after building native library'
: false,
);
final meshPath = Platform.environment['MESHPORT_LIBRARY'];
test(
'Rust and Go coexist in one Dart process with joint native cleanup',
() async {
final mesh = await MeshPortClient.open(libraryPath: meshPath);
final engine = await NativeProxyEngine.open(libraryPath: path);
final reserve = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = reserve.port;
await reserve.close();
final session = MeshProxySession(mesh: mesh, proxy: engine, port: port);
try {
await session.start(
"ipv4 = '10.253.82.11/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = []\n[network_identity]\nnetwork_name = 'native-lifecycle-test'\nnetwork_secret = 'test-only'\n[flags]\nno_tun = true\nuse_smoltcp = true\n",
);
expect(session.state, 'Running');
expect((await mesh.socksBridgeStatus())['running'], true);
final socket = await Socket.connect('127.0.0.1', port);
await session.stop();
expect(
await socket
.fold<int>(0, (n, b) => n + b.length)
.timeout(const Duration(seconds: 2)),
0,
);
socket.destroy();
expect((await mesh.status())['state'], 'Stopped');
expect((await mesh.socksBridgeStatus())['running'], false);
final reuse = await ServerSocket.bind(
InternetAddress.loopbackIPv4,
port,
);
await reuse.close();
} finally {
await session.close();
await mesh.close();
}
},
skip: path == null || meshPath == null
? 'Set both native library paths'
: false,
);
}