test: add automated regression and mesh proxy coexistence suites
This commit is contained in:
@@ -5,6 +5,8 @@
|
|||||||
/outputs/macos/
|
/outputs/macos/
|
||||||
# Runtime captures remain local; commit the validation summaries instead.
|
# Runtime captures remain local; commit the validation summaries instead.
|
||||||
/outputs/validation/*.log
|
/outputs/validation/*.log
|
||||||
|
/outputs/validation/automated-tests/
|
||||||
|
__pycache__/
|
||||||
**/.dart_tool/
|
**/.dart_tool/
|
||||||
**/build/
|
**/build/
|
||||||
!vendor/easytier/easytier/build/
|
!vendor/easytier/easytier/build/
|
||||||
|
|||||||
Generated
+1
@@ -2428,6 +2428,7 @@ dependencies = [
|
|||||||
"easytier",
|
"easytier",
|
||||||
"easytier-core",
|
"easytier-core",
|
||||||
"futures",
|
"futures",
|
||||||
|
"libloading",
|
||||||
"meshport",
|
"meshport",
|
||||||
"meshport-easytier",
|
"meshport-easytier",
|
||||||
"parking_lot",
|
"parking_lot",
|
||||||
|
|||||||
@@ -72,6 +72,19 @@ cargo run -p meshport-test-server -- 10.77.0.2:7007
|
|||||||
|
|
||||||
两种模式均自动学习符合规则的节点公告子网,无需填写远端 CIDR。应用内模式仅供 SDK TCP/UDP 访问;系统模式自动同步 OS 路由。规则及 macOS 启动方式见 [系统组网](docs/system-vpn.md)。
|
两种模式均自动学习符合规则的节点公告子网,无需填写远端 CIDR。应用内模式仅供 SDK TCP/UDP 访问;系统模式自动同步 OS 路由。规则及 macOS 启动方式见 [系统组网](docs/system-vpn.md)。
|
||||||
|
|
||||||
|
## 自动化测试
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/test.py # Rust、Go、Flutter 和 macOS 配置存储回归
|
||||||
|
python3 scripts/test.py sdk engine # 只测 SDK 与引擎联调
|
||||||
|
python3 scripts/test.py client --native # macOS:重新构建原生库后跑 Flutter 原生测试
|
||||||
|
python3 scripts/test.py throughput # 可选:本机模拟延迟与吞吐诊断
|
||||||
|
python3 scripts/test.py speed --min-mbps 10 # 重复测速矩阵、丢包检查及速度门槛
|
||||||
|
python3 scripts/test.py combined # sing-box + SDK 同进程双路负载、UDP 和故障隔离
|
||||||
|
```
|
||||||
|
|
||||||
|
脚本逐项保存日志,输出 JSON 与 JUnit 报告,任一步失败时返回非零状态;默认不运行吞吐诊断或系统 VPN/真机测试。参数、依赖和 CI 使用方式见 [自动化测试](docs/automated-testing.md)。
|
||||||
|
|
||||||
## 清理构建缓存
|
## 清理构建缓存
|
||||||
|
|
||||||
运行 `python3 scripts/clean-build-artifacts.py` 预览,增加 `--delete` 删除可重新生成的构建缓存和临时测试产物。脚本保留工具链、用户配置、Git 历史和 `outputs/android`、`outputs/macos` 安装包;下次构建需要重新生成缓存。
|
运行 `python3 scripts/clean-build-artifacts.py` 预览,增加 `--delete` 删除可重新生成的构建缓存和临时测试产物。脚本保留工具链、用户配置、Git 历史和 `outputs/android`、`outputs/macos` 安装包;下次构建需要重新生成缓存。
|
||||||
|
|||||||
@@ -7,11 +7,26 @@ import 'package:meshport_lab/features/lab_screen.dart';
|
|||||||
void main() {
|
void main() {
|
||||||
const channel = MethodChannel('meshport/system_vpn');
|
const channel = MethodChannel('meshport/system_vpn');
|
||||||
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
// Profile storage: nothing stored, saves accepted.
|
// Isolate native startup from bundled personal profiles and external peers.
|
||||||
|
const localProfile = '''
|
||||||
|
ipv4 = '10.79.0.10/24'
|
||||||
|
listeners = []
|
||||||
|
stun_servers = []
|
||||||
|
stun_servers_v6 = []
|
||||||
|
[network_identity]
|
||||||
|
network_name = 'ui-local-draft'
|
||||||
|
network_secret = 'test-only'
|
||||||
|
[flags]
|
||||||
|
no_tun = true
|
||||||
|
use_smoltcp = true
|
||||||
|
disable_p2p = true
|
||||||
|
[runtime]
|
||||||
|
mode = 'application'
|
||||||
|
''';
|
||||||
setUp(
|
setUp(
|
||||||
() => binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
() => binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||||
channel,
|
channel,
|
||||||
(_) async => null,
|
(call) async => call.method == 'load_profile' ? localProfile : null,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
tearDown(
|
tearDown(
|
||||||
|
|||||||
@@ -1,8 +1,210 @@
|
|||||||
|
import 'dart:async';
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:meshport_lab/features/proxy_speed_test.dart';
|
import 'package:meshport_lab/features/proxy_speed_test.dart';
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
|
test(
|
||||||
|
'speed conversion uses decimal Mbps and preserves first-byte timing',
|
||||||
|
() {
|
||||||
|
const result = ProxySpeedResult(
|
||||||
|
1250000,
|
||||||
|
Duration(seconds: 1),
|
||||||
|
Duration(milliseconds: 20),
|
||||||
|
);
|
||||||
|
expect(result.mbps, 10);
|
||||||
|
expect(result.mbps / 8, 1.25);
|
||||||
|
expect(result.firstByte.inMilliseconds, 20);
|
||||||
|
expect(
|
||||||
|
const ProxySpeedResult(1, Duration.zero, Duration.zero).mbps.isFinite,
|
||||||
|
isTrue,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('invalid proxy ports are rejected before starting a request', () async {
|
||||||
|
for (final port in [0, -1, 65536]) {
|
||||||
|
await expectLater(ProxySpeedTest().run(port: port), throwsArgumentError);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an empty response does not produce a speed result', () async {
|
||||||
|
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
addTearDown(() => proxy.close(force: true));
|
||||||
|
proxy.listen((request) => request.response.close());
|
||||||
|
await expectLater(
|
||||||
|
ProxySpeedTest().run(
|
||||||
|
port: proxy.port,
|
||||||
|
resource: Uri.parse('http://speed-test.invalid/empty'),
|
||||||
|
),
|
||||||
|
throwsStateError,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('redirect responses are not followed', () async {
|
||||||
|
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
addTearDown(() => proxy.close(force: true));
|
||||||
|
var calls = 0;
|
||||||
|
proxy.listen((request) async {
|
||||||
|
calls++;
|
||||||
|
request.response.statusCode = HttpStatus.found;
|
||||||
|
request.response.headers.set(
|
||||||
|
HttpHeaders.locationHeader,
|
||||||
|
'http://speed-test.invalid/other',
|
||||||
|
);
|
||||||
|
await request.response.close();
|
||||||
|
});
|
||||||
|
await expectLater(
|
||||||
|
ProxySpeedTest().run(
|
||||||
|
port: proxy.port,
|
||||||
|
resource: Uri.parse('http://speed-test.invalid/redirect'),
|
||||||
|
),
|
||||||
|
throwsA(isA<HttpException>()),
|
||||||
|
);
|
||||||
|
expect(calls, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'overlapping runs are rejected and a completed tester can be reused',
|
||||||
|
() async {
|
||||||
|
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
final arrived = Completer<void>();
|
||||||
|
final release = Completer<void>();
|
||||||
|
addTearDown(() async {
|
||||||
|
if (!release.isCompleted) release.complete();
|
||||||
|
await proxy.close(force: true);
|
||||||
|
});
|
||||||
|
proxy.listen((request) async {
|
||||||
|
if (!arrived.isCompleted) arrived.complete();
|
||||||
|
await release.future;
|
||||||
|
request.response.add(List.filled(4096, 42));
|
||||||
|
await request.response.close();
|
||||||
|
});
|
||||||
|
final speed = ProxySpeedTest();
|
||||||
|
final resource = Uri.parse('http://speed-test.invalid/reuse');
|
||||||
|
final first = speed.run(port: proxy.port, resource: resource);
|
||||||
|
await arrived.future.timeout(const Duration(seconds: 3));
|
||||||
|
await expectLater(
|
||||||
|
speed.run(port: proxy.port, resource: resource),
|
||||||
|
throwsStateError,
|
||||||
|
);
|
||||||
|
release.complete();
|
||||||
|
expect((await first).bytes, 4096);
|
||||||
|
expect(
|
||||||
|
(await speed.run(port: proxy.port, resource: resource)).bytes,
|
||||||
|
4096,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
'a timed-out partial download reports only the received bytes',
|
||||||
|
() async {
|
||||||
|
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
final release = Completer<void>();
|
||||||
|
addTearDown(() async {
|
||||||
|
if (!release.isCompleted) release.complete();
|
||||||
|
await proxy.close(force: true);
|
||||||
|
});
|
||||||
|
proxy.listen((request) async {
|
||||||
|
try {
|
||||||
|
request.response.add(List.filled(65536, 42));
|
||||||
|
await request.response.flush();
|
||||||
|
await release.future;
|
||||||
|
await request.response.close();
|
||||||
|
} on IOException {
|
||||||
|
// The test intentionally closes the client before the response ends.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
final result = await ProxySpeedTest().run(
|
||||||
|
port: proxy.port,
|
||||||
|
resource: Uri.parse('http://speed-test.invalid/slow'),
|
||||||
|
limit: const Duration(milliseconds: 500),
|
||||||
|
);
|
||||||
|
expect(result.bytes, 65536);
|
||||||
|
expect(result.mbps, greaterThan(0));
|
||||||
|
expect(result.firstByte, lessThanOrEqualTo(result.elapsed));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
'timeout before any data fails and cancellation permits a fresh run',
|
||||||
|
() async {
|
||||||
|
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
final release = Completer<void>();
|
||||||
|
addTearDown(() async {
|
||||||
|
if (!release.isCompleted) release.complete();
|
||||||
|
await proxy.close(force: true);
|
||||||
|
});
|
||||||
|
proxy.listen((request) async {
|
||||||
|
try {
|
||||||
|
if (request.uri.path == '/no-data') await release.future;
|
||||||
|
request.response.add(List.filled(4096, 42));
|
||||||
|
await request.response.close();
|
||||||
|
} on IOException {
|
||||||
|
// The no-data request is intentionally interrupted.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
final speed = ProxySpeedTest();
|
||||||
|
await expectLater(
|
||||||
|
speed.run(
|
||||||
|
port: proxy.port,
|
||||||
|
resource: Uri.parse('http://speed-test.invalid/no-data'),
|
||||||
|
limit: const Duration(milliseconds: 200),
|
||||||
|
),
|
||||||
|
throwsA(anyOf(isA<IOException>(), isA<StateError>())),
|
||||||
|
);
|
||||||
|
await expectLater(
|
||||||
|
speed.run(
|
||||||
|
port: proxy.port,
|
||||||
|
resource: Uri.parse('http://speed-test.invalid/cancel'),
|
||||||
|
onProgress: (_, _) => speed.cancel(),
|
||||||
|
),
|
||||||
|
throwsStateError,
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
(await speed.run(
|
||||||
|
port: proxy.port,
|
||||||
|
resource: Uri.parse('http://speed-test.invalid/fresh'),
|
||||||
|
)).bytes,
|
||||||
|
4096,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test(
|
||||||
|
'large responses stop at the transfer cap instead of reading to EOF',
|
||||||
|
() async {
|
||||||
|
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
|
addTearDown(() => proxy.close(force: true));
|
||||||
|
final chunk = List.filled(1024 * 1024, 42);
|
||||||
|
proxy.listen((request) async {
|
||||||
|
try {
|
||||||
|
for (var i = 0; i < 40; i++) {
|
||||||
|
request.response.add(chunk);
|
||||||
|
await request.response.flush();
|
||||||
|
}
|
||||||
|
await request.response.close();
|
||||||
|
} on IOException {
|
||||||
|
// The cap intentionally closes the response mid-stream.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
final result = await ProxySpeedTest().run(
|
||||||
|
port: proxy.port,
|
||||||
|
resource: Uri.parse('http://speed-test.invalid/large'),
|
||||||
|
);
|
||||||
|
// Network chunks can cross the cap; overshoot is bounded by a received chunk.
|
||||||
|
expect(
|
||||||
|
result.bytes,
|
||||||
|
inInclusiveRange(
|
||||||
|
ProxySpeedTest.maxBytes,
|
||||||
|
ProxySpeedTest.maxBytes + chunk.length,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(result.bytes, lessThan(40 * chunk.length));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('download uses explicit proxy without resolving the target', () async {
|
test('download uses explicit proxy without resolving the target', () async {
|
||||||
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
final proxy = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||||
addTearDown(() => proxy.close(force: true));
|
addTearDown(() => proxy.close(force: true));
|
||||||
|
|||||||
@@ -22,4 +22,5 @@ tokio-util = { version = "0.7", features = ["rt"] }
|
|||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
bytes = "1"
|
bytes = "1"
|
||||||
aes-gcm = "0.10"
|
aes-gcm = "0.10"
|
||||||
|
libloading = "0.8"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,625 @@
|
|||||||
|
//! Real Rust SDK + Go FFI in one process; no TUN, WAN, user profiles or STUN.
|
||||||
|
use anyhow::{Result, ensure};
|
||||||
|
use easytier::instance::factory::create_native_instance;
|
||||||
|
use easytier_core::config::toml::TomlConfig;
|
||||||
|
use meshport::Network;
|
||||||
|
use meshport_socks::{Bridge, Options};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::{
|
||||||
|
ffi::{CStr, CString, c_char},
|
||||||
|
net::{Ipv4Addr, SocketAddrV4},
|
||||||
|
sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicUsize, Ordering},
|
||||||
|
},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use tokio::{
|
||||||
|
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
|
||||||
|
net::{TcpListener, TcpStream, UdpSocket},
|
||||||
|
sync::{Barrier, oneshot},
|
||||||
|
task::{JoinHandle, JoinSet},
|
||||||
|
time::{sleep, timeout},
|
||||||
|
};
|
||||||
|
|
||||||
|
const CHUNK: usize = 64 * 1024;
|
||||||
|
const MESH_TAG: u8 = 0x51;
|
||||||
|
const PROXY_TAG: u8 = 0xa7;
|
||||||
|
const WAIT: Duration = Duration::from_secs(15);
|
||||||
|
|
||||||
|
trait Io: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||||
|
impl<T: AsyncRead + AsyncWrite + Unpin + Send> Io for T {}
|
||||||
|
|
||||||
|
struct NativeProxy {
|
||||||
|
handle: u64,
|
||||||
|
call: unsafe extern "C" fn(u64, *const c_char) -> *mut c_char,
|
||||||
|
free_string: unsafe extern "C" fn(*mut c_char),
|
||||||
|
free: unsafe extern "C" fn(u64),
|
||||||
|
listen: SocketAddrV4,
|
||||||
|
}
|
||||||
|
impl NativeProxy {
|
||||||
|
fn open() -> Result<Self> {
|
||||||
|
let path = std::env::var_os("MESHPORT_PROXY_LIBRARY")
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("MESHPORT_PROXY_LIBRARY required"))?;
|
||||||
|
// Go runtime threads retain executable addresses: never dlclose this
|
||||||
|
// library, including on an error path. Contexts still stop/free normally.
|
||||||
|
let library = std::mem::ManuallyDrop::new(unsafe { libloading::Library::new(path)? });
|
||||||
|
unsafe {
|
||||||
|
let version =
|
||||||
|
*library.get::<unsafe extern "C" fn() -> u32>(b"meshport_proxy_abi_version")?;
|
||||||
|
ensure!(version() == 1, "proxy ABI mismatch");
|
||||||
|
let new =
|
||||||
|
*library.get::<unsafe extern "C" fn() -> u64>(b"meshport_proxy_context_new")?;
|
||||||
|
let handle = new();
|
||||||
|
ensure!(handle != 0, "proxy context creation failed");
|
||||||
|
Ok(Self {
|
||||||
|
handle,
|
||||||
|
call: *library.get(b"meshport_proxy_call")?,
|
||||||
|
free_string: *library.get(b"meshport_proxy_string_free")?,
|
||||||
|
free: *library.get(b"meshport_proxy_context_free")?,
|
||||||
|
listen: "127.0.0.1:0".parse()?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn request(&self, value: Value) -> Result<Value> {
|
||||||
|
let input = CString::new(value.to_string())?;
|
||||||
|
let raw = unsafe { (self.call)(self.handle, input.as_ptr()) };
|
||||||
|
ensure!(!raw.is_null(), "missing proxy response");
|
||||||
|
let parsed = unsafe { serde_json::from_slice::<Value>(CStr::from_ptr(raw).to_bytes()) };
|
||||||
|
unsafe { (self.free_string)(raw) };
|
||||||
|
let parsed = parsed?;
|
||||||
|
ensure!(parsed["ok"] == true, "proxy error: {}", parsed["error"]);
|
||||||
|
Ok(parsed["data"].clone())
|
||||||
|
}
|
||||||
|
fn start(&mut self, feature: &str, bridge: SocketAddrV4, proxy: SocketAddrV4) -> Result<()> {
|
||||||
|
let reserve = std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||||
|
self.listen = reserve.local_addr()?.to_string().parse()?;
|
||||||
|
drop(reserve);
|
||||||
|
let cidrs = if feature == "proxy" {
|
||||||
|
vec![]
|
||||||
|
} else {
|
||||||
|
vec!["10.253.91.0/24", "10.253.93.0/24"]
|
||||||
|
};
|
||||||
|
let config = json!({"feature":feature,"mode":"global","listen_port":self.listen.port(),
|
||||||
|
"mesh_socks":if feature == "proxy" {String::new()} else {bridge.to_string()},"mesh_cidrs":cidrs,
|
||||||
|
"protected_cidrs":cidrs,
|
||||||
|
"proxy":if feature=="mesh" {Value::Null} else {json!({"type":"socks","version":"5","server":"127.0.0.1","server_port":proxy.port()})}});
|
||||||
|
ensure!(
|
||||||
|
self.request(json!({"op":"start","config":config}))?["state"] == "Running",
|
||||||
|
"proxy did not start"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
async fn stop(&self) -> Result<()> {
|
||||||
|
ensure!(
|
||||||
|
self.request(json!({"op":"stop"}))?["state"] == "Stopped",
|
||||||
|
"proxy did not stop"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
TcpStream::connect(self.listen).await.is_err(),
|
||||||
|
"proxy port still listening"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for NativeProxy {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe { (self.free)(self.handle) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn socks(
|
||||||
|
entry: SocketAddrV4,
|
||||||
|
command: u8,
|
||||||
|
target: SocketAddrV4,
|
||||||
|
) -> Result<(TcpStream, SocketAddrV4)> {
|
||||||
|
let mut stream = TcpStream::connect(entry).await?;
|
||||||
|
stream.write_all(&[5, 1, 0]).await?;
|
||||||
|
let mut auth = [0; 2];
|
||||||
|
stream.read_exact(&mut auth).await?;
|
||||||
|
ensure!(auth == [5, 0], "SOCKS auth failed");
|
||||||
|
let mut request = vec![5, command, 0, 1];
|
||||||
|
request.extend(target.ip().octets());
|
||||||
|
request.extend(target.port().to_be_bytes());
|
||||||
|
stream.write_all(&request).await?;
|
||||||
|
let mut reply = [0; 10];
|
||||||
|
stream.read_exact(&mut reply).await?;
|
||||||
|
ensure!(
|
||||||
|
reply[0] == 5 && reply[1] == 0 && reply[3] == 1,
|
||||||
|
"SOCKS request failed: {:?}",
|
||||||
|
reply
|
||||||
|
);
|
||||||
|
Ok((
|
||||||
|
stream,
|
||||||
|
SocketAddrV4::new(
|
||||||
|
Ipv4Addr::new(reply[4], reply[5], reply[6], reply[7]),
|
||||||
|
u16::from_be_bytes([reply[8], reply[9]]),
|
||||||
|
),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn pace(start: Instant, bytes: u64, mbps: u32) {
|
||||||
|
if mbps > 0 {
|
||||||
|
let elapsed = Duration::from_secs_f64(bytes as f64 * 8.0 / (mbps as f64 * 1e6));
|
||||||
|
if let Some(remaining) = elapsed.checked_sub(start.elapsed()) {
|
||||||
|
sleep(remaining).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn serve(mut socket: Box<dyn Io>, tag: u8, limit: u32) -> Result<()> {
|
||||||
|
let direction = socket.read_u8().await?;
|
||||||
|
let ms = socket.read_u64().await?;
|
||||||
|
ensure!((500..=10000).contains(&ms), "invalid duration");
|
||||||
|
let mut payload = vec![tag; CHUNK];
|
||||||
|
let start = Instant::now();
|
||||||
|
let mut total = 0u64;
|
||||||
|
if direction == 1 {
|
||||||
|
while start.elapsed() < Duration::from_millis(ms) {
|
||||||
|
socket.write_u32(CHUNK as u32).await?;
|
||||||
|
socket.write_all(&payload).await?;
|
||||||
|
total += CHUNK as u64;
|
||||||
|
pace(start, total, limit).await;
|
||||||
|
}
|
||||||
|
socket.write_u32(0).await?;
|
||||||
|
socket.write_u64(total).await?;
|
||||||
|
} else {
|
||||||
|
ensure!(direction == 2, "invalid direction");
|
||||||
|
loop {
|
||||||
|
let len = socket.read_u32().await? as usize;
|
||||||
|
if len == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ensure!(len <= CHUNK, "invalid upload frame");
|
||||||
|
socket.read_exact(&mut payload[..len]).await?;
|
||||||
|
ensure!(
|
||||||
|
payload[..len].iter().all(|v| *v == tag),
|
||||||
|
"upload data/route corruption"
|
||||||
|
);
|
||||||
|
total += len as u64;
|
||||||
|
}
|
||||||
|
socket.write_u64(total).await?;
|
||||||
|
}
|
||||||
|
socket.flush().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ProxyStub {
|
||||||
|
address: SocketAddrV4,
|
||||||
|
task: JoinHandle<()>,
|
||||||
|
wrong: Arc<AtomicUsize>,
|
||||||
|
tcp: Arc<AtomicUsize>,
|
||||||
|
udp: Arc<AtomicUsize>,
|
||||||
|
}
|
||||||
|
impl ProxyStub {
|
||||||
|
async fn start(limit: u32) -> Result<Self> {
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||||
|
let address = listener.local_addr()?.to_string().parse()?;
|
||||||
|
let wrong = Arc::new(AtomicUsize::new(0));
|
||||||
|
let tcp = Arc::new(AtomicUsize::new(0));
|
||||||
|
let udp = Arc::new(AtomicUsize::new(0));
|
||||||
|
let (w, t, u) = (wrong.clone(), tcp.clone(), udp.clone());
|
||||||
|
let task = tokio::spawn(async move {
|
||||||
|
let mut handlers = JoinSet::new();
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
accepted=listener.accept()=>{let (mut stream,_)=accepted.unwrap();let (w,t,u)=(w.clone(),t.clone(),u.clone());
|
||||||
|
handlers.spawn(async move {let outcome:Result<()>=async {
|
||||||
|
let mut auth=[0;3];stream.read_exact(&mut auth).await?;ensure!(auth==[5,1,0],"unexpected upstream auth");stream.write_all(&[5,0]).await?;
|
||||||
|
let mut request=[0;10];stream.read_exact(&mut request).await?;
|
||||||
|
ensure!(request[0]==5&&request[3]==1,"unsupported upstream request");
|
||||||
|
if request[1]==1 {
|
||||||
|
if request[4..10]!=[198,51,100,77,1,187] {w.fetch_add(1,Ordering::Relaxed);anyhow::bail!("wrong TCP outbound");}
|
||||||
|
t.fetch_add(1,Ordering::Relaxed);stream.write_all(&[5,0,0,1,127,0,0,1,0,0]).await?;
|
||||||
|
serve(Box::new(stream),PROXY_TAG,limit).await?;
|
||||||
|
} else {
|
||||||
|
ensure!(request[1]==3,"unsupported upstream command");
|
||||||
|
let relay=UdpSocket::bind("127.0.0.1:0").await?;let port=relay.local_addr()?.port();
|
||||||
|
let mut reply=vec![5,0,0,1,127,0,0,1];reply.extend(port.to_be_bytes());stream.write_all(&reply).await?;
|
||||||
|
let mut buffer=[0u8;2048];let mut control=[0;1];loop {tokio::select! {
|
||||||
|
_=stream.read(&mut control)=>break,
|
||||||
|
message=relay.recv_from(&mut buffer)=>{let (n,source)=message?;
|
||||||
|
if n<10 || buffer[..10]!=[0,0,0,1,198,51,100,77,20,233] {w.fetch_add(1,Ordering::Relaxed);anyhow::bail!("wrong UDP outbound");}
|
||||||
|
u.fetch_add(1,Ordering::Relaxed);relay.send_to(&buffer[..n],source).await?;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}.await;let _=outcome;});
|
||||||
|
},
|
||||||
|
_=handlers.join_next(),if !handlers.is_empty()=>{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Ok(Self {
|
||||||
|
address,
|
||||||
|
task,
|
||||||
|
wrong,
|
||||||
|
tcp,
|
||||||
|
udp,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
async fn stop(&mut self) {
|
||||||
|
self.task.abort();
|
||||||
|
let _ = (&mut self.task).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for ProxyStub {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.task.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Flow {
|
||||||
|
bytes: u64,
|
||||||
|
start: Instant,
|
||||||
|
end: Instant,
|
||||||
|
}
|
||||||
|
impl Flow {
|
||||||
|
fn json(
|
||||||
|
&self,
|
||||||
|
phase: &str,
|
||||||
|
lane: &str,
|
||||||
|
direction: &str,
|
||||||
|
repeat: usize,
|
||||||
|
overlap_ms: u128,
|
||||||
|
) -> Value {
|
||||||
|
let seconds = self.end.duration_since(self.start).as_secs_f64();
|
||||||
|
json!({"mode":"combined_flow","phase":phase,"lane":lane,
|
||||||
|
"direction":direction,"repeat":repeat,"bytes":self.bytes,"seconds":seconds,"mbps":self.bytes as f64*8.0/seconds/1e6,"overlap_ms":overlap_ms})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn transfer(
|
||||||
|
entry: SocketAddrV4,
|
||||||
|
target: SocketAddrV4,
|
||||||
|
download: bool,
|
||||||
|
tag: u8,
|
||||||
|
seconds: u64,
|
||||||
|
limit: u32,
|
||||||
|
barrier: Option<Arc<Barrier>>,
|
||||||
|
mut progress: Option<oneshot::Sender<()>>,
|
||||||
|
) -> Result<Flow> {
|
||||||
|
timeout(Duration::from_secs(seconds + 15), async {
|
||||||
|
let (mut socket, _) = socks(entry, 1, target).await?;
|
||||||
|
if let Some(barrier) = barrier {
|
||||||
|
barrier.wait().await;
|
||||||
|
}
|
||||||
|
let start = Instant::now();
|
||||||
|
socket.write_u8(if download { 1 } else { 2 }).await?;
|
||||||
|
socket.write_u64(seconds * 1000).await?;
|
||||||
|
let mut payload = vec![tag; CHUNK];
|
||||||
|
let mut bytes = 0u64;
|
||||||
|
if download {
|
||||||
|
loop {
|
||||||
|
let len = socket.read_u32().await? as usize;
|
||||||
|
if len == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ensure!(len <= CHUNK, "invalid download frame");
|
||||||
|
socket.read_exact(&mut payload[..len]).await?;
|
||||||
|
ensure!(
|
||||||
|
payload[..len].iter().all(|v| *v == tag),
|
||||||
|
"download data/route corruption"
|
||||||
|
);
|
||||||
|
bytes += len as u64;
|
||||||
|
if let Some(tx) = progress.take() {
|
||||||
|
let _ = tx.send(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ensure!(socket.read_u64().await? == bytes, "download count mismatch");
|
||||||
|
} else {
|
||||||
|
while start.elapsed() < Duration::from_secs(seconds) {
|
||||||
|
socket.write_u32(CHUNK as u32).await?;
|
||||||
|
socket.write_all(&payload).await?;
|
||||||
|
bytes += CHUNK as u64;
|
||||||
|
if let Some(tx) = progress.take() {
|
||||||
|
let _ = tx.send(());
|
||||||
|
}
|
||||||
|
pace(start, bytes, limit).await;
|
||||||
|
}
|
||||||
|
socket.write_u32(0).await?;
|
||||||
|
ensure!(socket.read_u64().await? == bytes, "upload count mismatch");
|
||||||
|
}
|
||||||
|
ensure!(bytes > 0, "empty transfer");
|
||||||
|
Ok(Flow {
|
||||||
|
bytes,
|
||||||
|
start,
|
||||||
|
end: Instant::now(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn udp_probe(entry: SocketAddrV4, target: SocketAddrV4, tag: u8) -> Result<()> {
|
||||||
|
timeout(WAIT, async {
|
||||||
|
let (_control, relay) = socks(entry, 3, "0.0.0.0:0".parse()?).await?;
|
||||||
|
let local = UdpSocket::bind("127.0.0.1:0").await?;
|
||||||
|
let mut frame = vec![0, 0, 0, 1];
|
||||||
|
frame.extend(target.ip().octets());
|
||||||
|
frame.extend(target.port().to_be_bytes());
|
||||||
|
frame.extend([tag, 3, 5, 7]);
|
||||||
|
local.send_to(&frame, relay).await?;
|
||||||
|
let mut buffer = [0u8; 2048];
|
||||||
|
let (n, _) = local.recv_from(&mut buffer).await?;
|
||||||
|
ensure!(buffer[..n] == frame, "UDP data/route corruption");
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||||
|
#[ignore = "native combined load test; run scripts/test.py combined"]
|
||||||
|
async fn combined_coexistence() -> Result<()> {
|
||||||
|
let seconds = std::env::var("MESHPORT_JOINT_SECONDS")
|
||||||
|
.unwrap_or_else(|_| "2".into())
|
||||||
|
.parse::<u64>()?;
|
||||||
|
let repeats = std::env::var("MESHPORT_JOINT_REPEATS")
|
||||||
|
.unwrap_or_else(|_| "3".into())
|
||||||
|
.parse::<usize>()?;
|
||||||
|
let delay = std::env::var("MESHPORT_TEST_DELAY_MS")
|
||||||
|
.unwrap_or_else(|_| "29".into())
|
||||||
|
.parse::<u64>()?;
|
||||||
|
let limit = std::env::var("MESHPORT_JOINT_PROXY_MBPS")
|
||||||
|
.unwrap_or_else(|_| "100".into())
|
||||||
|
.parse::<u32>()?;
|
||||||
|
ensure!(
|
||||||
|
(1..=5).contains(&seconds) && (1..=10).contains(&repeats) && delay <= 500,
|
||||||
|
"invalid joint test parameters"
|
||||||
|
);
|
||||||
|
let reserved = std::net::UdpSocket::bind("127.0.0.1:0")?;
|
||||||
|
let port = reserved.local_addr()?.port();
|
||||||
|
drop(reserved);
|
||||||
|
let identity =
|
||||||
|
"[network_identity]\nnetwork_name='combined-fixture'\nnetwork_secret='test-only'\n";
|
||||||
|
let server = create_native_instance(TomlConfig::new_from_str(&format!(
|
||||||
|
"ipv4='10.253.91.2/24'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/24'\nmapped_cidr='10.253.93.0/24'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true\ndisable_p2p=true\nenable_encryption=true"
|
||||||
|
))?)?;
|
||||||
|
server.start().await?;
|
||||||
|
let relay = UdpSocket::bind("127.0.0.1:0").await?;
|
||||||
|
let relay_port = relay.local_addr()?.port();
|
||||||
|
let relay_task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||||
|
let remote: std::net::SocketAddr = format!("127.0.0.1:{port}").parse().unwrap();
|
||||||
|
let mut client = None;
|
||||||
|
let mut pending = std::collections::VecDeque::new();
|
||||||
|
let mut buf = vec![0u8; 65536];
|
||||||
|
loop {
|
||||||
|
let at = pending
|
||||||
|
.front()
|
||||||
|
.map(|(at, _, _): &(tokio::time::Instant, Vec<u8>, std::net::SocketAddr)| *at)
|
||||||
|
.unwrap_or_else(|| tokio::time::Instant::now() + Duration::from_secs(3600));
|
||||||
|
tokio::select! {value=relay.recv_from(&mut buf)=>{let(n,source)=value.unwrap();let dest=if source==remote {let Some(client)=client else{continue};client}else{client=Some(source);remote};pending.push_back((tokio::time::Instant::now()+Duration::from_millis(delay),buf[..n].to_vec(),dest));},
|
||||||
|
_=tokio::time::sleep_until(at),if !pending.is_empty()=>{let(_,data,dest)=pending.pop_front().unwrap();relay.send_to(&data,dest).await.unwrap();}}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
let network=Arc::new(Network::start(&format!("ipv4='10.253.91.11/24'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{relay_port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true\ndisable_p2p=true")).await?);
|
||||||
|
timeout(WAIT, async {
|
||||||
|
while network.snapshot().await["peer_count"].as_u64().unwrap_or(0) == 0 {
|
||||||
|
sleep(Duration::from_millis(50)).await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let mut bridge = Bridge::start(network.clone(), Options::default()).await?;
|
||||||
|
let mut listener = server.data_plane_tcp_bind(0, WAIT).await?;
|
||||||
|
let mesh: SocketAddrV4 = format!("10.253.91.2:{}", listener.local_addr().port()).parse()?;
|
||||||
|
let mesh_task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||||
|
let mut children = JoinSet::new();
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
accepted=listener.accept()=>{let Ok((socket,_))=accepted else {break};children.spawn(serve(Box::new(socket),MESH_TAG,0));},
|
||||||
|
_=children.join_next(),if !children.is_empty()=>{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
let echo = UdpSocket::bind("127.0.0.1:0").await?;
|
||||||
|
let mesh_udp: SocketAddrV4 = format!("10.253.93.1:{}", echo.local_addr()?.port()).parse()?;
|
||||||
|
let echo_task = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
|
||||||
|
let mut buf = [0; 2048];
|
||||||
|
loop {
|
||||||
|
let (n, source) = echo.recv_from(&mut buf).await.unwrap();
|
||||||
|
echo.send_to(&buf[..n], source).await.unwrap();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
let mut upstream = ProxyStub::start(limit).await?;
|
||||||
|
let internet: SocketAddrV4 = "198.51.100.77:443".parse()?;
|
||||||
|
let internet_udp = "198.51.100.77:5353".parse()?;
|
||||||
|
let mut engine = NativeProxy::open()?;
|
||||||
|
for round in 1..=repeats {
|
||||||
|
for download in [true, false] {
|
||||||
|
let direction = if download { "download" } else { "upload" };
|
||||||
|
for (phase, feature, lane, target, tag, rate) in [
|
||||||
|
("mesh_only", "mesh", "mesh", mesh, MESH_TAG, 0),
|
||||||
|
("proxy_only", "proxy", "proxy", internet, PROXY_TAG, limit),
|
||||||
|
("combined_idle_mesh", "combined", "mesh", mesh, MESH_TAG, 0),
|
||||||
|
(
|
||||||
|
"combined_idle_proxy",
|
||||||
|
"combined",
|
||||||
|
"proxy",
|
||||||
|
internet,
|
||||||
|
PROXY_TAG,
|
||||||
|
limit,
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
engine.start(feature, bridge.local_addr(), upstream.address)?;
|
||||||
|
let flow = transfer(
|
||||||
|
engine.listen,
|
||||||
|
target,
|
||||||
|
download,
|
||||||
|
tag,
|
||||||
|
seconds,
|
||||||
|
rate,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
println!("{}", flow.json(phase, lane, direction, round, 0));
|
||||||
|
engine.stop().await?;
|
||||||
|
}
|
||||||
|
engine.start("combined", bridge.local_addr(), upstream.address)?;
|
||||||
|
let gate = Arc::new(Barrier::new(2));
|
||||||
|
let (mtx, mrx) = oneshot::channel();
|
||||||
|
let (ptx, prx) = oneshot::channel();
|
||||||
|
let a = transfer(
|
||||||
|
engine.listen,
|
||||||
|
mesh,
|
||||||
|
download,
|
||||||
|
MESH_TAG,
|
||||||
|
seconds,
|
||||||
|
0,
|
||||||
|
Some(gate.clone()),
|
||||||
|
Some(mtx),
|
||||||
|
);
|
||||||
|
let b = transfer(
|
||||||
|
engine.listen,
|
||||||
|
internet,
|
||||||
|
download,
|
||||||
|
PROXY_TAG,
|
||||||
|
seconds,
|
||||||
|
limit,
|
||||||
|
Some(gate),
|
||||||
|
Some(ptx),
|
||||||
|
);
|
||||||
|
let probes = async {
|
||||||
|
mrx.await?;
|
||||||
|
prx.await?;
|
||||||
|
let start = Instant::now();
|
||||||
|
for _ in 0..4 {
|
||||||
|
let (m, p) = tokio::join!(
|
||||||
|
udp_probe(engine.listen, mesh_udp, MESH_TAG),
|
||||||
|
udp_probe(engine.listen, internet_udp, PROXY_TAG)
|
||||||
|
);
|
||||||
|
m?;
|
||||||
|
p?;
|
||||||
|
}
|
||||||
|
Ok::<_, anyhow::Error>((start, Instant::now()))
|
||||||
|
};
|
||||||
|
let (a, b, probes) = tokio::join!(a, b, probes);
|
||||||
|
let (a, b, probes) = (a?, b?, probes?);
|
||||||
|
let overlap = a
|
||||||
|
.end
|
||||||
|
.min(b.end)
|
||||||
|
.duration_since(a.start.max(b.start))
|
||||||
|
.as_millis();
|
||||||
|
ensure!(
|
||||||
|
overlap >= seconds as u128 * 800,
|
||||||
|
"insufficient concurrent overlap"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
probes.0 >= a.start.max(b.start) && probes.1 <= a.end.min(b.end),
|
||||||
|
"UDP probes were not under concurrent TCP load"
|
||||||
|
);
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
a.json("concurrent", "mesh", direction, round, overlap)
|
||||||
|
);
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
b.json("concurrent", "proxy", direction, round, overlap)
|
||||||
|
);
|
||||||
|
engine.stop().await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ensure!(
|
||||||
|
upstream.wrong.load(Ordering::Relaxed) == 0
|
||||||
|
&& upstream.tcp.load(Ordering::Relaxed) > 0
|
||||||
|
&& upstream.udp.load(Ordering::Relaxed) == repeats * 2 * 4,
|
||||||
|
"route counters mismatch"
|
||||||
|
);
|
||||||
|
engine.start("combined", bridge.local_addr(), upstream.address)?;
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
let healthy = transfer(
|
||||||
|
engine.listen,
|
||||||
|
mesh,
|
||||||
|
true,
|
||||||
|
MESH_TAG,
|
||||||
|
seconds,
|
||||||
|
0,
|
||||||
|
None,
|
||||||
|
Some(tx),
|
||||||
|
);
|
||||||
|
let fail_proxy = async {
|
||||||
|
rx.await?;
|
||||||
|
upstream.stop().await;
|
||||||
|
ensure!(
|
||||||
|
transfer(
|
||||||
|
engine.listen,
|
||||||
|
internet,
|
||||||
|
true,
|
||||||
|
PROXY_TAG,
|
||||||
|
seconds,
|
||||||
|
limit,
|
||||||
|
None,
|
||||||
|
None
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"stopped proxy unexpectedly succeeded"
|
||||||
|
);
|
||||||
|
Ok::<_, anyhow::Error>(())
|
||||||
|
};
|
||||||
|
let (healthy, failed) = tokio::join!(healthy, fail_proxy);
|
||||||
|
healthy?;
|
||||||
|
failed?;
|
||||||
|
engine.stop().await?;
|
||||||
|
upstream = ProxyStub::start(limit).await?;
|
||||||
|
engine.start("combined", bridge.local_addr(), upstream.address)?;
|
||||||
|
transfer(
|
||||||
|
engine.listen,
|
||||||
|
internet,
|
||||||
|
true,
|
||||||
|
PROXY_TAG,
|
||||||
|
seconds,
|
||||||
|
limit,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
let healthy = transfer(
|
||||||
|
engine.listen,
|
||||||
|
internet,
|
||||||
|
true,
|
||||||
|
PROXY_TAG,
|
||||||
|
seconds,
|
||||||
|
limit,
|
||||||
|
None,
|
||||||
|
Some(tx),
|
||||||
|
);
|
||||||
|
let fail_mesh = async {
|
||||||
|
rx.await?;
|
||||||
|
let before = upstream.tcp.load(Ordering::Relaxed);
|
||||||
|
bridge.stop().await?;
|
||||||
|
network.stop().await;
|
||||||
|
ensure!(
|
||||||
|
transfer(engine.listen, mesh, true, MESH_TAG, seconds, 0, None, None)
|
||||||
|
.await
|
||||||
|
.is_err(),
|
||||||
|
"stopped mesh unexpectedly succeeded"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
upstream.tcp.load(Ordering::Relaxed) == before,
|
||||||
|
"mesh leaked into proxy"
|
||||||
|
);
|
||||||
|
Ok::<_, anyhow::Error>(())
|
||||||
|
};
|
||||||
|
let (healthy, failed) = tokio::join!(healthy, fail_mesh);
|
||||||
|
healthy?;
|
||||||
|
failed?;
|
||||||
|
ensure!(
|
||||||
|
engine.request(json!({"op":"status"}))?["state"] == "Running",
|
||||||
|
"healthy proxy was stopped"
|
||||||
|
);
|
||||||
|
engine.stop().await?;
|
||||||
|
upstream.stop().await;
|
||||||
|
server.stop().await;
|
||||||
|
drop(mesh_task);
|
||||||
|
drop(echo_task);
|
||||||
|
drop(relay_task);
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
json!({"mode":"combined_functional","mesh_survives_proxy_stop":true,"proxy_survives_mesh_stop":true,
|
||||||
|
"no_mesh_to_proxy_fallback":true,"proxy_recovered":true,"ports_released":true,"udp_probes_per_lane":repeats*2*4,
|
||||||
|
"rtt_ms":delay*2,"duration_seconds":seconds,"proxy_limit_mbps":limit,"repeats":repeats})
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
# 自动化测试
|
||||||
|
|
||||||
|
统一入口为 `python3 scripts/test.py`,仅使用 Python 标准库。可以从任意目录运行脚本。原有单项脚本继续可用。
|
||||||
|
|
||||||
|
## 日常运行
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/test.py
|
||||||
|
python3 scripts/test.py --list
|
||||||
|
python3 scripts/test.py sdk engine
|
||||||
|
python3 scripts/test.py client
|
||||||
|
python3 scripts/test.py client --native
|
||||||
|
python3 scripts/test.py runner
|
||||||
|
python3 scripts/test.py speed --min-mbps 10
|
||||||
|
python3 scripts/test.py combined
|
||||||
|
```
|
||||||
|
|
||||||
|
无参数等价于 `all`,覆盖自动化入口自身、Rust workspace、Go race/vet、Go → SDK TCP/UDP 联调、Flutter analyze/全量测试,以及 macOS 配置存储测试。`all` 不包含手动吞吐诊断或速度矩阵。各模块按固定顺序串行运行,不并行争用网络夹具或编译输出。
|
||||||
|
|
||||||
|
| 模块 | 范围 | 依赖 |
|
||||||
|
|---|---|---|
|
||||||
|
| `runner` | 入口脚本的失败传播、依赖跳过、超时与报告测试 | Python 3.9+ |
|
||||||
|
| `sdk` | `cargo test --workspace --release --locked`,保留显式忽略的测试 | Rust ≥1.95、protoc |
|
||||||
|
| `engine` | Go `test -race`、`vet`、构建测试引擎、显式运行真实 Go/SDK 桥接测试 | Go、C 编译器、Python、Rust/protoc |
|
||||||
|
| `client` | Flutter 依赖解析、analyze、全量测试 | Flutter(Dart ≥3.11) |
|
||||||
|
| `macos` | `LocalProfileStore` 的 Swift 本地测试 | macOS、Xcode command-line tools |
|
||||||
|
| `throughput` | 生产 TCP 封装的 channel/UDP 对照、加密 SDK 延迟吞吐诊断 | Rust/protoc |
|
||||||
|
| `speed` | 多延迟、多轮双向测速,包含 SDK、SOCKS、sing-box,自动汇总与门槛检查 | Rust/protoc、Go、C 编译器 |
|
||||||
|
| `combined` | 同进程真实 Rust SDK + Go FFI,组网/代理双路负载、UDP、故障隔离和速度对照 | macOS、Rust/protoc、Go、C 编译器 |
|
||||||
|
|
||||||
|
Rust、Go 优先复用 `scripts/cargo-local.sh`、`scripts/go-local.sh` 和项目本地工具链。Flutter 使用 PATH 中的 `flutter`。依赖解析或构建可能访问依赖仓库;测试通信使用隔离测试配置与本机夹具。macOS 存储检查在其他平台显示为 SKIP;其他平台是否能通过所有 Rust/Go/Flutter 测试仍需各自验证。
|
||||||
|
|
||||||
|
## 原生 Flutter 测试
|
||||||
|
|
||||||
|
默认 `client` 清除继承的 `MESHPORT_LIBRARY`、`MESHPORT_PROXY_LIBRARY` 等变量,依赖原生库的用例按现有机制显示为跳过,不误用旧库。`--native` 显式构建 Rust FFI 和 Go 代理库,再把这次构建的路径传给 Flutter 测试。当前原生库构建脚本只支持此入口的 macOS 路径,因此其他平台使用 `--native` 会明确报错。
|
||||||
|
|
||||||
|
原生连接 widget 测试使用固定 `load_profile` 夹具:没有外部 peer、监听服务或 STUN,不继承打包的个人默认网络。它启动应用内测试引擎,不请求管理员权限、安装 TUN 或连接用户节点。
|
||||||
|
|
||||||
|
## 可选吞吐诊断
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/test.py throughput --rtt-ms 58 --mib 8
|
||||||
|
```
|
||||||
|
|
||||||
|
`--rtt-ms` 是双向合计的附加 RTT,必须是 0–1000 的偶数;每方向加入一半延迟。`--mib` 为每个方向的数据量,范围 1–64,默认 8 MiB。
|
||||||
|
|
||||||
|
吞吐模块显式运行两个手动诊断,不使用全局 `--include-ignored`:TCP 封装分别通过保序内存通道和本机 UDP 传输,加密 SDK 路径输出合成测试包的窗口、重复序号及 UDP 会话队列满事件。不会读取真实下载链接或用户配置,也不会创建系统 VPN。会自动解析数据、检查上传/下载完整性、参数一致性和正的有限速度;绝对速度与基线门槛使用下面的 `speed` 模块。
|
||||||
|
|
||||||
|
夹具内部还有 60/90 秒的传输保护;很大的 RTT 与数据量组合可能触发该保护。入口的 `--timeout` 不覆盖夹具内部超时。
|
||||||
|
|
||||||
|
## 速度矩阵与性能门槛
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/test.py speed --min-mbps 10
|
||||||
|
python3 scripts/test.py all speed --native --min-mbps 10
|
||||||
|
python3 scripts/test.py speed --rtts-ms 0,58,100 --repeat 3 --mib 8
|
||||||
|
```
|
||||||
|
|
||||||
|
默认在 0、58、100 ms 附加 RTT 下各运行 3 轮,每方向传输 8 MiB。包含生产 TCP 封装的内存通道/普通 UDP 对照,以及 SDK 直连、SOCKS、sing-box → SOCKS 三条加密组网路径,共 90 个方向测量样本、30 个汇总分组。单独运行 `speed` 会构建所需 Go 引擎;与 `all` 合并时复用引擎构建。与 `throughput` 同时指定时只执行覆盖更完整的速度矩阵。
|
||||||
|
|
||||||
|
每个分组记录中位数、最小/最大 Mbps、重复 TCP 数据序号、最大数据包间隔与会话队列满事件。判定规则:
|
||||||
|
|
||||||
|
- 缺少某条路径的上传/下载、缺少包级统计、速度非正/非有限、参数不一致或重复样本,即使命令返回 0 也判失败。
|
||||||
|
- 每组必须完成指定轮数,组中位数不能低于 `--min-mbps`。默认 0,表示不设置跨机器的统一绝对速度要求;上面的 10 Mbps 是显式配置的本地验收值,不是公网速度承诺。
|
||||||
|
- SDK 会话队列满事件在每组的所有轮次中合计不能超过 `--max-queue-drops`,默认 0。该门槛用于加密 SDK 路径;普通通道没有 SDK 会话队列。
|
||||||
|
- 不对所有重复序号/零窗口设置硬性零阈值,因为它们不独立等同于实际丢包;原始统计保留供诊断。
|
||||||
|
|
||||||
|
基线回归比较:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/test.py speed --baseline /path/to/previous/metrics.json \
|
||||||
|
--max-regression-percent 20 --min-mbps 10
|
||||||
|
```
|
||||||
|
|
||||||
|
基线应来自同一机器、可比较的负载和工具链。模式、目标、入口、RTT、每方向数据量和方向必须完全匹配,否则拒绝比较;当前组中位数下降超过指定百分比时失败。基线格式、有限数值和重复分组也会验证。矩阵/门槛参数必须与 `speed` 一起使用,避免只跑功能测试却误认为已检查速度。
|
||||||
|
|
||||||
|
这是本机合成链路回归,不覆盖系统 TUN、真实公网节点、真实 NAS 下载或网络切换。实际 App 测速功能另有 HTTP 代理夹具,覆盖 Mbps 换算、首字节时间、空响应、非法端口、重定向、并发重入、超时/部分数据、取消恢复、传输上限和禁止直连回退。
|
||||||
|
|
||||||
|
## sing-box 与组网联合测试
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/test.py combined
|
||||||
|
python3 scripts/test.py combined --rtt-ms 58 --joint-repeat 3 --joint-seconds 2 --proxy-mbps 100
|
||||||
|
python3 scripts/test.py combined --proxy-mbps 0
|
||||||
|
```
|
||||||
|
|
||||||
|
`combined` 是显式选择的测试,不包含在默认 `all` 中。它构建 Go 共享库,在同一进程加载真实 Go FFI 和 Rust SDK,通过加密 EasyTier UDP 链路连接隔离节点。代理出口使用本地 SOCKS 上游夹具。不会启动系统 TUN、修改系统 VPN 或读取真实代理配置;因此不能据此判断真实运营商、NAS、公网代理或 TUN 路由冲突。
|
||||||
|
|
||||||
|
默认模拟组网 RTT 58 ms,每路每次持续至少 2 秒、重复 3 轮。分别对照组网路由配置、代理路由配置、联合配置单路传输、联合配置双路并发,覆盖上传和下载,共 36 个速度样本。SDK 节点在代理基线阶段保持空闲。代理夹具默认限速 100 Mbps,方便比较相同负载;`--proxy-mbps 0` 取消限速,用于主机资源竞争压力测试,可能暴露 CPU/内存带宽竞争。
|
||||||
|
|
||||||
|
双路并发要求传输重叠至少为配置时长的 80%,并在两路 TCP 同时传输期间分别完成 24 次 UDP 校验(默认三轮)。TCP/UDP 使用不同路径标记并校验数据,统计上游访问目标,检查组网流量没有进入代理出口。故障注入分别停止代理上游和组网桥接/节点,要求另一条已建立的传输继续成功;同时验证代理上游恢复以及每次停止后监听端口释放。
|
||||||
|
|
||||||
|
自动比较各方向中位数:联合配置空闲一路相对单独配置、并发相对联合配置单路、并发相对单独配置。下降超过 `--max-joint-slowdown-percent`(默认 20%)会使测试失败,测量仍保留在报告中。缺失样本、无效速度、重叠不足、UDP 或故障隔离未完成,即使命令返回 0 也会判失败。短时本地测试存在波动,不能替代长时间真实网络测试。
|
||||||
|
|
||||||
|
额外输出 `combined-metrics.json` 和 `combined-summary.md`,包含逐轮结果、中位数、变化百分比及功能检查证据。
|
||||||
|
|
||||||
|
## 报告与失败处理
|
||||||
|
|
||||||
|
默认输出目录:`outputs/validation/automated-tests/<UTC时间>-<随机ID>/`,已加入 Git 忽略规则。
|
||||||
|
|
||||||
|
- 每条命令一个 `.log`,终端输出运行阶段、耗时和失败日志末尾。
|
||||||
|
- `report.json` 记录命令、工作目录、状态、退出码、耗时和日志路径,不保存运行环境变量。
|
||||||
|
- `junit.xml` 以命令为 testcase,适合 CI 汇总;单元测试内部的通过/跳过数量在对应原始日志中。
|
||||||
|
- 速度模块另生成 `metrics.json`(逐次测量及分组汇总,可作为基线)和 `speed-summary.md`(易读表格);`speed-check` 的门槛失败同时进入 JSON/JUnit 和最终退出码。
|
||||||
|
|
||||||
|
任何失败返回 1;中断返回 130。默认继续其他独立模块,构建失败时跳过依赖它的步骤,最终仍返回失败。`--fail-fast` 在首个失败后跳过剩余步骤。每条命令默认最多运行 900 秒,超时终止命令及其进程组并记录退出码 124;可用 `--timeout 1800` 调整。
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/test.py sdk engine --fail-fast --timeout 1800
|
||||||
|
python3 scripts/test.py all --log-dir /tmp/meshport-ci-results
|
||||||
|
```
|
||||||
|
|
||||||
|
自定义 `--log-dir` 必须尚不存在,以防覆盖历史记录。入口会清除所有继承的 `MESHPORT_*` 环境变量,再为所选模块设置必要的测试路径和参数,避免旧动态库、真实 profile 或遗留诊断开关影响本轮测试。
|
||||||
|
|
||||||
|
## CI 接入
|
||||||
|
|
||||||
|
在 CI 中安装所选模块的依赖后运行同一命令,直接使用其退出码判断成功;无论结果如何,收集报告目录中的 JSON、JUnit XML 和 `.log`。例如只验证 SDK 与引擎:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/test.py sdk engine --log-dir /tmp/meshport-ci-results
|
||||||
|
```
|
||||||
|
|
||||||
|
本次提供的是可供 CI 调用的测试入口,没有添加自动推送、发布或安装应用的步骤。系统 TUN、Android 真机、签名/打包及真实公网测试继续使用原有专项流程,不属于默认自动化回归。
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
# 验证记录
|
# 验证记录
|
||||||
|
|
||||||
|
日常回归可使用 `python3 scripts/test.py`。模块选择、原生库测试、吞吐诊断及 JSON/JUnit 报告见 [自动化测试](automated-testing.md)。以下为各阶段的历史验证记录。
|
||||||
|
|
||||||
## Android 阶段(2026-10-10)
|
## Android 阶段(2026-10-10)
|
||||||
|
|
||||||
ARM64 Rust 原生库、JNI 桥接、Android debug/release APK 构建通过。OPPO PJZ110(API 37,4 KB 页面)已完成 Android Keystore 独立测试存储的保存/重新读取/删除,以及 SDK 经隔离公告子网的 TCP/UDP 回显。系统 VPN 授权后,Java 和 Dart 普通系统 Socket 的 TCP/UDP 回显、公告子网自动安装与撤销全部通过。修复了 JNI 绝对路径依赖、受保护 DNS resolver 功能缺失和 Android 网络注册时序。隔离 USB 夹具不覆盖公网打洞、长期后台运行或移动网络切换。
|
ARM64 Rust 原生库、JNI 桥接、Android debug/release APK 构建通过。OPPO PJZ110(API 37,4 KB 页面)已完成 Android Keystore 独立测试存储的保存/重新读取/删除,以及 SDK 经隔离公告子网的 TCP/UDP 回显。系统 VPN 授权后,Java 和 Dart 普通系统 Socket 的 TCP/UDP 回显、公告子网自动安装与撤销全部通过。修复了 JNI 绝对路径依赖、受保护 DNS resolver 功能缺失和 Android 网络注册时序。隔离 USB 夹具不覆盖公网打洞、长期后台运行或移动网络切换。
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# 软件功能与速度自动化验收,2026-11-03
|
||||||
|
|
||||||
|
## 结果
|
||||||
|
|
||||||
|
本次实际执行全部通过,未发现覆盖范围内的功能失败或配置门槛失败:
|
||||||
|
|
||||||
|
| 检查 | 结果 |
|
||||||
|
|---|---|
|
||||||
|
| 完整原生功能模式 `all --native` | 12 阶段通过,0 失败、0 阶段跳过 |
|
||||||
|
| Rust 工作区 | 47 项通过;4 项显式忽略,见下方边界 |
|
||||||
|
| Go 引擎 | race、vet 通过;桥接和 FFI 包测试通过(Go 可复用缓存) |
|
||||||
|
| Go → Rust SDK 桥接 | 显式运行被默认忽略的 TCP/UDP/公告撤销联调,1 项通过 |
|
||||||
|
| Flutter 客户端 | 77 项通过,含本次新增的测速边界用例与真实原生库用例 |
|
||||||
|
| macOS 配置存储 | 原生 Swift 存储、权限、原子替换、迁移、删除、重启、大小及符号链接/损坏处理通过 |
|
||||||
|
| 自动化/性能报告脚本 | 最终版本 14 项自测通过,包含“命令成功但测量缺失/速度门槛失败”的反例 |
|
||||||
|
| 速度矩阵 | 29 阶段通过,90 个方向样本,30 个汇总组,各组重复 3 次 |
|
||||||
|
| 实际速度门槛 | 显式设置中位数 ≥10 Mbps、每组会话队列满事件合计 ≤0;全部满足 |
|
||||||
|
|
||||||
|
速度采用本机合成拓扑,数据量每方向 8 MiB;RTT 是双向合计的附加延迟。SDK 加密链路包括直接调用 SDK、经本地 SOCKS、经 sing-box → SOCKS 三条路径;另含内存通道与普通 UDP 的生产 TCP 封装对照。没有把实际 WAN 速度当成本地测试结果。
|
||||||
|
|
||||||
|
## SDK 三条路径的速度中位数
|
||||||
|
|
||||||
|
每格为“下载 / 上传”,单位十进制 Mbps,每组 3 次。
|
||||||
|
|
||||||
|
| 附加 RTT | SDK | SOCKS → SDK | sing-box → SOCKS → SDK |
|
||||||
|
|---|---:|---:|---:|
|
||||||
|
| 0 ms | 631.43 / 662.99 | 692.41 / 639.10 | 688.33 / 643.64 |
|
||||||
|
| 58 ms | 60.93 / 60.72 | 60.51 / 61.11 | 63.27 / 61.28 |
|
||||||
|
| 100 ms | 36.75 / 36.42 | 37.66 / 36.87 | 38.37 / 36.77 |
|
||||||
|
|
||||||
|
三条 SDK 路径的全部速度组,会话队列满事件合计为 0。所有 30 个组中最低的速度中位数约 34.46 Mbps,高于本轮配置的 10 Mbps。重复 TCP 序号与包间隔保留在原始记录中,没有把所有重复序号或零窗口当成丢包并强制要求为零。
|
||||||
|
|
||||||
|
## 本次补齐
|
||||||
|
|
||||||
|
- `scripts/test.py speed`:多 RTT、多轮、双向和多入口测试;自动构建 Go 引擎。
|
||||||
|
- `scripts/performance.py`:校验每条路径的上传/下载、包级统计、数据量/RTT 与有限正速度。命令退出 0 但没有有效样本仍失败。
|
||||||
|
- 自动汇总中位数、最小/最大值、重复序号、最大数据间隔和队列满事件,生成 `metrics.json` 与 `speed-summary.md`。
|
||||||
|
- `speed-check` 把配置的速度/队列门槛或基线回退写入最终退出码、JSON/JUnit,避免只保存诊断日志却总显示通过。
|
||||||
|
- 基线比较检查模式、目标、入口、RTT、数据量、方向是否一致;单元测试验证速度下降、队列事件、缺少测量、重复/非法结果、基线不匹配及非有限速度都会被拒绝。真实基线文件的 CLI 读取/计划预览也已验证;本轮未重新运行另一套完整矩阵做历史基线对照。
|
||||||
|
- App 内 HTTP 测速共 11 个测试:单位换算、首字节、非法端口、空数据、重定向、并发重入/复用、部分数据超时、无数据超时、取消后重用、传输上限、强制代理与禁止直连回退、HTTP 错误。全部使用本地 HTTP 代理夹具。
|
||||||
|
- 原生连接测试使用固定无外部 peer/STUN 配置,不继承用户打包的个人默认网络。
|
||||||
|
|
||||||
|
## 复现
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/test.py all --native
|
||||||
|
python3 scripts/test.py speed --min-mbps 10 --repeat 3
|
||||||
|
# 后续同机基线比较
|
||||||
|
python3 scripts/test.py speed --baseline /path/to/metrics.json --max-regression-percent 20
|
||||||
|
```
|
||||||
|
|
||||||
|
完整用法见 [自动化测试](../../docs/automated-testing.md)。本轮使用同机串行测速,没有让功能测试与速度测试并行争用 CPU 或网络夹具。
|
||||||
|
|
||||||
|
## 原始产物
|
||||||
|
|
||||||
|
原始产物留在 Git 忽略的本机目录,可由 CI 上传归档:
|
||||||
|
|
||||||
|
- [完整功能 JSON 报告](automated-tests/20261104T014004Z-963346bd/report.json),[JUnit](automated-tests/20261104T014004Z-963346bd/junit.xml)。
|
||||||
|
- [速度矩阵 JSON 报告](automated-tests/20261104T013703Z-ce31d5d0/report.json),[JUnit](automated-tests/20261104T013703Z-ce31d5d0/junit.xml)。
|
||||||
|
- [最终脚本自测 JSON 报告](automated-tests/20261104T015239Z-28016fb2/report.json),[JUnit](automated-tests/20261104T015239Z-28016fb2/junit.xml)。
|
||||||
|
- [完整速度表](automated-tests/20261104T013703Z-ce31d5d0/speed-summary.md),[逐次样本与汇总](automated-tests/20261104T013703Z-ce31d5d0/metrics.json)。
|
||||||
|
|
||||||
|
## 边界
|
||||||
|
|
||||||
|
默认 Rust 测试跳过的 Go 联调与两个吞吐诊断已分别显式执行;需要真实物理 macOS 网络/TUN 的 `physical_bootstrap_with_existing_tun` 没有运行。12 个功能阶段显示“0 阶段跳过”不等于底层所有显式忽略用例都已执行。
|
||||||
|
|
||||||
|
本轮不启动已安装 App 的系统 VPN、不替换安装包、不修改用户网络配置。真实公网/NAS 下载、系统 TUN 的实际数据通路、移动设备、二维码/相机硬件、网络切换、长时间压力与内存增长未纳入此次验收;不能称为全部平台或全部场景已验证。绝对速度值是本机短传输观测,不是产品的公网带宽承诺。
|
||||||
|
|
||||||
|
提交前检查:`git diff --check` 通过。
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# sing-box 与组网联合测试验收(2026-11-03)
|
||||||
|
|
||||||
|
结论:本机 SDK/引擎层联合测试通过;本轮没有观察到明显速度下降、数据损坏、流量串线或一路故障导致另一路传输失败。小幅正向变化属于本次短时测量,不作为性能提升结论。
|
||||||
|
|
||||||
|
## 测试范围
|
||||||
|
|
||||||
|
- 真实 Rust SDK 与 Go sing-box 共享库处于同一进程;组网通过加密 EasyTier UDP 链路,模拟附加 RTT 58 ms。
|
||||||
|
- 代理出口为本地 SOCKS 夹具,分别限速 100 Mbps 和取消限速;不限速速度是本机转发能力,不是公网速度。
|
||||||
|
- 每组 3 轮,每次配置传输时长 2 秒;分别对照单独路由配置、联合配置单路传输、联合配置双路并发,均覆盖上传/下载。代理基线期间 SDK 节点保持空闲。
|
||||||
|
- 共 72 个速度样本;每组每路在 TCP 双路并发期间完成 24 次 UDP 数据校验。
|
||||||
|
- 分别停止代理上游与组网桥接/节点,验证另一条既有传输继续完成;同时验证代理恢复、组网不回退到代理、停止后监听端口释放。
|
||||||
|
- 未启动系统 TUN、未读取个人配置、未修改当前系统 VPN。未验证系统级 DNS/路由冲突、真实公网/NAS、长时间稳定性或移动端。
|
||||||
|
|
||||||
|
## 中位数结果
|
||||||
|
|
||||||
|
| 负载 | 路径 | 方向 | 单独配置 Mbps | 联合配置单路 Mbps | 双路并发 Mbps | 并发相对单独变化 |
|
||||||
|
|---|---|---|---:|---:|---:|---:|
|
||||||
|
| 代理限速 100 Mbps | mesh | download | 63.41 | 63.54 | 65.36 | +3.08% |
|
||||||
|
| 代理限速 100 Mbps | mesh | upload | 62.87 | 62.40 | 64.22 | +2.14% |
|
||||||
|
| 代理限速 100 Mbps | proxy | download | 99.87 | 99.88 | 99.95 | +0.08% |
|
||||||
|
| 代理限速 100 Mbps | proxy | upload | 99.89 | 99.87 | 99.90 | +0.01% |
|
||||||
|
| 代理不限速压力 | mesh | download | 63.51 | 64.22 | 67.63 | +6.49% |
|
||||||
|
| 代理不限速压力 | mesh | upload | 63.27 | 63.29 | 66.80 | +5.57% |
|
||||||
|
| 代理不限速压力 | proxy | download | 37078.21 | 37009.02 | 38264.92 | +3.20% |
|
||||||
|
| 代理不限速压力 | proxy | upload | 36473.09 | 36434.11 | 36911.23 | +1.20% |
|
||||||
|
|
||||||
|
## 自动化与原始证据
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 scripts/test.py combined
|
||||||
|
python3 scripts/test.py combined --proxy-mbps 0
|
||||||
|
python3 scripts/test.py runner
|
||||||
|
```
|
||||||
|
|
||||||
|
默认中位数下降门槛为 20%;同时检查完整样本、有效速度、并发重叠时间、UDP 校验和故障隔离。入口自身共 20 项单元测试通过。
|
||||||
|
|
||||||
|
原始日志与逐次测量位于 Git 忽略的本机目录;以下相对链接仅在保留原始产物的工作副本有效。
|
||||||
|
|
||||||
|
- 代理限速 100 Mbps:[汇总](automated-tests/20261104T033631Z-5bd64a3e/combined-summary.md)、[逐次数据](automated-tests/20261104T033631Z-5bd64a3e/combined-metrics.json)、[运行状态](automated-tests/20261104T033631Z-5bd64a3e/report.json)。
|
||||||
|
|
||||||
|
- 代理不限速压力:[汇总](automated-tests/20261104T033805Z-6ea20e0d/combined-summary.md)、[逐次数据](automated-tests/20261104T033805Z-6ea20e0d/combined-metrics.json)、[运行状态](automated-tests/20261104T033805Z-6ea20e0d/report.json)。
|
||||||
|
|
||||||
|
- 自动化入口检查:[日志](automated-tests/20261104T033945Z-c3b49af1/runner-tests.log)。
|
||||||
|
- 本轮增加测试和报告脚本及测试专用依赖,没有修改生产转发逻辑。
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""Validate native mesh/proxy coexistence measurements and compare medians."""
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
from statistics import median
|
||||||
|
|
||||||
|
PHASES = (("mesh_only", "mesh"), ("proxy_only", "proxy"),
|
||||||
|
("combined_idle_mesh", "mesh"), ("combined_idle_proxy", "proxy"),
|
||||||
|
("concurrent", "mesh"), ("concurrent", "proxy"))
|
||||||
|
FLAGS = ("mesh_survives_proxy_stop", "proxy_survives_mesh_stop",
|
||||||
|
"no_mesh_to_proxy_fallback", "proxy_recovered", "ports_released")
|
||||||
|
|
||||||
|
|
||||||
|
def positive(value):
|
||||||
|
return type(value) in (int, float) and math.isfinite(value) and value > 0
|
||||||
|
|
||||||
|
|
||||||
|
def parse(log, spec):
|
||||||
|
flows, functional = [], []
|
||||||
|
for line in log.splitlines():
|
||||||
|
if not line.startswith("{"):
|
||||||
|
continue
|
||||||
|
record = json.loads(line)
|
||||||
|
if record.get("mode") == "combined_flow":
|
||||||
|
flows.append(record)
|
||||||
|
elif record.get("mode") == "combined_functional":
|
||||||
|
functional.append(record)
|
||||||
|
expected = {(phase, lane, direction, repeat) for phase, lane in PHASES
|
||||||
|
for direction in ("download", "upload") for repeat in range(1, spec["repeats"] + 1)}
|
||||||
|
seen = set()
|
||||||
|
for flow in flows:
|
||||||
|
key = tuple(flow[k] for k in ("phase", "lane", "direction", "repeat"))
|
||||||
|
if key not in expected or key in seen:
|
||||||
|
raise ValueError("unexpected or duplicate joint sample: " + str(key))
|
||||||
|
seen.add(key)
|
||||||
|
if any(not positive(flow[k]) for k in ("bytes", "seconds", "mbps")):
|
||||||
|
raise ValueError("invalid joint transfer measurement")
|
||||||
|
if flow["seconds"] < spec["duration_seconds"] * .8:
|
||||||
|
raise ValueError("joint transfer duration too short")
|
||||||
|
if not math.isclose(flow["mbps"], flow["bytes"] * 8 / flow["seconds"] / 1e6, rel_tol=1e-6):
|
||||||
|
raise ValueError("inconsistent joint transfer rate")
|
||||||
|
overlap = flow["overlap_ms"]
|
||||||
|
if type(overlap) not in (float, int) or not math.isfinite(overlap) or overlap < 0:
|
||||||
|
raise ValueError("invalid joint overlap")
|
||||||
|
if flow["phase"] == "concurrent" and not spec["duration_seconds"] * 800 <= overlap <= flow["seconds"] * 1000:
|
||||||
|
raise ValueError("insufficient concurrent overlap")
|
||||||
|
if seen != expected:
|
||||||
|
raise ValueError(f"missing joint measurements: {len(expected - seen)}")
|
||||||
|
if len(functional) != 1 or any(functional[0].get(key) is not True for key in FLAGS):
|
||||||
|
raise ValueError("joint fault-isolation checks incomplete or failed")
|
||||||
|
for key in ("repeats", "duration_seconds", "rtt_ms", "proxy_limit_mbps"):
|
||||||
|
if functional[0].get(key) != spec[key]:
|
||||||
|
raise ValueError("joint configuration mismatch: " + key)
|
||||||
|
if functional[0].get("udp_probes_per_lane") != spec["repeats"] * 8:
|
||||||
|
raise ValueError("missing UDP probes under concurrent TCP load")
|
||||||
|
groups = []
|
||||||
|
for direction in ("download", "upload"):
|
||||||
|
for phase, lane in PHASES:
|
||||||
|
rates = [f["mbps"] for f in flows if (f["phase"], f["lane"], f["direction"]) == (phase, lane, direction)]
|
||||||
|
groups.append(dict(phase=phase, lane=lane, direction=direction, samples=len(rates),
|
||||||
|
median_mbps=median(rates), min_mbps=min(rates), max_mbps=max(rates)))
|
||||||
|
comparisons, issues = [], []
|
||||||
|
for direction in ("download", "upload"):
|
||||||
|
for lane in ("mesh", "proxy"):
|
||||||
|
rates = {g["phase"]: g["median_mbps"] for g in groups if g["lane"] == lane and g["direction"] == direction}
|
||||||
|
for label, before, after in (("enabled_idle", lane + "_only", "combined_idle_" + lane),
|
||||||
|
("concurrent_vs_idle", "combined_idle_" + lane, "concurrent"),
|
||||||
|
("concurrent_vs_only", lane + "_only", "concurrent")):
|
||||||
|
change = (rates[after] / rates[before] - 1) * 100
|
||||||
|
comparisons.append(dict(lane=lane, direction=direction, comparison=label, change_percent=change))
|
||||||
|
if change < -spec["max_slowdown_percent"]:
|
||||||
|
issues.append(f"{lane}/{direction}/{label}: {change:+.2f}% exceeds {spec['max_slowdown_percent']}% slowdown limit")
|
||||||
|
return dict(measurements=flows, functional=functional[0], summary=groups, comparisons=comparisons, issues=issues)
|
||||||
|
|
||||||
|
|
||||||
|
def markdown(result):
|
||||||
|
lines = ["# Native mesh + sing-box coexistence", "",
|
||||||
|
"Local upstream fixture; real Rust SDK and Go FFI in one process. No system TUN or WAN.", "",
|
||||||
|
"| Phase | Lane | Direction | Samples | Median Mbps | Min | Max |",
|
||||||
|
"|---|---|---|---:|---:|---:|---:|"]
|
||||||
|
for g in result["summary"]:
|
||||||
|
lines.append(f"| {g['phase']} | {g['lane']} | {g['direction']} | {g['samples']} | {g['median_mbps']:.2f} | {g['min_mbps']:.2f} | {g['max_mbps']:.2f} |")
|
||||||
|
lines += ["", "| Lane | Direction | Comparison | Change |", "|---|---|---|---:|"]
|
||||||
|
for c in result["comparisons"]:
|
||||||
|
lines.append(f"| {c['lane']} | {c['direction']} | {c['comparison']} | {c['change_percent']:+.2f}% |")
|
||||||
|
lines += ["", "Functional evidence: `" + json.dumps(result["functional"], sort_keys=True) + "`", ""]
|
||||||
|
lines += result["issues"] or ["All configured joint criteria passed."]
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"""Parse synthetic speed fixtures and evaluate explicit performance criteria."""
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import re
|
||||||
|
import statistics
|
||||||
|
|
||||||
|
KEY_FIELDS = ("mode", "target", "entry", "rtt_ms", "mib", "direction")
|
||||||
|
|
||||||
|
|
||||||
|
def positive_number(value):
|
||||||
|
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and value > 0
|
||||||
|
|
||||||
|
|
||||||
|
def key(record):
|
||||||
|
return tuple(record[field] for field in KEY_FIELDS)
|
||||||
|
|
||||||
|
|
||||||
|
def parse(text, spec):
|
||||||
|
records = {}
|
||||||
|
for line in text.replace("\r", "\n").splitlines():
|
||||||
|
match = re.fullmatch(r"(sdk|subnet) entry=(sdk|socks|singbox) added_rtt_ms=(\d+) direction=(download|upload) mib=(\d+) mbps=([\d.eE+-]+)", line)
|
||||||
|
if match and spec["mode"] == "mesh":
|
||||||
|
target, entry, rtt, direction, mib, mbps = match.groups()
|
||||||
|
record = dict(mode="mesh", target=target, entry=entry, rtt_ms=int(rtt), mib=int(mib), direction=direction, mbps=float(mbps))
|
||||||
|
elif line.startswith("{"):
|
||||||
|
try:
|
||||||
|
value = json.loads(line)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
continue
|
||||||
|
if spec["mode"] == "mesh" and value.get("mode") == "easytier_encrypted_relay":
|
||||||
|
identity = ("mesh", value["target"], value["entry"], spec["rtt_ms"], spec["mib"], value["direction"])
|
||||||
|
if identity not in records or "wire" in records[identity]:
|
||||||
|
raise ValueError("missing or duplicate throughput sample for wire observation")
|
||||||
|
records[identity]["wire"] = value
|
||||||
|
continue
|
||||||
|
if value.get("mode") != spec["mode"] or spec["mode"] not in ("channel", "udp"):
|
||||||
|
continue
|
||||||
|
record = dict(mode=value["mode"], target="stack", entry="direct", rtt_ms=value["added_rtt_ms"],
|
||||||
|
mib=value["mib"], direction=value["direction"], mbps=value["mbps"], wire=value)
|
||||||
|
else:
|
||||||
|
continue
|
||||||
|
if not positive_number(record["mbps"]):
|
||||||
|
raise ValueError("speed must be finite and greater than zero")
|
||||||
|
if record["rtt_ms"] != spec["rtt_ms"] or record["mib"] != spec["mib"]:
|
||||||
|
raise ValueError("fixture RTT/data size differs from requested parameters")
|
||||||
|
identity = key(record)
|
||||||
|
if identity in records:
|
||||||
|
raise ValueError("duplicate speed sample")
|
||||||
|
record["repeat"] = spec.get("repeat", 1)
|
||||||
|
records[identity] = record
|
||||||
|
expected = {(spec["mode"], spec["target"], entry, spec["rtt_ms"], spec["mib"], direction)
|
||||||
|
for entry in spec["entries"] for direction in ("download", "upload")}
|
||||||
|
if set(records) != expected:
|
||||||
|
raise ValueError("missing/unexpected speed samples; both upload and download are required for every path")
|
||||||
|
for record in records.values():
|
||||||
|
wire = record.get("wire")
|
||||||
|
if wire is None:
|
||||||
|
raise ValueError("missing packet-level observation")
|
||||||
|
if record["mode"] == "mesh":
|
||||||
|
drops = wire.get("udp_session_queue_full_drops")
|
||||||
|
if not isinstance(drops, int) or isinstance(drops, bool) or drops < 0:
|
||||||
|
raise ValueError("missing/invalid UDP session queue-drop count")
|
||||||
|
record["queue_drops"] = drops
|
||||||
|
sender = wire.get("server_wire_at_relay" if record["direction"] == "download" else "client_wire_at_relay", {})
|
||||||
|
else:
|
||||||
|
sender = wire.get("server_wire" if record["direction"] == "download" else "client_wire", {})
|
||||||
|
for field in ("data_packets", "repeated_sequences", "max_data_gap_ms"):
|
||||||
|
number = sender.get(field)
|
||||||
|
if not isinstance(number, int) or isinstance(number, bool) or number < 0:
|
||||||
|
raise ValueError("missing/invalid wire statistic: " + field)
|
||||||
|
if sender["data_packets"] == 0:
|
||||||
|
raise ValueError("no TCP data packets observed")
|
||||||
|
record["repeated_sequences"] = sender["repeated_sequences"]
|
||||||
|
record["max_data_gap_ms"] = sender["max_data_gap_ms"]
|
||||||
|
return list(records.values())
|
||||||
|
|
||||||
|
|
||||||
|
def summarize(results):
|
||||||
|
groups = {}
|
||||||
|
for result in results:
|
||||||
|
for record in result.get("measurements", []):
|
||||||
|
groups.setdefault(key(record), []).append(record)
|
||||||
|
summary = []
|
||||||
|
for identity, records in sorted(groups.items()):
|
||||||
|
speeds = [record["mbps"] for record in records]
|
||||||
|
item = dict(zip(KEY_FIELDS, identity))
|
||||||
|
item.update(samples=len(records), median_mbps=statistics.median(speeds), min_mbps=min(speeds), max_mbps=max(speeds),
|
||||||
|
repeated_sequences=sum(r["repeated_sequences"] for r in records),
|
||||||
|
max_data_gap_ms=max(r["max_data_gap_ms"] for r in records))
|
||||||
|
if identity[0] == "mesh":
|
||||||
|
item["queue_drops"] = sum(r["queue_drops"] for r in records)
|
||||||
|
summary.append(item)
|
||||||
|
return summary
|
||||||
|
|
||||||
|
|
||||||
|
def validate_baseline(value):
|
||||||
|
if not isinstance(value, dict) or not isinstance(value.get("summary"), list) or not value["summary"]:
|
||||||
|
raise ValueError("baseline must be a metrics.json with a nonempty summary")
|
||||||
|
seen = set()
|
||||||
|
for item in value["summary"]:
|
||||||
|
try:
|
||||||
|
identity = key(item)
|
||||||
|
except (KeyError, TypeError) as error:
|
||||||
|
raise ValueError("baseline is missing measurement identity fields") from error
|
||||||
|
if any(not isinstance(item[field], str) or not item[field] for field in ("mode", "target", "entry", "direction")):
|
||||||
|
raise ValueError("baseline path fields must be nonempty strings")
|
||||||
|
if item["direction"] not in ("download", "upload") or any(not isinstance(item[field], int) or isinstance(item[field], bool) for field in ("rtt_ms", "mib")):
|
||||||
|
raise ValueError("baseline direction/RTT/size is invalid")
|
||||||
|
if identity in seen or not positive_number(item.get("median_mbps")):
|
||||||
|
raise ValueError("baseline contains duplicate groups or invalid speed")
|
||||||
|
seen.add(identity)
|
||||||
|
return value["summary"]
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(summary, policy):
|
||||||
|
issues = []
|
||||||
|
if not summary:
|
||||||
|
return ["no performance measurements"]
|
||||||
|
for item in summary:
|
||||||
|
label = "/".join(str(v) for v in key(item))
|
||||||
|
if item["samples"] != policy["repeats"]:
|
||||||
|
issues.append(label + ": incomplete repeat count")
|
||||||
|
if item["median_mbps"] < policy["min_mbps"]:
|
||||||
|
issues.append(f"{label}: median {item['median_mbps']:.2f} Mbps below {policy['min_mbps']:.2f}")
|
||||||
|
if item.get("queue_drops", 0) > policy["max_queue_drops"]:
|
||||||
|
issues.append(f"{label}: {item['queue_drops']} queue drops exceed {policy['max_queue_drops']}")
|
||||||
|
baseline = policy.get("baseline")
|
||||||
|
if baseline is not None:
|
||||||
|
before = {key(item): item for item in baseline}
|
||||||
|
after = {key(item): item for item in summary}
|
||||||
|
if set(before) != set(after):
|
||||||
|
issues.append("baseline groups differ (mode, target, entry, RTT, size or direction); comparison refused")
|
||||||
|
else:
|
||||||
|
for identity, item in after.items():
|
||||||
|
floor = before[identity]["median_mbps"] * (1 - policy["max_regression_percent"] / 100)
|
||||||
|
if item["median_mbps"] < floor:
|
||||||
|
issues.append(f"{identity}: median {item['median_mbps']:.2f} Mbps exceeds allowed baseline regression")
|
||||||
|
return issues
|
||||||
Executable
+350
@@ -0,0 +1,350 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Run MeshPort's local regression suites and write CI-friendly reports."""
|
||||||
|
import argparse
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shlex
|
||||||
|
import signal
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
import performance
|
||||||
|
import coexistence
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
SUITES = ("all", "runner", "sdk", "engine", "client", "macos", "throughput", "speed", "combined")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Step:
|
||||||
|
name: str
|
||||||
|
command: list
|
||||||
|
cwd: Path = ROOT
|
||||||
|
requires: tuple = ()
|
||||||
|
env: dict = field(default_factory=dict)
|
||||||
|
skip: str = ""
|
||||||
|
measurement: dict = field(default_factory=dict)
|
||||||
|
checks: dict = field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
def plan(suites, native=False, rtt_ms=58, mib=8, platform=sys.platform, rtts=(0, 58, 100), repeats=3, policy=None, joint=None):
|
||||||
|
selected = set(suites)
|
||||||
|
if "all" in selected:
|
||||||
|
selected.update(("runner", "sdk", "engine", "client", "macos"))
|
||||||
|
steps = []
|
||||||
|
cargo = ["sh", "scripts/cargo-local.sh"]
|
||||||
|
go = ["sh", "scripts/go-local.sh"]
|
||||||
|
if "runner" in selected:
|
||||||
|
steps.append(Step("runner-tests", [sys.executable, "-m", "unittest", "discover", "-s", "scripts/tests", "-p", "*_test.py"]))
|
||||||
|
if "sdk" in selected:
|
||||||
|
steps.append(Step("sdk", cargo + ["test", "--workspace", "--release", "--locked"]))
|
||||||
|
if "engine" in selected:
|
||||||
|
steps.extend([
|
||||||
|
Step("go-race", go + ["test", "-race", "./..."]),
|
||||||
|
Step("go-vet", go + ["vet", "./..."]),
|
||||||
|
Step("go-bridge-build", ["sh", "scripts/build-singbox.sh"]),
|
||||||
|
Step("go-sdk-bridge", cargo + ["test", "-p", "meshport-socks", "--release", "--locked",
|
||||||
|
"--test", "bridge", "singbox_to_meshport_tcp_udp_and_withdrawal", "--", "--ignored"],
|
||||||
|
requires=("go-bridge-build",),
|
||||||
|
env={"MESHPORT_SINGBOX_BIN": str(ROOT / "target/debug/meshport-singbox")}),
|
||||||
|
])
|
||||||
|
if "client" in selected:
|
||||||
|
app = ROOT / "apps/meshport_lab"
|
||||||
|
steps.extend([
|
||||||
|
Step("flutter-dependencies", ["flutter", "pub", "get"], cwd=app),
|
||||||
|
Step("flutter-analyze", ["flutter", "analyze"], cwd=app, requires=("flutter-dependencies",)),
|
||||||
|
])
|
||||||
|
dependencies = ("flutter-dependencies",)
|
||||||
|
env = {}
|
||||||
|
if native:
|
||||||
|
if platform != "darwin":
|
||||||
|
raise ValueError("--native currently requires macOS (the native build script targets macOS)")
|
||||||
|
steps.extend([
|
||||||
|
Step("client-rust-library", cargo + ["build", "-p", "meshport-ffi", "--locked"]),
|
||||||
|
Step("client-go-library", ["sh", "scripts/build-singbox-library.sh", "macos"]),
|
||||||
|
])
|
||||||
|
dependencies += ("client-rust-library", "client-go-library")
|
||||||
|
env = {
|
||||||
|
"MESHPORT_LIBRARY": str(ROOT / "target/debug/libmeshport_ffi.dylib"),
|
||||||
|
"MESHPORT_PROXY_LIBRARY": str(ROOT / "target/debug/libmeshport_proxy.dylib"),
|
||||||
|
}
|
||||||
|
steps.append(Step("flutter-tests", ["flutter", "test"], cwd=app, requires=dependencies, env=env))
|
||||||
|
if "macos" in selected:
|
||||||
|
steps.append(Step("macos-profile-storage", ["sh", "scripts/test-macos-profile-storage.sh"],
|
||||||
|
skip="requires macOS and Xcode command-line tools" if platform != "darwin" else ""))
|
||||||
|
if "throughput" in selected and "speed" not in selected:
|
||||||
|
common = {"MESHPORT_TEST_DELAY_MS": str(rtt_ms // 2), "MESHPORT_TEST_MIB": str(mib)}
|
||||||
|
for mode in ("channel", "udp"):
|
||||||
|
steps.append(Step("tcp-stack-" + mode, cargo + ["test", "-p", "meshport-socks", "--release",
|
||||||
|
"--locked", "--test", "tcp_stack_diagnostic", "sdk_tcp_stack_diagnostic",
|
||||||
|
"--", "--ignored", "--nocapture"], env={**common, "MESHPORT_TEST_LINK": mode},
|
||||||
|
measurement=dict(mode=mode, target="stack", entries=["direct"], rtt_ms=rtt_ms, mib=mib)))
|
||||||
|
steps.append(Step("sdk-throughput", cargo + ["test", "-p", "meshport-socks", "--release", "--locked",
|
||||||
|
"--test", "bridge", "subnet_throughput_diagnostic", "--", "--ignored", "--nocapture"],
|
||||||
|
env={**common, "MESHPORT_TEST_TARGET": "sdk", "MESHPORT_TEST_ENTRIES": "sdk",
|
||||||
|
"MESHPORT_TEST_TRACE_TCP": "1"},
|
||||||
|
measurement=dict(mode="mesh", target="sdk", entries=["sdk"], rtt_ms=rtt_ms, mib=mib)))
|
||||||
|
if "speed" in selected:
|
||||||
|
build = "go-bridge-build" if "engine" in selected else "speed-engine-build"
|
||||||
|
if "engine" not in selected:
|
||||||
|
steps.append(Step(build, ["sh", "scripts/build-singbox.sh"]))
|
||||||
|
measured = []
|
||||||
|
for rtt in rtts:
|
||||||
|
for repeat in range(1, repeats + 1):
|
||||||
|
common = {"MESHPORT_TEST_DELAY_MS": str(rtt // 2), "MESHPORT_TEST_MIB": str(mib)}
|
||||||
|
for mode in ("channel", "udp", "mesh"):
|
||||||
|
name = f"speed-{mode}-{rtt}ms-{repeat}"
|
||||||
|
measured.append(name)
|
||||||
|
spec = dict(mode=mode, target="sdk" if mode == "mesh" else "stack",
|
||||||
|
entries=["sdk", "socks", "singbox"] if mode == "mesh" else ["direct"],
|
||||||
|
rtt_ms=rtt, mib=mib, repeat=repeat)
|
||||||
|
if mode == "mesh":
|
||||||
|
command = cargo + ["test", "-p", "meshport-socks", "--release", "--locked", "--test", "bridge",
|
||||||
|
"subnet_throughput_diagnostic", "--", "--ignored", "--nocapture"]
|
||||||
|
env = {**common, "MESHPORT_TEST_TARGET": "sdk", "MESHPORT_TEST_ENTRIES": "sdk,socks,singbox",
|
||||||
|
"MESHPORT_TEST_TRACE_TCP": "1", "MESHPORT_SINGBOX_BIN": str(ROOT / "target/debug/meshport-singbox")}
|
||||||
|
requires = (build,)
|
||||||
|
else:
|
||||||
|
command = cargo + ["test", "-p", "meshport-socks", "--release", "--locked", "--test", "tcp_stack_diagnostic",
|
||||||
|
"sdk_tcp_stack_diagnostic", "--", "--ignored", "--nocapture"]
|
||||||
|
env = {**common, "MESHPORT_TEST_LINK": mode}
|
||||||
|
requires = ()
|
||||||
|
steps.append(Step(name, command, requires=requires, env=env, measurement=spec))
|
||||||
|
steps.append(Step("speed-check", [], requires=tuple(measured), checks=policy or
|
||||||
|
dict(repeats=repeats, min_mbps=0, max_queue_drops=0, baseline=None, max_regression_percent=20)))
|
||||||
|
if "combined" in selected:
|
||||||
|
if platform != "darwin":
|
||||||
|
raise ValueError("combined currently requires macOS (native Go shared library build)")
|
||||||
|
build = "client-go-library" if "client" in selected and native else "combined-go-library"
|
||||||
|
if build == "combined-go-library":
|
||||||
|
steps.append(Step(build, ["sh", "scripts/build-singbox-library.sh", "macos"]))
|
||||||
|
spec = joint or dict(duration_seconds=2, repeats=3, proxy_limit_mbps=100, max_slowdown_percent=20)
|
||||||
|
spec = {**spec, "rtt_ms": rtt_ms, "mode": "combined"}
|
||||||
|
steps.append(Step("combined-coexistence", cargo + ["test", "-p", "meshport-socks", "--release", "--locked",
|
||||||
|
"--test", "combined", "combined_coexistence", "--", "--ignored", "--nocapture"],
|
||||||
|
requires=(build,), measurement=spec,
|
||||||
|
env={"MESHPORT_PROXY_LIBRARY": str(ROOT / "target/debug/libmeshport_proxy.dylib"),
|
||||||
|
"MESHPORT_TEST_DELAY_MS": str(rtt_ms // 2),
|
||||||
|
"MESHPORT_JOINT_SECONDS": str(spec["duration_seconds"]),
|
||||||
|
"MESHPORT_JOINT_REPEATS": str(spec["repeats"]),
|
||||||
|
"MESHPORT_JOINT_PROXY_MBPS": str(spec["proxy_limit_mbps"])}))
|
||||||
|
return steps
|
||||||
|
|
||||||
|
|
||||||
|
def test_environment(overrides):
|
||||||
|
# Do not inherit user profiles, drain fixtures, old native libraries or
|
||||||
|
# diagnostic knobs. Every optional native/diagnostic input is set explicitly.
|
||||||
|
return {**{key: value for key, value in os.environ.items() if not key.startswith("MESHPORT_")}, **overrides}
|
||||||
|
|
||||||
|
|
||||||
|
def stop_process(process):
|
||||||
|
if process.poll() is not None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
if os.name == "posix":
|
||||||
|
os.killpg(process.pid, signal.SIGTERM)
|
||||||
|
else:
|
||||||
|
process.terminate()
|
||||||
|
except ProcessLookupError:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
process.wait(timeout=5)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
if os.name == "posix":
|
||||||
|
os.killpg(process.pid, signal.SIGKILL)
|
||||||
|
else:
|
||||||
|
process.kill()
|
||||||
|
process.wait()
|
||||||
|
|
||||||
|
|
||||||
|
def execute(step, directory, timeout):
|
||||||
|
log = directory / (step.name + ".log")
|
||||||
|
start = time.monotonic()
|
||||||
|
result = {"name": step.name, "command": step.command, "cwd": str(step.cwd), "log": str(log)}
|
||||||
|
print("RUN " + step.name + " " + shlex.join(step.command), flush=True)
|
||||||
|
process = None
|
||||||
|
try:
|
||||||
|
with log.open("w", encoding="utf-8") as output:
|
||||||
|
process = subprocess.Popen(step.command, cwd=step.cwd, env=test_environment(step.env),
|
||||||
|
stdout=output, stderr=subprocess.STDOUT, start_new_session=os.name == "posix")
|
||||||
|
try:
|
||||||
|
code = process.wait(timeout=timeout)
|
||||||
|
result.update(status="passed" if code == 0 else "failed", exit_code=code)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
stop_process(process)
|
||||||
|
result.update(status="failed", exit_code=124, reason=f"timeout after {timeout} seconds")
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
stop_process(process)
|
||||||
|
result.update(status="failed", exit_code=130, reason="interrupted")
|
||||||
|
except OSError as error:
|
||||||
|
log.write_text(str(error) + "\n", encoding="utf-8")
|
||||||
|
result.update(status="failed", exit_code=127, reason=str(error))
|
||||||
|
result["seconds"] = round(time.monotonic() - start, 3)
|
||||||
|
if step.measurement and result["status"] == "passed":
|
||||||
|
try:
|
||||||
|
content = log.read_text(encoding="utf-8", errors="replace")
|
||||||
|
if step.measurement.get("mode") == "combined":
|
||||||
|
result["joint_results"] = coexistence.parse(content, step.measurement)
|
||||||
|
if result["joint_results"]["issues"]:
|
||||||
|
result.update(status="failed", command_exit_code=0, exit_code=1,
|
||||||
|
reason="; ".join(result["joint_results"]["issues"]))
|
||||||
|
else:
|
||||||
|
result["measurements"] = performance.parse(content, step.measurement)
|
||||||
|
except (ValueError, KeyError, TypeError) as error:
|
||||||
|
result.update(status="failed", command_exit_code=0, exit_code=1, reason="invalid speed result: " + str(error))
|
||||||
|
print(("PASS " if result["status"] == "passed" else "FAIL ") + step.name + f" ({result['seconds']:.1f}s)", flush=True)
|
||||||
|
if result["status"] == "failed":
|
||||||
|
if "reason" in result:
|
||||||
|
print(result["reason"], flush=True)
|
||||||
|
print("\n".join(log.read_text(encoding="utf-8", errors="replace").splitlines()[-20:]), flush=True)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def run(steps, directory, timeout=900, fail_fast=False):
|
||||||
|
directory.mkdir(parents=True, exist_ok=False)
|
||||||
|
results = []
|
||||||
|
stopped = False
|
||||||
|
for step in steps:
|
||||||
|
previous = {result["name"]: result["status"] for result in results}
|
||||||
|
blocked = [name for name in step.requires if previous.get(name) != "passed"]
|
||||||
|
reason = step.skip or ("run stopped after failure" if stopped else "")
|
||||||
|
if not reason and blocked:
|
||||||
|
reason = "prerequisite did not pass: " + ", ".join(blocked)
|
||||||
|
if reason:
|
||||||
|
results.append({"name": step.name, "status": "skipped", "reason": reason, "seconds": 0})
|
||||||
|
print("SKIP " + step.name + " " + reason, flush=True)
|
||||||
|
continue
|
||||||
|
if step.checks:
|
||||||
|
issues = performance.evaluate(performance.summarize(results), step.checks)
|
||||||
|
log = directory / (step.name + ".log")
|
||||||
|
log.write_text("\n".join(issues) + "\n" if issues else "All configured speed criteria passed.\n", encoding="utf-8")
|
||||||
|
result = dict(name=step.name, status="failed" if issues else "passed", exit_code=1 if issues else 0,
|
||||||
|
seconds=0, log=str(log), criteria=step.checks)
|
||||||
|
if issues:
|
||||||
|
result["reason"] = "; ".join(issues)
|
||||||
|
print(("FAIL " if issues else "PASS ") + step.name, flush=True)
|
||||||
|
for issue in issues:
|
||||||
|
print(issue, flush=True)
|
||||||
|
else:
|
||||||
|
result = execute(step, directory, timeout)
|
||||||
|
results.append(result)
|
||||||
|
stopped = stopped or result.get("exit_code") == 130 or (fail_fast and result["status"] == "failed")
|
||||||
|
write_reports(results, directory)
|
||||||
|
write_reports(results, directory)
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def write_reports(results, directory):
|
||||||
|
for result in results:
|
||||||
|
if "joint_results" in result:
|
||||||
|
(directory / "combined-metrics.json").write_text(json.dumps(result["joint_results"], indent=2) + "\n", encoding="utf-8")
|
||||||
|
(directory / "combined-summary.md").write_text(coexistence.markdown(result["joint_results"]), encoding="utf-8")
|
||||||
|
measurements = [record for result in results for record in result.get("measurements", [])]
|
||||||
|
if measurements:
|
||||||
|
summary = performance.summarize(results)
|
||||||
|
(directory / "metrics.json").write_text(json.dumps(dict(measurements=measurements, summary=summary), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||||
|
table = ["# Local synthetic speed results", "", "RTT is added round-trip delay; these are local fixtures, not WAN speed measurements.", "",
|
||||||
|
"| Path | RTT ms | MiB/direction | Direction | Samples | Median Mbps | Min | Max | Queue drops |",
|
||||||
|
"|---|---:|---:|---|---:|---:|---:|---:|---:|"]
|
||||||
|
for item in summary:
|
||||||
|
path = item["mode"] + "/" + item["target"] + "/" + item["entry"]
|
||||||
|
table.append(f"| {path} | {item['rtt_ms']} | {item['mib']} | {item['direction']} | {item['samples']} | {item['median_mbps']:.2f} | {item['min_mbps']:.2f} | {item['max_mbps']:.2f} | {item.get('queue_drops', 'n/a')} |")
|
||||||
|
(directory / "speed-summary.md").write_text("\n".join(table) + "\n", encoding="utf-8")
|
||||||
|
(directory / "report.json").write_text(json.dumps({"steps": results}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||||
|
suite = ET.Element("testsuite", name="meshport", tests=str(len(results)),
|
||||||
|
failures=str(sum(r["status"] == "failed" for r in results)),
|
||||||
|
skipped=str(sum(r["status"] == "skipped" for r in results)))
|
||||||
|
for result in results:
|
||||||
|
case = ET.SubElement(suite, "testcase", name=result["name"], classname="meshport.automation", time=str(result["seconds"]))
|
||||||
|
if result["status"] == "skipped":
|
||||||
|
ET.SubElement(case, "skipped", message=result["reason"])
|
||||||
|
elif result["status"] == "failed":
|
||||||
|
ET.SubElement(case, "failure", message=result.get("reason", f"exit code {result['exit_code']}"))
|
||||||
|
if "log" in result:
|
||||||
|
ET.SubElement(case, "system-out").text = result["log"]
|
||||||
|
ET.ElementTree(suite).write(directory / "junit.xml", encoding="utf-8", xml_declaration=True)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("suites", nargs="*", metavar="SUITE", help=", ".join(SUITES) + " (default: all)")
|
||||||
|
parser.add_argument("--native", action="store_true", help="build macOS native libraries for Flutter tests")
|
||||||
|
parser.add_argument("--list", action="store_true", help="print commands without running them")
|
||||||
|
parser.add_argument("--fail-fast", action="store_true")
|
||||||
|
parser.add_argument("--timeout", type=int, default=900, help="timeout per command in seconds (default: 900)")
|
||||||
|
parser.add_argument("--rtt-ms", type=int, default=58, help="even simulated RTT, 0..1000, for throughput/combined")
|
||||||
|
parser.add_argument("--joint-seconds", type=int, default=2, help="combined duration per flow, 1..5")
|
||||||
|
parser.add_argument("--joint-repeat", type=int, default=3, help="combined repeats, 1..10")
|
||||||
|
parser.add_argument("--proxy-mbps", type=int, default=100, help="combined proxy fixture limit; 0 means unlimited")
|
||||||
|
parser.add_argument("--max-joint-slowdown-percent", type=float, default=20, help="maximum median slowdown between combined phases")
|
||||||
|
parser.add_argument("--mib", type=int, default=8, help="data per direction in MiB, 1..64, for throughput/speed")
|
||||||
|
parser.add_argument("--rtts-ms", default="0,58,100", help="comma-separated even RTTs for speed matrix")
|
||||||
|
parser.add_argument("--repeat", type=int, default=3, help="speed matrix repeats per RTT, 1..10")
|
||||||
|
parser.add_argument("--min-mbps", type=float, default=0, help="minimum group median for speed checks; default: no absolute floor")
|
||||||
|
parser.add_argument("--max-queue-drops", type=int, default=0, help="maximum queue drops per speed group across repeats")
|
||||||
|
parser.add_argument("--baseline", type=Path, help="previous metrics.json for matching speed groups")
|
||||||
|
parser.add_argument("--max-regression-percent", type=float, default=20, help="maximum median drop from baseline")
|
||||||
|
parser.add_argument("--log-dir", type=Path, help="new report directory; must not already exist")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
args.suites = args.suites or ["all"]
|
||||||
|
if set(args.suites) - set(SUITES):
|
||||||
|
parser.error("unknown suite; choose from: " + ", ".join(SUITES))
|
||||||
|
if args.native and not set(args.suites).intersection({"all", "client"}):
|
||||||
|
parser.error("--native requires the client or all suite")
|
||||||
|
if args.timeout <= 0 or not 0 <= args.rtt_ms <= 1000 or args.rtt_ms % 2 or not 1 <= args.mib <= 64:
|
||||||
|
parser.error("timeout must be positive; RTT must be even and 0..1000; MiB must be 1..64")
|
||||||
|
try:
|
||||||
|
import math
|
||||||
|
if not 1 <= args.joint_seconds <= 5 or not 1 <= args.joint_repeat <= 10 or not 0 <= args.proxy_mbps <= 100000:
|
||||||
|
raise ValueError("joint seconds must be 1..5, repeats 1..10, proxy Mbps 0..100000")
|
||||||
|
if not math.isfinite(args.max_joint_slowdown_percent) or not 0 <= args.max_joint_slowdown_percent < 100:
|
||||||
|
raise ValueError("joint slowdown percent must be finite and in 0..<100")
|
||||||
|
if "combined" not in args.suites and (args.joint_seconds != 2 or args.joint_repeat != 3 or args.proxy_mbps != 100 or args.max_joint_slowdown_percent != 20):
|
||||||
|
raise ValueError("joint options require the combined suite")
|
||||||
|
rtts = tuple(int(value) for value in args.rtts_ms.split(","))
|
||||||
|
if not rtts or len(set(rtts)) != len(rtts) or any(not 0 <= value <= 1000 or value % 2 for value in rtts):
|
||||||
|
raise ValueError("speed RTTs must be distinct even integers in 0..1000")
|
||||||
|
if not 1 <= args.repeat <= 10 or not math.isfinite(args.min_mbps) or args.min_mbps < 0 or args.max_queue_drops < 0:
|
||||||
|
raise ValueError("repeat must be 1..10; speed and queue-drop limits must be nonnegative and finite")
|
||||||
|
if not math.isfinite(args.max_regression_percent) or not 0 <= args.max_regression_percent < 100:
|
||||||
|
raise ValueError("maximum regression percent must be finite and in 0..<100")
|
||||||
|
if "speed" not in args.suites and (args.min_mbps != 0 or args.max_queue_drops != 0 or args.repeat != 3 or
|
||||||
|
args.rtts_ms != "0,58,100" or args.max_regression_percent != 20):
|
||||||
|
raise ValueError("matrix/gate options require the speed suite")
|
||||||
|
if args.baseline and "speed" not in args.suites:
|
||||||
|
raise ValueError("--baseline requires the speed suite")
|
||||||
|
baseline = performance.validate_baseline(json.loads(args.baseline.read_text())) if args.baseline else None
|
||||||
|
policy = dict(repeats=args.repeat, min_mbps=args.min_mbps, max_queue_drops=args.max_queue_drops,
|
||||||
|
baseline=baseline, max_regression_percent=args.max_regression_percent)
|
||||||
|
joint = dict(duration_seconds=args.joint_seconds, repeats=args.joint_repeat,
|
||||||
|
proxy_limit_mbps=args.proxy_mbps, max_slowdown_percent=args.max_joint_slowdown_percent)
|
||||||
|
steps = plan(args.suites, args.native, args.rtt_ms, args.mib, rtts=rtts, repeats=args.repeat, policy=policy, joint=joint)
|
||||||
|
except (OSError, json.JSONDecodeError) as error:
|
||||||
|
parser.error("cannot read baseline: " + str(error))
|
||||||
|
except ValueError as error:
|
||||||
|
parser.error(str(error))
|
||||||
|
if args.list:
|
||||||
|
for step in steps:
|
||||||
|
print(step.name + ": " + ("SKIP " + step.skip if step.skip else shlex.join(step.command) if step.command else "evaluate medians, drop counts and optional baseline"))
|
||||||
|
return 0
|
||||||
|
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||||
|
directory = (args.log_dir or ROOT / "outputs/validation/automated-tests" / (stamp + "-" + uuid.uuid4().hex[:8])).resolve()
|
||||||
|
if directory.exists():
|
||||||
|
parser.error("report directory already exists: " + str(directory))
|
||||||
|
print("Reports: " + str(directory), flush=True)
|
||||||
|
results = run(steps, directory, args.timeout, args.fail_fast)
|
||||||
|
counts = {state: sum(r["status"] == state for r in results) for state in ("passed", "failed", "skipped")}
|
||||||
|
print("Summary: " + ", ".join(f"{number} {state}" for state, number in counts.items()), flush=True)
|
||||||
|
print("Report: " + str(directory / "report.json"), flush=True)
|
||||||
|
if any(r.get("exit_code") == 130 for r in results):
|
||||||
|
return 130
|
||||||
|
return 1 if counts["failed"] else 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
import coexistence
|
||||||
|
import test as runner
|
||||||
|
|
||||||
|
SPEC = dict(mode="combined", duration_seconds=2, repeats=3, proxy_limit_mbps=100,
|
||||||
|
rtt_ms=58, max_slowdown_percent=20)
|
||||||
|
|
||||||
|
|
||||||
|
def fixture(concurrent=1):
|
||||||
|
flows = []
|
||||||
|
for phase, lane in coexistence.PHASES:
|
||||||
|
for direction in ("download", "upload"):
|
||||||
|
for repeat in range(1, 4):
|
||||||
|
rate = (60 if lane == "mesh" else 100) * (concurrent if phase == "concurrent" else 1)
|
||||||
|
flows.append(dict(mode="combined_flow", phase=phase, lane=lane, direction=direction,
|
||||||
|
repeat=repeat, bytes=rate * 1e6 / 8 * 2, seconds=2, mbps=rate,
|
||||||
|
overlap_ms=1900 if phase == "concurrent" else 0))
|
||||||
|
functional = dict(mode="combined_functional", **{k: True for k in coexistence.FLAGS},
|
||||||
|
repeats=3, duration_seconds=2, rtt_ms=58, proxy_limit_mbps=100, udp_probes_per_lane=24)
|
||||||
|
return flows + [functional]
|
||||||
|
|
||||||
|
|
||||||
|
def log(records):
|
||||||
|
return "\n".join(json.dumps(r) for r in records)
|
||||||
|
|
||||||
|
|
||||||
|
class CoexistenceTest(unittest.TestCase):
|
||||||
|
def test_complete_results_and_comparisons(self):
|
||||||
|
result = coexistence.parse(log(fixture()), SPEC)
|
||||||
|
self.assertEqual(len(result["measurements"]), 36)
|
||||||
|
self.assertEqual(len(result["summary"]), 12)
|
||||||
|
self.assertEqual(len(result["comparisons"]), 12)
|
||||||
|
self.assertEqual(result["issues"], [])
|
||||||
|
self.assertIn("concurrent_vs_idle", coexistence.markdown(result))
|
||||||
|
|
||||||
|
def test_rejects_missing_duplicate_and_unfinished_results(self):
|
||||||
|
records = fixture()
|
||||||
|
for bad in (records[:-1], records[1:], records + [records[0]], []):
|
||||||
|
with self.subTest(count=len(bad)), self.assertRaises(ValueError):
|
||||||
|
coexistence.parse(log(bad), SPEC)
|
||||||
|
|
||||||
|
def test_rejects_bad_duration_rate_overlap_and_nonfinite_values(self):
|
||||||
|
for replacement in (dict(seconds=.1), dict(mbps=0), dict(bytes=float("nan")),
|
||||||
|
dict(mbps=99), dict(overlap_ms=-1)):
|
||||||
|
records = fixture()
|
||||||
|
records[0].update(replacement)
|
||||||
|
with self.subTest(replacement=replacement), self.assertRaises(ValueError):
|
||||||
|
coexistence.parse(log(records), SPEC)
|
||||||
|
records = fixture()
|
||||||
|
next(r for r in records if r.get("phase") == "concurrent")["overlap_ms"] = 100
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
coexistence.parse(log(records), SPEC)
|
||||||
|
|
||||||
|
def test_requires_fault_checks_config_and_concurrent_udp_evidence(self):
|
||||||
|
for replacement in (dict(mesh_survives_proxy_stop=False), dict(proxy_survives_mesh_stop=1),
|
||||||
|
dict(repeats=1), dict(udp_probes_per_lane=1), dict(rtt_ms=0)):
|
||||||
|
records = fixture()
|
||||||
|
records[-1].update(replacement)
|
||||||
|
with self.subTest(replacement=replacement), self.assertRaises(ValueError):
|
||||||
|
coexistence.parse(log(records), SPEC)
|
||||||
|
|
||||||
|
def test_slowdown_fails_command_and_preserves_measurements(self):
|
||||||
|
step = runner.Step("joint", [sys.executable, "-c", "print(" + repr(log(fixture(.5))) + ")"], measurement=SPEC)
|
||||||
|
with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
directory = Path(temporary) / "run"
|
||||||
|
results = runner.run([step], directory)
|
||||||
|
self.assertEqual(results[0]["status"], "failed")
|
||||||
|
self.assertIn("slowdown", results[0]["reason"])
|
||||||
|
self.assertTrue((directory / "combined-summary.md").exists())
|
||||||
|
self.assertEqual(len(json.loads((directory / "combined-metrics.json").read_text())["measurements"]), 36)
|
||||||
|
|
||||||
|
def test_plan_reuses_native_build_and_rejects_unsupported_platform(self):
|
||||||
|
steps = runner.plan(["all", "combined"], native=True, platform="darwin")
|
||||||
|
combined = steps[-1]
|
||||||
|
self.assertEqual(combined.requires, ("client-go-library",))
|
||||||
|
self.assertEqual(combined.env["MESHPORT_JOINT_REPEATS"], "3")
|
||||||
|
self.assertNotIn("combined-go-library", [s.name for s in steps])
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
runner.plan(["combined"], platform="linux")
|
||||||
|
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
|
||||||
|
runner.main(["all", "--proxy-mbps", "0", "--list"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import contextlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
import performance
|
||||||
|
import test as runner
|
||||||
|
|
||||||
|
|
||||||
|
def fixture(speed=20, drops=0, entries=("sdk",)):
|
||||||
|
lines = []
|
||||||
|
for entry in entries:
|
||||||
|
for direction in ("download", "upload"):
|
||||||
|
lines.append(f"sdk entry={entry} added_rtt_ms=58 direction={direction} mib=8 mbps={speed}")
|
||||||
|
wire = dict(data_packets=100, repeated_sequences=2, max_data_gap_ms=60)
|
||||||
|
lines.append(json.dumps(dict(mode="easytier_encrypted_relay", target="sdk", entry=entry, direction=direction,
|
||||||
|
client_wire_at_relay=wire, server_wire_at_relay=wire, udp_session_queue_full_drops=drops)))
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
SPEC = dict(mode="mesh", target="sdk", entries=["sdk"], rtt_ms=58, mib=8)
|
||||||
|
|
||||||
|
|
||||||
|
class PerformanceTest(unittest.TestCase):
|
||||||
|
def test_extracts_each_path_and_both_directions(self):
|
||||||
|
entries = ["sdk", "socks", "singbox"]
|
||||||
|
records = performance.parse(fixture(entries=entries), {**SPEC, "entries": entries})
|
||||||
|
self.assertEqual(len(records), 6)
|
||||||
|
self.assertEqual({r["entry"] for r in records}, set(entries))
|
||||||
|
self.assertTrue(all(r["repeated_sequences"] == 2 and r["queue_drops"] == 0 for r in records))
|
||||||
|
|
||||||
|
def test_rejects_missing_duplicate_mismatched_and_zero_results(self):
|
||||||
|
good = fixture()
|
||||||
|
invalid = ["", "\n".join(good.splitlines()[:2]), good + "\n" + good,
|
||||||
|
good.replace("added_rtt_ms=58", "added_rtt_ms=100"), fixture(speed=0),
|
||||||
|
"\n".join(line for line in good.splitlines() if not line.startswith("{"))]
|
||||||
|
for text in invalid:
|
||||||
|
with self.subTest(text=text[:80]), self.assertRaises(ValueError):
|
||||||
|
performance.parse(text, SPEC)
|
||||||
|
|
||||||
|
def test_checks_group_median_drops_and_baseline(self):
|
||||||
|
results = [dict(measurements=performance.parse(fixture(speed=v), SPEC)) for v in (10, 20, 90)]
|
||||||
|
summary = performance.summarize(results)
|
||||||
|
self.assertTrue(all(item["median_mbps"] == 20 and item["samples"] == 3 for item in summary))
|
||||||
|
policy = dict(repeats=3, min_mbps=15, max_queue_drops=0, baseline=None, max_regression_percent=20)
|
||||||
|
self.assertEqual(performance.evaluate(summary, policy), [])
|
||||||
|
self.assertTrue(performance.evaluate(summary, {**policy, "min_mbps": 25}))
|
||||||
|
with_drops = [{**item, "queue_drops": 1} for item in summary]
|
||||||
|
self.assertTrue(performance.evaluate(with_drops, policy))
|
||||||
|
baseline = [{**item, "median_mbps": 30} for item in summary]
|
||||||
|
self.assertTrue(performance.evaluate(summary, {**policy, "baseline": baseline}))
|
||||||
|
mismatch = [{**item, "mib": 2} for item in baseline]
|
||||||
|
self.assertIn("comparison refused", " ".join(performance.evaluate(summary, {**policy, "baseline": mismatch})))
|
||||||
|
|
||||||
|
def test_validates_baseline_and_finite_values(self):
|
||||||
|
records = performance.parse(fixture(), SPEC)
|
||||||
|
summary = performance.summarize([dict(measurements=records)])
|
||||||
|
self.assertEqual(performance.validate_baseline(dict(summary=summary)), summary)
|
||||||
|
for bad in ({}, dict(summary=[]), dict(summary=summary + summary), dict(summary=[{**summary[0], "mode": []}]),
|
||||||
|
dict(summary=[{**summary[0], "median_mbps": float("nan") }])):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
performance.validate_baseline(bad)
|
||||||
|
|
||||||
|
def test_successful_command_with_missing_measurements_is_a_failure(self):
|
||||||
|
step = runner.Step("empty", [sys.executable, "-c", "print('success, but no measurements')"], measurement=SPEC)
|
||||||
|
with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
result = runner.execute(step, Path(temporary), 5)
|
||||||
|
self.assertEqual(result["command_exit_code"], 0)
|
||||||
|
self.assertEqual(result["status"], "failed")
|
||||||
|
|
||||||
|
def test_speed_gate_failure_produces_reports_even_after_command_success(self):
|
||||||
|
spec = dict(SPEC)
|
||||||
|
steps = [runner.Step("measured", [sys.executable, "-c", "print(" + repr(fixture(speed=2)) + ")"], measurement=spec),
|
||||||
|
runner.Step("speed-check", [], requires=("measured",), checks=dict(repeats=1, min_mbps=10,
|
||||||
|
max_queue_drops=0, baseline=None, max_regression_percent=20))]
|
||||||
|
with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
directory = Path(temporary) / "run"
|
||||||
|
results = runner.run(steps, directory)
|
||||||
|
self.assertEqual([r["status"] for r in results], ["passed", "failed"])
|
||||||
|
metrics = json.loads((directory / "metrics.json").read_text())
|
||||||
|
self.assertEqual(metrics["summary"][0]["median_mbps"], 2)
|
||||||
|
self.assertIn("below", (directory / "speed-check.log").read_text())
|
||||||
|
self.assertTrue((directory / "speed-summary.md").exists())
|
||||||
|
|
||||||
|
def test_speed_plan_covers_matrix_and_deduplicates_throughput(self):
|
||||||
|
steps = runner.plan(["speed", "throughput"], rtts=(0, 58, 100), repeats=3)
|
||||||
|
measured = [s for s in steps if s.measurement]
|
||||||
|
self.assertEqual(len(measured), 27)
|
||||||
|
self.assertEqual(steps[-1].name, "speed-check")
|
||||||
|
self.assertEqual(len(steps[-1].requires), 27)
|
||||||
|
|
||||||
|
def test_gate_options_cannot_silently_run_functional_tests_only(self):
|
||||||
|
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as error:
|
||||||
|
runner.main(["all", "--min-mbps", "10", "--list"])
|
||||||
|
self.assertEqual(error.exception.code, 2)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import contextlib
|
||||||
|
import importlib.util
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
|
||||||
|
spec = importlib.util.spec_from_file_location("meshport_test_runner", Path(__file__).resolve().parents[1] / "test.py")
|
||||||
|
runner = importlib.util.module_from_spec(spec)
|
||||||
|
sys.modules[spec.name] = runner
|
||||||
|
spec.loader.exec_module(runner)
|
||||||
|
|
||||||
|
|
||||||
|
class RunnerTest(unittest.TestCase):
|
||||||
|
def test_default_plan_excludes_throughput_and_native_builds(self):
|
||||||
|
steps = runner.plan(["all"], platform="darwin")
|
||||||
|
names = {step.name for step in steps}
|
||||||
|
self.assertTrue({"sdk", "go-race", "go-vet", "go-sdk-bridge", "flutter-tests", "macos-profile-storage"} <= names)
|
||||||
|
self.assertNotIn("sdk-throughput", names)
|
||||||
|
self.assertNotIn("client-rust-library", names)
|
||||||
|
self.assertIn("sdk", self.list_default())
|
||||||
|
|
||||||
|
def list_default(self):
|
||||||
|
with contextlib.redirect_stdout(io.StringIO()) as output:
|
||||||
|
self.assertEqual(runner.main(["--list"]), 0)
|
||||||
|
return output.getvalue()
|
||||||
|
|
||||||
|
def test_native_tests_depend_on_both_new_libraries(self):
|
||||||
|
step = next(s for s in runner.plan(["client"], native=True, platform="darwin") if s.name == "flutter-tests")
|
||||||
|
self.assertIn("client-rust-library", step.requires)
|
||||||
|
self.assertIn("client-go-library", step.requires)
|
||||||
|
self.assertTrue(step.env["MESHPORT_LIBRARY"].endswith("libmeshport_ffi.dylib"))
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
runner.plan(["client"], native=True, platform="linux")
|
||||||
|
|
||||||
|
def test_removes_inherited_profiles_and_diagnostic_inputs(self):
|
||||||
|
with patch.dict(os.environ, {"MESHPORT_DRAIN_PROFILE": "private.json", "MESHPORT_LIBRARY": "old.dylib", "MESHPORT_TEST_DELAY_MS": "999"}):
|
||||||
|
env = runner.test_environment({"MESHPORT_LIBRARY": "new.dylib"})
|
||||||
|
self.assertEqual(env["MESHPORT_LIBRARY"], "new.dylib")
|
||||||
|
self.assertNotIn("MESHPORT_DRAIN_PROFILE", env)
|
||||||
|
self.assertNotIn("MESHPORT_TEST_DELAY_MS", env)
|
||||||
|
|
||||||
|
def test_failure_skips_dependents_but_runs_independent_steps_and_reports(self):
|
||||||
|
steps = [
|
||||||
|
runner.Step("failure", [sys.executable, "-c", "print('失败日志'); raise SystemExit(7)"]),
|
||||||
|
runner.Step("dependent", [sys.executable, "-c", "raise SystemExit(99)"], requires=("failure",)),
|
||||||
|
runner.Step("independent", [sys.executable, "-c", "print('ok')"]),
|
||||||
|
]
|
||||||
|
with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
directory = Path(temporary) / "run"
|
||||||
|
results = runner.run(steps, directory)
|
||||||
|
self.assertEqual([r["status"] for r in results], ["failed", "skipped", "passed"])
|
||||||
|
self.assertEqual(results[0]["exit_code"], 7)
|
||||||
|
self.assertIn("失败日志", (directory / "failure.log").read_text())
|
||||||
|
self.assertEqual(len(json.loads((directory / "report.json").read_text())["steps"]), 3)
|
||||||
|
xml = ET.parse(directory / "junit.xml").getroot()
|
||||||
|
self.assertEqual(xml.attrib["failures"], "1")
|
||||||
|
self.assertEqual(xml.attrib["skipped"], "1")
|
||||||
|
|
||||||
|
def test_fail_fast_and_timeout(self):
|
||||||
|
steps = [runner.Step("timeout", [sys.executable, "-c", "import time; time.sleep(10)"]),
|
||||||
|
runner.Step("later", [sys.executable, "-c", "pass"])]
|
||||||
|
with tempfile.TemporaryDirectory() as temporary, contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
results = runner.run(steps, Path(temporary) / "run", timeout=0.05, fail_fast=True)
|
||||||
|
self.assertEqual(results[0]["exit_code"], 124)
|
||||||
|
self.assertEqual(results[1]["status"], "skipped")
|
||||||
|
|
||||||
|
def test_main_returns_failure_exit_code(self):
|
||||||
|
result = [{"name": "failed", "status": "failed", "exit_code": 3}]
|
||||||
|
with tempfile.TemporaryDirectory() as temporary, patch.object(runner, "run", return_value=result), contextlib.redirect_stdout(io.StringIO()):
|
||||||
|
self.assertEqual(runner.main(["sdk", "--log-dir", str(Path(temporary) / "run")]), 1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user