Add proxy speed measurement, connection logs and standalone Android packaging

This commit is contained in:
shen
2026-10-13 23:08:57 -07:00
parent f94dab0555
commit 72566b9a8a
22 changed files with 551 additions and 91 deletions
+25 -2
View File
@@ -1,3 +1,5 @@
import java.util.Properties
plugins {
id("com.android.application")
id("kotlin-android")
@@ -5,6 +7,16 @@ plugins {
id("dev.flutter.flutter-gradle-plugin")
}
val standalone = System.getenv("MESHPORT_ANDROID_STANDALONE") == "1"
val standaloneSigning = Properties().apply {
if (standalone) {
val path = requireNotNull(System.getenv("MESHPORT_ANDROID_SIGNING_PROPERTIES")) {
"Use scripts/package-lab-android.sh --standalone to prepare signing"
}
file(path).inputStream().use { load(it) }
}
}
android {
buildFeatures { buildConfig = true }
namespace = "com.example.meshport_lab"
@@ -22,7 +34,8 @@ android {
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "com.example.meshport_lab"
applicationId = if (standalone) "com.meshport.client.standalone" else "com.example.meshport_lab"
manifestPlaceholders["meshportAppLabel"] = if (standalone) "MeshPort 独立版" else "MeshPort"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = 26
@@ -36,13 +49,23 @@ android {
versionName = flutter.versionName
}
signingConfigs {
if (standalone) {
create("standalone") {
storeFile = file(standaloneSigning.getProperty("storeFile"))
storePassword = standaloneSigning.getProperty("storePassword")
keyAlias = standaloneSigning.getProperty("keyAlias")
keyPassword = standaloneSigning.getProperty("keyPassword")
}
}
}
buildTypes {
debug { ndk { abiFilters.clear(); abiFilters += "arm64-v8a" } }
release {
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.getByName("debug")
signingConfig = signingConfigs.getByName(if (standalone) "standalone" else "debug")
}
}
externalNativeBuild { cmake { path = file("src/main/cpp/CMakeLists.txt"); version = "3.22.1" } }
@@ -6,20 +6,20 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
<application
android:allowBackup="false"
android:label="MeshPort"
android:label="${meshportAppLabel}"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<!-- Override ZXing's sensorLandscape default and respect user rotation. -->
<activity android:name="com.journeyapps.barcodescanner.CaptureActivity"
android:screenOrientation="fullUser"
tools:replace="android:screenOrientation" />
<service android:name=".MeshVpnService" android:exported="false"
<service android:name="com.example.meshport_lab.MeshVpnService" android:exported="false"
android:permission="android.permission.BIND_VPN_SERVICE" android:foregroundServiceType="specialUse">
<intent-filter><action android:name="android.net.VpnService" /></intent-filter>
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" android:value="User initiated mesh networking VPN" />
</service>
<activity
android:name=".MainActivity"
android:name="com.example.meshport_lab.MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
@@ -196,23 +196,49 @@ class SubnetListPageBody extends StatelessWidget {
}
}
class LogsPageBody extends StatelessWidget {
class LogsPageBody extends StatefulWidget {
final List<String> logs;
final VoidCallback onClear;
const LogsPageBody({super.key, required this.logs, required this.onClear});
@override
State<LogsPageBody> createState() => _LogsPageBodyState();
}
class _LogsPageBodyState extends State<LogsPageBody> {
bool proxyOnly = false;
List<String> get visibleLogs => proxyOnly
? widget.logs
.where((line) => line.contains('代理') || line.contains('sing-box'))
.toList()
: widget.logs;
@override
Widget build(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'显示本次应用会话最近 300 条事件。macOS 同步写入系统日志,可在 Console 中筛选 MeshPort / Runtime。复制保留节点地址,隐藏认证信息。',
const Text('显示本次会话最近 300 条事件。代理日志包含连接、目标地址、分流出口及引擎错误。复制保留目标地址,隐藏认证信息。'),
const SizedBox(height: 12),
SegmentedButton<bool>(
segments: const [
ButtonSegment(value: false, label: Text('全部日志')),
ButtonSegment(value: true, label: Text('代理日志')),
],
selected: {proxyOnly},
onSelectionChanged: (selection) =>
setState(() => proxyOnly = selection.single),
),
if (visibleLogs.isEmpty)
const Padding(
padding: EdgeInsets.symmetric(vertical: 12),
child: Text('暂无日志'),
),
Wrap(
spacing: 12,
children: [
OutlinedButton(
onPressed: () async {
await Clipboard.setData(ClipboardData(text: logs.join('\n')));
await Clipboard.setData(
ClipboardData(text: visibleLogs.join('\n')),
);
if (context.mounted) {
ScaffoldMessenger.of(
context,
@@ -221,10 +247,10 @@ class LogsPageBody extends StatelessWidget {
},
child: const Text('复制当前范围'),
),
TextButton(onPressed: onClear, child: const Text('清空显示')),
TextButton(onPressed: widget.onClear, child: const Text('清空显示')),
],
),
for (final line in logs)
for (final line in visibleLogs)
Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: SelectableText(
+101 -66
View File
@@ -12,6 +12,7 @@ import 'proxy_panel.dart';
import 'configuration_pages.dart';
import 'detail_pages.dart';
import 'runtime_diagnostics.dart';
import 'proxy_speed_test.dart';
class LabScreen extends StatefulWidget {
const LabScreen({super.key, this.initializeNative = true});
@@ -70,6 +71,12 @@ class _LabScreenState extends State<LabScreen> {
Map<String, dynamic> status = {'state': 'Stopped', 'peer_count': 0};
Map<String, dynamic>? result;
final logs = <String>[];
final proxySpeedTest = ProxySpeedTest();
bool speedTesting = false;
ProxySpeedResult? speedResult;
String speedError = '';
double speedProgressMbps = 0;
int speedBytes = 0;
final diagnosticRedactor = DiagnosticRedactor();
String lastProxyState = '';
int proxyEventSequence = 0;
@@ -502,6 +509,9 @@ class _LabScreenState extends State<LabScreen> {
}
Future<void> startConfig(String config) async {
proxySpeedTest.cancel();
speedResult = null;
speedError = '';
proxyEventSequence = 0;
if (singBoxEnabled) proxyProfile.validateConnection();
// Validation selects mode from effective flags, avoiding ad-hoc TOML parsing.
@@ -608,9 +618,9 @@ class _LabScreenState extends State<LabScreen> {
if (mounted) {
setState(() {
legacyMigrationPending = info?['migration_pending'] == true;
if (info?['path'] is String) {
if (info?['path'] is String) {
localProfilePath = info!['path'] as String;
}
}
});
}
if (legacyMigrationPending) log('旧配置需要迁移,请在设置中点击“迁移旧配置”');
@@ -664,6 +674,7 @@ class _LabScreenState extends State<LabScreen> {
}
Future<void> stopActive(MeshPortClient c) async {
proxySpeedTest.cancel();
try {
if (c == applicationClient && proxySession != null) {
await proxySession!.stop();
@@ -811,6 +822,7 @@ class _LabScreenState extends State<LabScreen> {
@override
void dispose() {
cancel = true;
proxySpeedTest.cancel();
timer?.cancel();
subscriptionTimer?.cancel();
unawaited(
@@ -906,6 +918,91 @@ class _LabScreenState extends State<LabScreen> {
},
);
Future<void> measureProxySpeed() async {
if (speedTesting || busy || !running) return;
setState(() {
speedTesting = true;
speedResult = null;
speedError = '';
speedBytes = 0;
speedProgressMbps = 0;
});
log('代理测速 · 开始 · $runningProxyMode · $runningProxyLabel');
var lastUpdate = Duration.zero;
try {
final measured = await proxySpeedTest.run(
port: proxySession?.port ?? 10818,
onProgress: (bytes, elapsed) {
if (!mounted ||
elapsed - lastUpdate < const Duration(milliseconds: 250)) {
return;
}
lastUpdate = elapsed;
setState(() {
speedBytes = bytes;
speedProgressMbps =
bytes * 8 / elapsed.inMicroseconds.clamp(1, 1 << 62);
});
},
);
if (!mounted) return;
setState(() {
speedResult = measured;
speedBytes = measured.bytes;
});
log(
'代理测速 · ${measured.mbps.toStringAsFixed(1)} Mbps · '
'${formatBytes(measured.bytes)} · 首字节 ${measured.firstByte.inMilliseconds} ms',
);
} catch (e) {
if (mounted) {
setState(() => speedError = diagnosticRedactor.sanitize('$e'));
log('代理测速 · $e');
}
} finally {
if (mounted) setState(() => speedTesting = false);
}
}
Widget speedPanel() => panel('代理测速', [
Text(
speedTesting
? '${speedProgressMbps.toStringAsFixed(1)} Mbps · 已下载 ${formatBytes(speedBytes)}'
: speedResult == null
? '尚未测速'
: '${speedResult!.mbps.toStringAsFixed(1)} Mbps · '
'${(speedResult!.mbps / 8).toStringAsFixed(2)} MB/s',
),
if (speedResult != null)
Text(
'首字节 ${speedResult!.firstByte.inMilliseconds} ms · '
'下载 ${formatBytes(speedResult!.bytes)}',
),
if (speedTesting) const LinearProgressIndicator(),
if (speedError.isNotEmpty) Text(speedError),
const Text(
'通过当前代理入口下载 Cloudflare 测试资源,遵循当前分流规则。最多 32 MB / 15 秒,会占用带宽;结果不代表视频站点速度。',
),
if (!running) const Text('连接代理后可测速'),
Wrap(
spacing: 12,
children: [
FilledButton.tonalIcon(
onPressed: !running || busy || speedTesting
? null
: measureProxySpeed,
icon: const Icon(Icons.speed),
label: const Text('开始测速'),
),
if (speedTesting)
TextButton(
onPressed: proxySpeedTest.cancel,
child: const Text('取消测速'),
),
],
),
]);
Widget overview() {
if (proxyProfile.feature != 'proxy') return networkOverview();
final selected = proxyProfile.nodes
@@ -956,6 +1053,7 @@ class _LabScreenState extends State<LabScreen> {
],
),
]),
speedPanel(),
if (logs.isNotEmpty)
panel('最近事件', logs.take(3).map((line) => Text(line)).toList()),
],
@@ -1005,15 +1103,7 @@ class _LabScreenState extends State<LabScreen> {
SelectableText('SOCKS5:${proxySession?.endpoint ?? '—'}'),
const Text('TCP / UDP · 自动公告分流。子网变化时重建引擎,已有代理连接需重连。'),
]),
metricGroup([
metric(
'最近测试耗时',
result == null
? '—'
: '${(result!['elapsed_ms'] as num).toStringAsFixed(1)} ms',
),
metric('远端节点', '${status['peer_count'] ?? 0}'),
]),
if (proxyProfile.feature == 'combined') speedPanel(),
panel('网络流量', [
metricGroup([
metric(
@@ -1065,20 +1155,6 @@ class _LabScreenState extends State<LabScreen> {
label: const Text('复制网络诊断'),
),
]),
panel('最近测试趋势', [
const Text('显示连接或回显耗时,并非持续服务器 RTT'),
const SizedBox(height: 12),
SizedBox(height: 140, child: CustomPaint(painter: _Trend(latencies))),
]),
panel('快速测试', [
Text('目标 ${target.text}'),
const SizedBox(height: 12),
FilledButton.icon(
onPressed: () => openDetail('网络诊断', tests),
icon: const Icon(Icons.play_arrow),
label: const Text('打开连接测试'),
),
]),
panel(
'最近事件',
logs
@@ -1689,44 +1765,3 @@ class _LabScreenState extends State<LabScreen> {
);
}
}
class _Trend extends CustomPainter {
final List<double> samples;
_Trend(this.samples);
@override
void paint(Canvas canvas, Size size) {
final grid = Paint()
..color = const Color(0xffe9e6e0)
..strokeWidth = 1;
for (var i = 0; i < 5; i++) {
final y = size.height * i / 4;
canvas.drawLine(Offset(0, y), Offset(size.width, y), grid);
}
if (samples.length < 2) {
return;
}
final max = samples.reduce((a, b) => a > b ? a : b) * 1.2 + 1;
final path = Path();
for (var i = 0; i < samples.length; i++) {
final p = Offset(
size.width * i / (samples.length - 1),
size.height * (1 - samples[i] / max),
);
if (i == 0) {
path.moveTo(p.dx, p.dy);
} else {
path.lineTo(p.dx, p.dy);
}
}
canvas.drawPath(
path,
Paint()
..color = const Color(0xff087d8e)
..style = PaintingStyle.stroke
..strokeWidth = 2,
);
}
@override
bool shouldRepaint(_Trend oldDelegate) => true;
}
@@ -0,0 +1,74 @@
import 'dart:async';
import 'dart:io';
class ProxySpeedResult {
final int bytes;
final Duration elapsed;
final Duration firstByte;
const ProxySpeedResult(this.bytes, this.elapsed, this.firstByte);
double get mbps => bytes * 8 / elapsed.inMicroseconds.clamp(1, 1 << 62);
}
/// Explicit loopback HTTP proxy only: never fall back to a physical connection.
class ProxySpeedTest {
HttpClient? _client;
bool _cancelled = false;
static const maxBytes = 32 * 1024 * 1024;
void cancel() {
_cancelled = true;
_client?.close(force: true);
}
Future<ProxySpeedResult> run({
required int port,
Uri? resource,
Duration limit = const Duration(seconds: 15),
void Function(int bytes, Duration elapsed)? onProgress,
}) async {
if (_client != null) throw StateError('测速正在进行');
if (port < 1 || port > 65535) throw ArgumentError('无效代理端口');
_cancelled = false;
final client = HttpClient()..connectionTimeout = const Duration(seconds: 8);
_client = client;
client.findProxy = (_) => 'PROXY 127.0.0.1:$port';
final clock = Stopwatch()..start();
var bytes = 0;
Duration? firstByte;
var timedOut = false;
final timeout = Timer(limit, () {
timedOut = true;
client.close(force: true);
});
try {
final request = await client.getUrl(
resource ??
Uri.parse('https://speed.cloudflare.com/__down?bytes=$maxBytes'),
);
request.followRedirects = false;
request.headers.set(HttpHeaders.acceptEncodingHeader, 'identity');
final response = await request.close();
if (response.statusCode != HttpStatus.ok) {
throw HttpException('测速资源返回 HTTP ${response.statusCode}');
}
await for (final chunk in response) {
if (_cancelled) throw StateError('测速已取消');
firstByte ??= clock.elapsed;
bytes += chunk.length;
onProgress?.call(bytes, clock.elapsed);
if (bytes >= maxBytes) break;
}
} catch (_) {
if (_cancelled) throw StateError('测速已取消');
if (!timedOut || bytes == 0) rethrow;
} finally {
timeout.cancel();
clock.stop();
client.close(force: true);
_client = null;
}
if (_cancelled) throw StateError('测速已取消');
if (bytes == 0) throw StateError('测速未收到数据');
return ProxySpeedResult(bytes, clock.elapsed, firstByte ?? clock.elapsed);
}
}
@@ -0,0 +1,43 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/detail_pages.dart';
import 'package:meshport_lab/features/lab_screen.dart';
void main() {
testWidgets('overview offers explicit speed measurement after connection', (
tester,
) async {
await tester.pumpWidget(
const MaterialApp(home: LabScreen(initializeNative: false)),
);
expect(find.text('代理测速'), findsOneWidget);
expect(find.text('连接代理后可测速'), findsOneWidget);
expect(
tester
.widget<FilledButton>(find.widgetWithText(FilledButton, '开始测速'))
.onPressed,
isNull,
);
});
testWidgets('proxy log view excludes unrelated mesh events', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: LogsPageBody(
logs: const [
'12:00:00 代理 · outbound connection',
'12:00:01 穿透 · peer connected',
],
onClear: () {},
),
),
),
);
expect(find.text('12:00:01 穿透 · peer connected'), findsOneWidget);
await tester.tap(find.text('代理日志'));
await tester.pump();
expect(find.text('12:00:01 穿透 · peer connected'), findsNothing);
expect(find.text('12:00:00 代理 · outbound connection'), findsOneWidget);
});
}
@@ -0,0 +1,77 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshport_lab/features/proxy_speed_test.dart';
void main() {
test('download uses explicit proxy without resolving the target', () async {
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => proxy.close(force: true));
var calls = 0;
proxy.listen((request) async {
calls++;
expect(request.uri.host, 'speed-test.invalid');
request.response.add(List.filled(65536, 42));
await request.response.close();
});
final result = await ProxySpeedTest().run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/download'),
);
expect(calls, 1);
expect(result.bytes, 65536);
expect(result.mbps, greaterThan(0));
});
test('unavailable proxy never falls back to direct origin', () async {
final origin = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => origin.close(force: true));
var calls = 0;
origin.listen((request) {
calls++;
request.response.close();
});
final reserved = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = reserved.port;
await reserved.close();
await expectLater(
ProxySpeedTest().run(
port: port,
resource: Uri.parse('http://127.0.0.1:${origin.port}/'),
),
throwsA(isA<SocketException>()),
);
expect(calls, 0);
});
test(
'cancellation and error responses do not produce a speed result',
() async {
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => proxy.close(force: true));
proxy.listen((request) async {
if (request.uri.path == '/failure') {
request.response.statusCode = 503;
} else {
request.response.add(List.filled(65536, 42));
}
await request.response.close();
});
final speed = ProxySpeedTest();
await expectLater(
speed.run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/failure'),
),
throwsA(isA<HttpException>()),
);
await expectLater(
speed.run(
port: proxy.port,
resource: Uri.parse('http://speed-test.invalid/download'),
onProgress: (_, _) => speed.cancel(),
),
throwsStateError,
);
},
);
}