合并 网络质量探测 1.1.2

将 release/1.1.2 合入 main。
署名:言灸
This commit is contained in:
YanJiu committed 2026-11-20 19:03:57 +08:00
commit d31f30c048
41 files changed
+3835 -553

No files matched your search

+13 -3
View File
@@ -63,7 +63,15 @@ flutter run -d linux
3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。 3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。
4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。 4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。
本机的 UDP 探测会记下这次解析出的每个地址。结果上的「发往」是当前实际在用的地址。还没有哪个地址应答时,一个超时就换下一个;已经有应答之后,要连续三次没有应答才换,中途开关 VPN 不会把还在应答的地址丢掉。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。 本机的 UDP 探测会记下这次解析出的每个地址。结果上的「实际地址」是真正发包或连通的地址,并注明 IPv4 或 IPv6。域名解析出来的地址单独标成「解析到」,不会被说成已经在用。还没有哪个地址应答时,一次失败就换下一个,这次失败不计入正式丢包,界面会说明回退;已经有应答之后,超时算正式结果,要连续三次没有应答才换。全部地址都失败时显示失败,不会显示 0% 成功。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。
远程节点从 1.1.2 起会在每条结果里带上实际地址。更早的节点没有这个字段时,界面写明「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。1.1.1 的节点仍会把选址失败算进统计。
端口框写着当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。
已有远程节点可以改名称、控制地址和口令。节点编号和当前选择不变。口令留空表示不改,界面不显示已经保存的口令。
手动停止后曲线还在,并给出这次的开始、结束、用时和最终指标。停止时还没完成的请求不算丢包。点曲线可以钉住该时刻,松手后仍然保留。指标的算法在应用里的「指标说明」,版本记录在「更新历史」。
节点口令保存在本机应用目录里,权限尽量收成只有自己能读,不会写进网址或日志。 节点口令保存在本机应用目录里,权限尽量收成只有自己能读,不会写进网址或日志。
@@ -96,10 +104,12 @@ cd server && go test -race ./...
cd client && flutter analyze && flutter test cd client && flutter analyze && flutter test
``` ```
Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.1`。 Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.2`,构建号 `5`。
这一版的说明在 [docs/release-notes/1.1.2.md](docs/release-notes/1.1.2.md)。
## 许可 ## 许可
Copyright (C) 2026 灸 言 Copyright (C) 2026 言灸
本项目以 GNU Affero General Public License v3.0 许可(SPDX 标识:AGPL-3.0-only)。你可以在遵守该许可的前提下使用、修改和分发。完整条款见仓库根目录的 [LICENSE](LICENSE)。 本项目以 GNU Affero General Public License v3.0 许可(SPDX 标识:AGPL-3.0-only)。你可以在遵守该许可的前提下使用、修改和分发。完整条款见仓库根目录的 [LICENSE](LICENSE)。
+1 -1
View File
@@ -7,4 +7,4 @@ flutter pub get
flutter run -d linux flutter run -d linux
``` ```
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。 默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。合作反射 UDP 默认 `19091`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。当前版本是 1.1.2。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。
+55
View File
@@ -0,0 +1,55 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
/// Versions that exist as this release or as a real Git tag / GitHub Release.
/// Unpublished earlier behavior mentioned inside the 1.1.1 notes is not given
/// its own entry.
class ReleaseEntry {
const ReleaseEntry({
required this.version,
required this.title,
required this.source,
required this.points,
this.published,
});
final String version;
final String title;
final String source;
final String? published;
final List<String> points;
}
const releaseHistory = <ReleaseEntry>[
ReleaseEntry(
version: '1.1.2',
title: '网络质量探测 1.1.2',
source: '仓库 docs/release-notes/1.1.2.md。这一版的 Git 标签要等发布时才有,这里写的是即将发布的内容。',
points: [
'可以修改已有远程节点的名称、控制地址和口令。节点编号和当前选择保持不变。口令留空表示不改,界面不显示已经保存的口令。',
'端口框标明当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。',
'本机和远程节点都显示实际连通或实际发包的地址,以及 IPv4 / IPv6。旧节点如果没有上报地址,会写明未报告,不会把域名解析的第一个地址当成已经使用的地址。',
'选址阶段失败的候选(例如 IPv6 没有应答后改用 IPv4)不再计入正式丢包,并单独说明回退。选定地址之后的失败仍然计入。全部候选都失败时显示失败,不会显示 0% 成功。',
'结果给出已发送、已收到、超时、比率、当前/最小/平均/中位/P95/最大延迟、抖动和用时。某种探测没有测量的量会标成不适用或 —。',
'手动停止后保留曲线,并给出开始、结束、用时、目标、来源、实际地址和最终指标。停止时还没完成的请求不计入丢包。',
'点曲线可以钉住该时刻的数值,松手后仍然保留;再点另一点会更换。新的一次探测,或该点滚出窗口后,不会沿用过期选择。',
'新增「指标说明」。',
],
),
ReleaseEntry(
version: '1.1.1',
title: '网络质量探测 1.1.1',
published: '2026-11-09',
source: 'Git 标签 v1.1.1,以及 GitHub Release「网络质量探测 1.1.1」(发布于 2026-11-09,之后补过桌面和节点压缩包)。',
points: [
'本机 UDP 会把解析出的地址逐个试过,停在第一个真正有应答的地址上。',
'还没有地址应答时,一次超时就换下一个。已经有应答之后,要连续 3 次没有应答才换。',
'结果里显示当时实际在用的地址。地址落在 198.18.0.0/15 时,会提示这是 VPN 假地址。',
'发布物包含 Android APK(arm64-v8a 与 armeabi-v7a,versionName 1.1.1,versionCode 分别为 2004 和 1004)、Linux 与 Windows 桌面客户端,以及 Linux amd64、Linux arm64、Windows amd64 的检测节点包。',
'标签 v1.1.1 没有因为后来补上的桌面和节点压缩包而移动。',
],
),
];
const releaseHistoryNote =
'仓库里目前公开的版本标签只有 v1.1.1。1.1.1 的发布说明提到过更早的发包行为,但没有单独的标签或 Release,所以这里不写成另一个版本。';
+65
View File
@@ -0,0 +1,65 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
/// Latency over successful round-trips only.
///
/// * current: the latest successful sample, stored separately as `rttMs`
/// * min / max: smallest and largest successful sample
/// * mean: arithmetic mean
/// * median: the middle sample after sorting; when the count is even, the
/// mean of the two middle samples
/// * p95: nearest-rank. Rank is `ceil(0.95 * n)` computed as
/// `(95 * n + 99) ~/ 100` so binary floating point cannot move the rank.
/// Rank is 1-based and then clamped to the sample count.
class LatencyStats {
const LatencyStats({
required this.min,
required this.mean,
required this.median,
required this.p95,
required this.max,
});
final double min;
final double mean;
final double median;
final double p95;
final double max;
static LatencyStats? from(List<double> samples) {
if (samples.isEmpty) {
return null;
}
final sorted = [...samples]..sort();
var sum = 0.0;
for (final value in sorted) {
sum += value;
}
final count = sorted.length;
final median = count.isOdd
? sorted[count ~/ 2]
: (sorted[count ~/ 2 - 1] + sorted[count ~/ 2]) / 2;
final rank = nearestRank95(count);
return LatencyStats(
min: sorted.first,
mean: sum / count,
median: median,
p95: sorted[rank - 1],
max: sorted.last,
);
}
}
int nearestRank95(int count) {
if (count <= 1) {
return 1;
}
final rank = (95 * count + 99) ~/ 100;
if (rank < 1) {
return 1;
}
if (rank > count) {
return count;
}
return rank;
}
+48 -1
View File
@@ -1,3 +1,5 @@
import 'latency.dart';
class Outcome { class Outcome {
const Outcome({ const Outcome({
required this.status, required this.status,
@@ -6,6 +8,7 @@ class Outcome {
this.note = '', this.note = '',
this.detail = const {}, this.detail = const {},
this.reconnect = false, this.reconnect = false,
this.selectionSkipped = 0,
}); });
final String status; final String status;
@@ -15,6 +18,10 @@ class Outcome {
final Map<String, String> detail; final Map<String, String> detail;
final bool reconnect; final bool reconnect;
/// Candidate failures folded into this measured attempt. They are not
/// themselves samples.
final int selectionSkipped;
static const ok = 'ok'; static const ok = 'ok';
static const timeout = 'timeout'; static const timeout = 'timeout';
static const unknown = 'unknown'; static const unknown = 'unknown';
@@ -48,6 +55,13 @@ class ProbeSummary {
required this.unknownPct, required this.unknownPct,
required this.lastNote, required this.lastNote,
required this.detail, required this.detail,
this.minRttMs,
this.meanRttMs,
this.medianRttMs,
this.p95RttMs,
this.maxRttMs,
this.selectionSkipped = 0,
this.latencyStats = false,
}); });
final int sent; final int sent;
@@ -68,6 +82,15 @@ class ProbeSummary {
final double? unknownPct; final double? unknownPct;
final String lastNote; final String lastNote;
final Map<String, String> detail; final Map<String, String> detail;
final double? minRttMs;
final double? meanRttMs;
final double? medianRttMs;
final double? p95RttMs;
final double? maxRttMs;
final int selectionSkipped;
/// False when an older remote node omitted the latency distribution.
final bool latencyStats;
static const empty = ProbeSummary( static const empty = ProbeSummary(
sent: 0, sent: 0,
@@ -110,6 +133,16 @@ class ProbeSummary {
unknownPct: _double(json['unknownPct']), unknownPct: _double(json['unknownPct']),
lastNote: json['lastNote'] is String ? json['lastNote'] as String : '', lastNote: json['lastNote'] is String ? json['lastNote'] as String : '',
detail: _detail(json['detail']), detail: _detail(json['detail']),
minRttMs: _double(json['minRttMs']),
meanRttMs: _double(json['meanRttMs']),
medianRttMs: _double(json['medianRttMs']),
p95RttMs: _double(json['p95RttMs']),
maxRttMs: _double(json['maxRttMs']),
selectionSkipped: _int(json['selectionSkipped']),
latencyStats:
json.containsKey('minRttMs') ||
json.containsKey('medianRttMs') ||
json.containsKey('p95RttMs'),
); );
} }
} }
@@ -137,7 +170,9 @@ class ProbeSample {
factory ProbeSample.fromJson(Map<String, dynamic> json) { factory ProbeSample.fromJson(Map<String, dynamic> json) {
final summary = json['summary'] is Map final summary = json['summary'] is Map
? ProbeSummary.fromJson(Map<String, dynamic>.from(json['summary'] as Map)) ? ProbeSummary.fromJson(
Map<String, dynamic>.from(json['summary'] as Map),
)
: ProbeSummary.empty; : ProbeSummary.empty;
return ProbeSample( return ProbeSample(
seq: _int(json['seq']), seq: _int(json['seq']),
@@ -171,12 +206,15 @@ class SampleBook {
double jitterMs = 0; double jitterMs = 0;
bool _hasJitter = false; bool _hasJitter = false;
double _lastTransit = 0; double _lastTransit = 0;
final List<double> _rtts = [];
int selectionSkipped = 0;
String lastNote = ''; String lastNote = '';
Map<String, String> detail = {}; Map<String, String> detail = {};
void add(Outcome outcome) { void add(Outcome outcome) {
sent += 1; sent += 1;
completed += 1; completed += 1;
selectionSkipped += outcome.selectionSkipped;
if (outcome.reconnect) { if (outcome.reconnect) {
reconnects += 1; reconnects += 1;
} }
@@ -193,6 +231,7 @@ class SampleBook {
final rtt = outcome.rttMs; final rtt = outcome.rttMs;
if (rtt != null) { if (rtt != null) {
lastRttMs = rtt; lastRttMs = rtt;
_rtts.add(rtt);
if (_hasJitter) { if (_hasJitter) {
final delta = (rtt - _lastTransit).abs(); final delta = (rtt - _lastTransit).abs();
jitterMs += (delta - jitterMs) / 16; jitterMs += (delta - jitterMs) / 16;
@@ -250,6 +289,7 @@ class SampleBook {
} }
} }
} }
final latency = LatencyStats.from(_rtts);
return ProbeSummary( return ProbeSummary(
sent: sent, sent: sent,
completed: completed, completed: completed,
@@ -269,6 +309,13 @@ class SampleBook {
unknownPct: unknownPct, unknownPct: unknownPct,
lastNote: lastNote, lastNote: lastNote,
detail: detail, detail: detail,
minRttMs: latency?.min,
meanRttMs: latency?.mean,
medianRttMs: latency?.median,
p95RttMs: latency?.p95,
maxRttMs: latency?.max,
selectionSkipped: selectionSkipped,
latencyStats: true,
); );
} }
+120
View File
@@ -0,0 +1,120 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'sample_book.dart';
/// A candidate "responded" when the address itself answered: success, a
/// protocol mismatch, or an explicit refusal. Silence, timeout and a
/// connect error are not a response, so another address may be tried.
bool selectionResponded(Outcome outcome) {
switch (outcome.status) {
case Outcome.ok:
case Outcome.protocol:
case Outcome.refused:
return true;
default:
return false;
}
}
class SelectionDecision {
const SelectionDecision({required this.commit, this.skipped = 0});
final List<Outcome> commit;
final int skipped;
}
/// Separates address selection from measured probes.
///
/// Before any candidate has responded, failures are held. A later response
/// drops those held failures: they are reported as a fallback diagnostic and
/// are not added to sent, timeout or loss. If every candidate fails in the
/// round, the held failures are committed, so the session cannot show a
/// false 0% success. After a response, further failures are committed
/// immediately. [endMeasurement] is called when the picker leaves the
/// address that was being measured; the failure that caused the leave has
/// already been committed.
class SelectionLedger {
SelectionLedger(this.candidateCount);
final int candidateCount;
bool measuring = false;
final List<Outcome> _held = [];
SelectionDecision take(Outcome outcome, {required bool responded}) {
if (candidateCount <= 1) {
if (responded) {
measuring = true;
}
return SelectionDecision(commit: [outcome]);
}
if (measuring) {
return SelectionDecision(commit: [outcome]);
}
if (responded) {
final skipped = _held.length;
final next = skipped == 0
? outcome
: _attach(outcome, _fallbackText(_held, outcome), skipped);
_held.clear();
measuring = true;
return SelectionDecision(commit: [next], skipped: skipped);
}
_held.add(outcome);
if (_held.length >= candidateCount) {
final commit = List<Outcome>.of(_held);
_held.clear();
return SelectionDecision(commit: commit);
}
return const SelectionDecision(commit: []);
}
void endMeasurement() {
measuring = false;
}
}
Outcome _attach(Outcome outcome, String fallback, int skipped) {
return Outcome(
status: outcome.status,
kind: outcome.kind,
rttMs: outcome.rttMs,
note: outcome.note,
reconnect: outcome.reconnect,
selectionSkipped: outcome.selectionSkipped + skipped,
detail: {...outcome.detail, 'fallback': fallback},
);
}
String _fallbackText(List<Outcome> held, Outcome success) {
final failed = held
.map((outcome) {
final address = outcome.detail['address'];
final family = outcome.detail['family'];
final where = address == null || address.isEmpty
? '未知地址'
: (family == null || family.isEmpty)
? address
: '$address($family)';
final why = outcome.note.isEmpty ? '没有成功' : outcome.note;
return '$where:$why';
})
.join(';');
final used = success.detail['address'] ?? '';
final usedFamily = success.detail['family'] ?? '';
final usedText = used.isEmpty
? '另一个地址'
: usedFamily.isEmpty
? used
: '$used($usedFamily)';
return '候选未成功:$failed。已改用 $usedText。这些失败没有计入正式丢包或失败率。';
}
/// Stop discards the attempt that was still in flight. A finished attempt
/// whose note says it was stopped is not a measured loss either.
bool countsAfterStop(Outcome? outcome, {required bool cancelled}) {
if (cancelled || outcome == null) {
return false;
}
return outcome.note != '已停止';
}
+45
View File
@@ -0,0 +1,45 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import '../storage/token_vault.dart';
import 'session_config.dart';
/// Blank means "keep the token already stored". A non-blank value replaces it.
/// The saved token is never returned here.
String? replacementNodeToken(String entered) {
final trimmed = entered.trim();
if (trimmed.isEmpty) {
return null;
}
return trimmed;
}
/// Writes a replacement token. Returns false when the existing secret is kept.
Future<bool> saveEditedNodeToken(
TokenVault vault,
String id,
String entered,
) async {
final next = replacementNodeToken(entered);
if (next == null) {
return false;
}
await vault.write(nodeTokenKey(id), next);
return true;
}
/// Keeps [RemoteNode.id]. Changing the control URL clears a cached visibility
/// check because it may now be a different server. The token is not part of
/// this object.
RemoteNode applyNodeEdit(
RemoteNode node, {
required String name,
required String baseUrl,
}) {
final urlChanged = node.baseUrl != baseUrl;
return node.copyWith(
name: name,
baseUrl: baseUrl,
visibility: urlChanged ? '' : node.visibility,
);
}
+32
View File
@@ -0,0 +1,32 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'probe_profile.dart';
/// Keeps a port the user typed. An empty field or a value that is still the
/// previous profile's default follows the newly selected profile.
String portAfterProfileChange({
required String current,
required int previousDefault,
required int nextDefault,
}) {
final trimmed = current.trim();
if (trimmed.isEmpty || int.tryParse(trimmed) == previousDefault) {
return '$nextDefault';
}
return current;
}
String portHint(ProbeProfile profile) {
switch (profile.id) {
case 'nq-tcp':
return '合作反射 TCP 默认 19090';
case 'nq-udp':
return '合作反射 UDP 默认 19091';
default:
return '${profile.label} 默认 ${profile.port}';
}
}
const portHelperText =
'合作反射 TCP 默认 19090,UDP 默认 19091。只有当前端口仍是上一种类型的默认值或为空时,切换类型才会自动更换。';
+340 -107
View File
@@ -1,22 +1,67 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:async'; import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import '../metrics/sample_book.dart'; import '../metrics/sample_book.dart';
import '../models/probe_profile.dart'; import '../models/probe_profile.dart';
import '../models/session_config.dart'; import '../models/session_config.dart';
import '../ui/address_text.dart';
import 'endpoint_picker.dart'; import 'endpoint_picker.dart';
import 'probe_loop.dart'; import 'probe_loop.dart';
import 'remote_client.dart'; import 'remote_client.dart';
class ChartSample { class ChartSample {
const ChartSample({required this.sec, required this.rttMs, required this.ratePct}); const ChartSample({
required this.sec,
required this.rttMs,
required this.ratePct,
});
final double sec; final double sec;
final double? rttMs; final double? rttMs;
final double? ratePct; final double? ratePct;
} }
class SessionReport {
const SessionReport({
required this.startedAt,
required this.endedAt,
required this.elapsed,
required this.target,
required this.profileLabel,
required this.sourceLabel,
required this.profileId,
required this.summary,
required this.rateLabel,
required this.resolved,
required this.usedAddress,
required this.usedFamily,
required this.fallbackText,
required this.addressUnreported,
required this.usedIsFake,
});
final DateTime startedAt;
final DateTime endedAt;
final Duration elapsed;
final String target;
final String profileLabel;
final String sourceLabel;
final String profileId;
final ProbeSummary summary;
final String rateLabel;
final List<ResolvedAddress> resolved;
final String? usedAddress;
final String? usedFamily;
final String fallbackText;
final bool addressUnreported;
final bool usedIsFake;
}
class ProbeView { class ProbeView {
const ProbeView({ const ProbeView({
required this.running, required this.running,
@@ -28,8 +73,22 @@ class ProbeView {
required this.samples, required this.samples,
required this.rateLabel, required this.rateLabel,
required this.sourceLabel, required this.sourceLabel,
this.targetAddress, required this.sessionId,
this.targetIsFake = false, this.profileId = '',
required this.elapsed,
this.targetHost = '',
this.profileLabel = '',
this.tryingAddress,
this.tryingFamily,
this.usedAddress,
this.usedFamily,
this.usedIsFake = false,
this.resolved = const [],
this.fallbackText = '',
this.addressUnreported = false,
this.report,
this.startedAt,
this.endedAt,
}); });
static const initial = ProbeView( static const initial = ProbeView(
@@ -42,6 +101,8 @@ class ProbeView {
samples: [], samples: [],
rateLabel: '探测无应答', rateLabel: '探测无应答',
sourceLabel: '本机', sourceLabel: '本机',
sessionId: 0,
elapsed: Duration.zero,
); );
final bool running; final bool running;
@@ -53,8 +114,22 @@ class ProbeView {
final List<ChartSample> samples; final List<ChartSample> samples;
final String rateLabel; final String rateLabel;
final String sourceLabel; final String sourceLabel;
final String? targetAddress; final int sessionId;
final bool targetIsFake; final String profileId;
final Duration elapsed;
final String targetHost;
final String profileLabel;
final String? tryingAddress;
final String? tryingFamily;
final String? usedAddress;
final String? usedFamily;
final bool usedIsFake;
final List<ResolvedAddress> resolved;
final String fallbackText;
final bool addressUnreported;
final SessionReport? report;
final DateTime? startedAt;
final DateTime? endedAt;
ProbeView copyWith({ ProbeView copyWith({
bool? running, bool? running,
@@ -67,8 +142,24 @@ class ProbeView {
List<ChartSample>? samples, List<ChartSample>? samples,
String? rateLabel, String? rateLabel,
String? sourceLabel, String? sourceLabel,
String? targetAddress, int? sessionId,
bool? targetIsFake, String? profileId,
Duration? elapsed,
String? targetHost,
String? profileLabel,
String? tryingAddress,
String? tryingFamily,
bool clearTrying = false,
String? usedAddress,
String? usedFamily,
bool? usedIsFake,
List<ResolvedAddress>? resolved,
String? fallbackText,
bool? addressUnreported,
SessionReport? report,
bool clearReport = false,
DateTime? startedAt,
DateTime? endedAt,
}) { }) {
return ProbeView( return ProbeView(
running: running ?? this.running, running: running ?? this.running,
@@ -80,8 +171,22 @@ class ProbeView {
samples: samples ?? this.samples, samples: samples ?? this.samples,
rateLabel: rateLabel ?? this.rateLabel, rateLabel: rateLabel ?? this.rateLabel,
sourceLabel: sourceLabel ?? this.sourceLabel, sourceLabel: sourceLabel ?? this.sourceLabel,
targetAddress: targetAddress ?? this.targetAddress, sessionId: sessionId ?? this.sessionId,
targetIsFake: targetIsFake ?? this.targetIsFake, profileId: profileId ?? this.profileId,
elapsed: elapsed ?? this.elapsed,
targetHost: targetHost ?? this.targetHost,
profileLabel: profileLabel ?? this.profileLabel,
tryingAddress: clearTrying ? null : tryingAddress ?? this.tryingAddress,
tryingFamily: clearTrying ? null : tryingFamily ?? this.tryingFamily,
usedAddress: usedAddress ?? this.usedAddress,
usedFamily: usedFamily ?? this.usedFamily,
usedIsFake: usedIsFake ?? this.usedIsFake,
resolved: resolved ?? this.resolved,
fallbackText: fallbackText ?? this.fallbackText,
addressUnreported: addressUnreported ?? this.addressUnreported,
report: clearReport ? null : report ?? this.report,
startedAt: startedAt ?? this.startedAt,
endedAt: endedAt ?? this.endedAt,
); );
} }
} }
@@ -93,113 +198,154 @@ class ProbeController extends ChangeNotifier {
RemoteProbe? _remote; RemoteProbe? _remote;
String _nodeToken = ''; String _nodeToken = '';
var _token = 0; var _token = 0;
var _session = 0;
var _busy = false;
var _remoteMode = false;
DateTime? _startedAt;
Timer? _tick;
Future<void> start(SessionConfig config, {required String nodeToken, required String echoToken}) async { Future<void> start(
final problem = config.validate(); SessionConfig config, {
if (problem != null) { required String nodeToken,
view = view.copyWith(banner: problem, phase: '无法开始'); required String echoToken,
notifyListeners(); }) async {
if (_busy) {
return; return;
} }
final echoProblem = _echoProblem(config.profileId, echoToken); _busy = true;
if (echoProblem != null) {
view = view.copyWith(banner: echoProblem, phase: '无法开始');
notifyListeners();
return;
}
await stop();
_nodeToken = nodeToken;
final generation = ++_token;
_clock
..reset()
..start();
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
view = ProbeView(
running: true,
phase: '探测中',
banner: null,
note: config.remote ? '正在让节点向目标发包' : '正在从本机向目标发包',
detail: const {},
summary: ProbeSummary.empty,
samples: const [],
rateLabel: rateLabelFor(config.profileId),
sourceLabel: source,
);
notifyListeners();
bool cancelled() => generation != _token;
try { try {
if (config.remote) { final problem = config.validate();
final remote = RemoteProbe(); if (problem != null) {
_remote = remote; view = view.copyWith(banner: problem, phase: '无法开始');
await remote.run(
baseUrl: config.node!.baseUrl,
nodeToken: nodeToken,
body: ProbeBody(
target: config.host.trim(),
port: config.port,
profile: config.profileId,
intervalMs: config.intervalMs,
timeoutMs: config.timeoutMs,
durationSec: config.durationSec,
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
);
} else {
final loop = ProbeLoop(
onEndpoint: (address) {
if (generation != _token) {
return;
}
view = view.copyWith(
targetAddress: address.address,
targetIsFake: isClashFakeIp(address),
);
notifyListeners();
},
);
_local = loop;
await loop.run(
request: ProbeRequest(
host: config.host.trim(),
port: config.port,
profileId: config.profileId,
interval: Duration(milliseconds: config.intervalMs),
timeout: Duration(milliseconds: config.timeoutMs),
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
);
}
if (generation == _token) {
view = view.copyWith(running: false, phase: '已停止');
notifyListeners(); notifyListeners();
return;
} }
} on RemoteException catch (error) { final echoProblem = _echoProblem(config.profileId, echoToken);
if (generation == _token) { if (echoProblem != null) {
view = view.copyWith(running: false, phase: '出错', banner: error.message); view = view.copyWith(banner: echoProblem, phase: '无法开始');
notifyListeners(); notifyListeners();
return;
} }
} on Object { await stop();
if (generation == _token) { _nodeToken = nodeToken;
view = view.copyWith(running: false, phase: '出错', banner: '探测中断'); _remoteMode = config.remote;
notifyListeners(); final generation = ++_token;
final session = ++_session;
_startedAt = DateTime.now();
_clock
..reset()
..start();
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
final profile = ProbeProfile.byId(config.profileId);
view = ProbeView(
running: true,
phase: '探测中',
banner: null,
note: config.remote ? '正在让节点向目标发包' : '正在从本机向目标发包',
detail: const {},
summary: ProbeSummary.empty,
samples: const [],
rateLabel: rateLabelFor(config.profileId),
sourceLabel: source,
sessionId: session,
profileId: config.profileId,
elapsed: Duration.zero,
targetHost: '${config.host.trim()}:${config.port}',
profileLabel: profile.label,
startedAt: _startedAt,
);
notifyListeners();
_armTick(generation);
bool cancelled() => generation != _token;
try {
if (config.remote) {
final remote = RemoteProbe();
_remote = remote;
await remote.run(
baseUrl: config.node!.baseUrl,
nodeToken: nodeToken,
body: ProbeBody(
target: config.host.trim(),
port: config.port,
profile: config.profileId,
intervalMs: config.intervalMs,
timeoutMs: config.timeoutMs,
durationSec: config.durationSec,
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
onResolved: (resolved) {
if (generation != _token) {
return;
}
view = view.copyWith(resolved: resolved);
notifyListeners();
},
cancelled: cancelled,
);
} else {
final loop = ProbeLoop(
onEndpoint: (address) {
if (generation != _token) {
return;
}
view = view.copyWith(
tryingAddress: address.address,
tryingFamily: addressFamily(address),
);
notifyListeners();
},
onResolved: (addresses) {
if (generation != _token) {
return;
}
view = view.copyWith(
resolved: [
for (final address in addresses)
ResolvedAddress(
address: address.address,
family: addressFamily(address),
),
],
);
notifyListeners();
},
);
_local = loop;
await loop.run(
request: ProbeRequest(
host: config.host.trim(),
port: config.port,
profileId: config.profileId,
interval: Duration(milliseconds: config.intervalMs),
timeout: Duration(milliseconds: config.timeoutMs),
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
);
}
_finish(generation, '已停止');
} on RemoteException catch (error) {
_finish(generation, '出错', banner: error.message);
} on Object {
_finish(generation, '出错', banner: '探测中断');
} finally {
if (generation == _token) {
_local = null;
_remote = null;
}
} }
} finally { } finally {
if (generation == _token) { _busy = false;
_local = null;
_remote = null;
}
} }
} }
@@ -217,11 +363,73 @@ class ProbeController extends ChangeNotifier {
_nodeToken = ''; _nodeToken = '';
} }
if (view.running) { if (view.running) {
view = view.copyWith(running: false, phase: '已停止'); _clock.stop();
_tick?.cancel();
final ended = DateTime.now();
view = view.copyWith(
running: false,
phase: '已停止',
elapsed: _clock.elapsed,
endedAt: ended,
report: _snapshot(ended),
);
notifyListeners(); notifyListeners();
} }
} }
void _finish(int generation, String phase, {String? banner}) {
if (generation != _token || !view.running) {
return;
}
_clock.stop();
_tick?.cancel();
final ended = DateTime.now();
view = view.copyWith(
running: false,
phase: phase,
banner: banner,
elapsed: _clock.elapsed,
endedAt: ended,
report: _snapshot(ended),
);
notifyListeners();
}
SessionReport? _snapshot(DateTime ended) {
final started = _startedAt;
if (started == null) {
return null;
}
return SessionReport(
startedAt: started,
endedAt: ended,
elapsed: _clock.elapsed,
target: view.targetHost,
profileLabel: view.profileLabel,
sourceLabel: view.sourceLabel,
profileId: view.profileId,
summary: view.summary,
rateLabel: view.rateLabel,
resolved: view.resolved,
usedAddress: view.usedAddress,
usedFamily: view.usedFamily,
fallbackText: view.fallbackText,
addressUnreported: view.addressUnreported,
usedIsFake: view.usedIsFake,
);
}
void _armTick(int generation) {
_tick?.cancel();
_tick = Timer.periodic(const Duration(seconds: 1), (_) {
if (generation != _token || !view.running) {
return;
}
view = view.copyWith(elapsed: _clock.elapsed);
notifyListeners();
});
}
void _accept(int generation, ProbeSample sample) { void _accept(int generation, ProbeSample sample) {
if (generation != _token) { if (generation != _token) {
return; return;
@@ -246,6 +454,16 @@ class ProbeController extends ChangeNotifier {
ratePct: rate, ratePct: rate,
), ),
); );
final reported = sample.detail['address'];
final hasAddress = reported != null && reported.isNotEmpty;
final fallback = sample.detail['fallback'];
final parsed = hasAddress ? InternetAddress.tryParse(reported) : null;
final family = hasAddress
? ((sample.detail['family'] != null &&
sample.detail['family']!.isNotEmpty)
? sample.detail['family']
: familyOfAddress(reported))
: null;
view = view.copyWith( view = view.copyWith(
phase: phaseFor(sample.status), phase: phaseFor(sample.status),
note: sample.note, note: sample.note,
@@ -253,9 +471,24 @@ class ProbeController extends ChangeNotifier {
summary: sample.summary, summary: sample.summary,
samples: samples, samples: samples,
clearBanner: true, clearBanner: true,
elapsed: _clock.elapsed,
usedAddress: hasAddress ? reported : view.usedAddress,
usedFamily: hasAddress ? family : view.usedFamily,
usedIsFake: hasAddress
? parsed != null && isClashFakeIp(parsed)
: view.usedIsFake,
clearTrying: hasAddress || (fallback != null && fallback.isNotEmpty),
fallbackText: (fallback != null && fallback.isNotEmpty) ? fallback : null,
addressUnreported: _remoteMode && !hasAddress,
); );
notifyListeners(); notifyListeners();
} }
@override
void dispose() {
_tick?.cancel();
super.dispose();
}
} }
String? _echoProblem(String profileId, String echoToken) { String? _echoProblem(String profileId, String echoToken) {
+324 -92
View File
@@ -3,7 +3,9 @@ import 'dart:io';
import 'dart:typed_data'; import 'dart:typed_data';
import '../metrics/sample_book.dart'; import '../metrics/sample_book.dart';
import '../metrics/selection_ledger.dart';
import '../protocol/probe_packet.dart'; import '../protocol/probe_packet.dart';
import '../ui/address_text.dart';
import 'endpoint_picker.dart'; import 'endpoint_picker.dart';
import 'game_codec.dart'; import 'game_codec.dart';
@@ -36,10 +38,7 @@ class ProbeRequest {
/// Sends one probe at a time from this device. A cancelled attempt is not /// Sends one probe at a time from this device. A cancelled attempt is not
/// recorded, so stopping cannot paint a fake loss sample. /// recorded, so stopping cannot paint a fake loss sample.
class ProbeLoop { class ProbeLoop {
ProbeLoop({ ProbeLoop({this.lookup, this.onEndpoint, this.onResolved});
this.lookup,
this.onEndpoint,
});
/// Replaces [lookupAll] in tests. /// Replaces [lookupAll] in tests.
final Future<List<InternetAddress>> Function(String host)? lookup; final Future<List<InternetAddress>> Function(String host)? lookup;
@@ -47,10 +46,16 @@ class ProbeLoop {
/// Fires when the address about to be used is chosen or changed. /// Fires when the address about to be used is chosen or changed.
final void Function(InternetAddress address)? onEndpoint; final void Function(InternetAddress address)? onEndpoint;
/// Fires once with the lookup result. This is not the address in use.
final void Function(List<InternetAddress> addresses)? onResolved;
_TcpPipe? _tcp; _TcpPipe? _tcp;
_UdpPipe? _udp; _UdpPipe? _udp;
EndpointPicker? _picker; EndpointPicker? _picker;
SelectionLedger? _ledger;
InternetAddress? _announced; InternetAddress? _announced;
InternetAddress? _tcpUsed;
List<InternetAddress>? _resolved;
int _seq = 0; int _seq = 0;
int _dnsId = 1; int _dnsId = 1;
final int _guid = DateTime.now().microsecondsSinceEpoch; final int _guid = DateTime.now().microsecondsSinceEpoch;
@@ -65,20 +70,32 @@ class ProbeLoop {
while (!cancelled()) { while (!cancelled()) {
final started = DateTime.now(); final started = DateTime.now();
final outcome = await _once(request, cancelled); final outcome = await _once(request, cancelled);
if (cancelled() || outcome == null) { if (!countsAfterStop(outcome, cancelled: cancelled())) {
break; break;
} }
if (_usesDatagram(request.profileId)) { var commit = <Outcome>[outcome!];
final responded = outcome.status == Outcome.ok || if (_usesDatagram(request.profileId) && _picker != null) {
outcome.status == Outcome.protocol || _ledger ??= SelectionLedger(_picker!.candidates.length);
outcome.status == Outcome.refused; final responded = selectionResponded(outcome);
if (_picker != null && _picker!.record(responded)) { final wasMeasuring = _ledger!.measuring;
final changed = _picker!.record(responded);
final decision = _ledger!.take(outcome, responded: responded);
if (wasMeasuring && changed) {
_ledger!.endMeasurement();
}
if (changed) {
await _dropUdp(); await _dropUdp();
_announce(_picker!.current); _announce(_picker!.current);
} }
commit = decision.commit;
if (commit.isEmpty) {
continue;
}
}
for (final item in commit) {
book.add(item);
onSample(book.sample(book.sent, item));
} }
book.add(outcome);
onSample(book.sample(book.sent, outcome));
final spent = DateTime.now().difference(started); final spent = DateTime.now().difference(started);
final rest = request.interval - spent; final rest = request.interval - spent;
if (!cancelled() && rest > Duration.zero) { if (!cancelled() && rest > Duration.zero) {
@@ -103,7 +120,10 @@ class ProbeLoop {
} }
} }
Future<Outcome?> _once(ProbeRequest request, bool Function() cancelled) async { Future<Outcome?> _once(
ProbeRequest request,
bool Function() cancelled,
) async {
try { try {
final outcome = await _dispatch(request, cancelled); final outcome = await _dispatch(request, cancelled);
final peer = _udp?.peer; final peer = _udp?.peer;
@@ -160,45 +180,58 @@ class ProbeLoop {
ProbeRequest request, ProbeRequest request,
bool Function() cancelled, bool Function() cancelled,
) async { ) async {
final watch = Stopwatch()..start(); final opened = await _openTcp(request, cancelled);
final socket = await Socket.connect( final failure = opened.failure;
request.host, if (failure != null) {
request.port, return failure;
timeout: request.timeout, }
); final socket = opened.socket!;
watch.stop(); opened.watch?.stop();
await socket.close(); await socket.close();
if (cancelled()) { if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止'); return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '已停止',
);
} }
return Outcome( return _withUsed(
status: Outcome.ok, Outcome(
kind: Outcome.connect, status: Outcome.ok,
rttMs: watch.elapsedMicroseconds / 1000, kind: Outcome.connect,
note: 'TCP 已连通', rttMs: (opened.watch?.elapsedMicroseconds ?? 0) / 1000,
note: 'TCP 已连通',
),
opened.used,
opened.fallback,
opened.skipped,
); );
} }
Future<Outcome> _nqTcp(ProbeRequest request, bool Function() cancelled) async { Future<Outcome> _nqTcp(
ProbeRequest request,
bool Function() cancelled,
) async {
var fallback = '';
var skipped = 0;
if (_tcp == null) { if (_tcp == null) {
try { final opened = await _openTcp(request, cancelled);
final socket = await Socket.connect( final failure = opened.failure;
request.host, if (failure != null) {
request.port, return Outcome(
timeout: request.timeout, status: failure.status,
); kind: failure.kind,
socket.setOption(SocketOption.tcpNoDelay, true); note: failure.note,
_tcp = _TcpPipe(socket); reconnect: failure.note != '已停止',
} on SocketException catch (error) { detail: failure.detail,
return classifySocket(error, reconnect: true);
} on TimeoutException {
return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
reconnect: true,
note: '连接超时,将重试',
); );
} }
final socket = opened.socket!;
socket.setOption(SocketOption.tcpNoDelay, true);
_tcp = _TcpPipe(socket);
_tcpUsed = opened.used;
fallback = opened.fallback;
skipped = opened.skipped;
} }
final pipe = _tcp!; final pipe = _tcp!;
_seq += 1; _seq += 1;
@@ -232,21 +265,35 @@ class ProbeLoop {
} }
}); });
if (cancelled()) { if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止'); return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '已停止',
);
} }
if (matched == null) { if (matched == null) {
await _dropTcp(); await _dropTcp();
return const Outcome( return _withUsed(
status: Outcome.timeout, const Outcome(
kind: Outcome.probe, status: Outcome.timeout,
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包', kind: Outcome.probe,
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
),
_tcpUsed,
fallback,
skipped,
); );
} }
return Outcome( return _withUsed(
status: Outcome.ok, Outcome(
kind: Outcome.probe, status: Outcome.ok,
rttMs: watch.elapsedMicroseconds / 1000, kind: Outcome.probe,
note: '收到回显', rttMs: watch.elapsedMicroseconds / 1000,
note: '收到回显',
),
_tcpUsed,
fallback,
skipped,
); );
} }
@@ -258,7 +305,10 @@ class ProbeLoop {
} }
} }
Future<Outcome> _nqUdp(ProbeRequest request, bool Function() cancelled) async { Future<Outcome> _nqUdp(
ProbeRequest request,
bool Function() cancelled,
) async {
final pipe = await _datagram(request); final pipe = await _datagram(request);
_seq += 1; _seq += 1;
final seq = _seq; final seq = _seq;
@@ -286,7 +336,11 @@ class ProbeLoop {
} }
}); });
if (cancelled()) { if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止'); return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '已停止',
);
} }
if (reply == null) { if (reply == null) {
if (sawInvalid) { if (sawInvalid) {
@@ -329,7 +383,11 @@ class ProbeLoop {
pipe.send(payload, request.port); pipe.send(payload, request.port);
final reply = await pipe.waitMatch(request.timeout, (_) => true); final reply = await pipe.waitMatch(request.timeout, (_) => true);
if (cancelled()) { if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止'); return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '已停止',
);
} }
if (reply == null) { if (reply == null) {
return const Outcome( return const Outcome(
@@ -339,7 +397,8 @@ class ProbeLoop {
); );
} }
final wanted = expect; final wanted = expect;
if (wanted != null && (reply.length < wanted.length || !_prefix(reply, wanted))) { if (wanted != null &&
(reply.length < wanted.length || !_prefix(reply, wanted))) {
return const Outcome( return const Outcome(
status: Outcome.protocol, status: Outcome.protocol,
kind: Outcome.query, kind: Outcome.query,
@@ -358,7 +417,9 @@ class ProbeLoop {
final pipe = await _datagram(request); final pipe = await _datagram(request);
_dnsId = _dnsId == 65535 ? 1 : _dnsId + 1; _dnsId = _dnsId == 65535 ? 1 : _dnsId + 1;
final id = _dnsId; final id = _dnsId;
final name = request.dnsName.trim().isEmpty ? 'example.com' : request.dnsName.trim(); final name = request.dnsName.trim().isEmpty
? 'example.com'
: request.dnsName.trim();
final watch = Stopwatch()..start(); final watch = Stopwatch()..start();
pipe.send(dnsQuery(id, name), request.port); pipe.send(dnsQuery(id, name), request.port);
var malformed = false; var malformed = false;
@@ -378,7 +439,11 @@ class ProbeLoop {
return true; return true;
}); });
if (cancelled()) { if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止'); return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '已停止',
);
} }
if (reply == null) { if (reply == null) {
if (malformed) { if (malformed) {
@@ -422,7 +487,11 @@ class ProbeLoop {
return true; return true;
}); });
if (cancelled()) { if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止'); return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '已停止',
);
} }
if (reply == null) { if (reply == null) {
if (sawInvalid) { if (sawInvalid) {
@@ -448,11 +517,12 @@ class ProbeLoop {
} }
Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async { Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async {
final socket = await Socket.connect( final opened = await _openTcp(request, cancelled);
request.host, final failure = opened.failure;
request.port, if (failure != null) {
timeout: request.timeout, return failure;
); }
final socket = opened.socket!;
final reader = _BytePipe(socket); final reader = _BytePipe(socket);
try { try {
socket.add(javaHandshake(request.host, request.port)); socket.add(javaHandshake(request.host, request.port));
@@ -460,18 +530,28 @@ class ProbeLoop {
await socket.flush(); await socket.flush();
final status = await reader.nextPacket(request.timeout); final status = await reader.nextPacket(request.timeout);
if (status == null || status.isEmpty || status[0] != 0x00) { if (status == null || status.isEmpty || status[0] != 0x00) {
return const Outcome( return _withUsed(
status: Outcome.protocol, const Outcome(
kind: Outcome.query, status: Outcome.protocol,
note: 'Minecraft 状态响应无效', kind: Outcome.query,
note: 'Minecraft 状态响应无效',
),
opened.used,
opened.fallback,
opened.skipped,
); );
} }
final jsonText = readMcString(status, 1); final jsonText = readMcString(status, 1);
if (jsonText == null) { if (jsonText == null) {
return const Outcome( return _withUsed(
status: Outcome.protocol, const Outcome(
kind: Outcome.query, status: Outcome.protocol,
note: 'Minecraft 状态内容无法解析', kind: Outcome.query,
note: 'Minecraft 状态内容无法解析',
),
opened.used,
opened.fallback,
opened.skipped,
); );
} }
final detail = minecraftStatusDetail(jsonText); final detail = minecraftStatusDetail(jsonText);
@@ -481,30 +561,49 @@ class ProbeLoop {
await socket.flush(); await socket.flush();
final pong = await reader.nextPacket(request.timeout); final pong = await reader.nextPacket(request.timeout);
if (cancelled()) { if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止'); return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '已停止',
);
} }
if (pong == null || pong.length != 9 || pong[0] != 0x01) { if (pong == null || pong.length != 9 || pong[0] != 0x01) {
return Outcome( return _withUsed(
status: Outcome.protocol, Outcome(
kind: Outcome.query, status: Outcome.protocol,
note: '没有收到有效的 Minecraft pong', kind: Outcome.query,
detail: detail, note: '没有收到有效的 Minecraft pong',
detail: detail,
),
opened.used,
opened.fallback,
opened.skipped,
); );
} }
if (ByteData.sublistView(pong).getUint64(1) != nonce) { if (ByteData.sublistView(pong).getUint64(1) != nonce) {
return Outcome( return _withUsed(
status: Outcome.protocol, Outcome(
kind: Outcome.query, status: Outcome.protocol,
note: 'Minecraft pong 的时间戳不匹配', kind: Outcome.query,
detail: detail, note: 'Minecraft pong 的时间戳不匹配',
detail: detail,
),
opened.used,
opened.fallback,
opened.skipped,
); );
} }
return Outcome( return _withUsed(
status: Outcome.ok, Outcome(
kind: Outcome.query, status: Outcome.ok,
rttMs: watch.elapsedMicroseconds / 1000, kind: Outcome.query,
note: '收到 Minecraft 状态和 ping 应答', rttMs: watch.elapsedMicroseconds / 1000,
detail: detail, note: '收到 Minecraft 状态和 ping 应答',
detail: detail,
),
opened.used,
opened.fallback,
opened.skipped,
); );
} finally { } finally {
await reader.close(); await reader.close();
@@ -513,7 +612,7 @@ class ProbeLoop {
} }
Future<_UdpPipe> _datagram(ProbeRequest request) async { Future<_UdpPipe> _datagram(ProbeRequest request) async {
_picker ??= EndpointPicker(await (lookup ?? lookupAll)(request.host)); _picker ??= EndpointPicker(await _addresses(request.host));
final want = _picker!.current; final want = _picker!.current;
final existing = _udp; final existing = _udp;
if (existing != null && existing.peer.address == want.address) { if (existing != null && existing.peer.address == want.address) {
@@ -550,6 +649,134 @@ class ProbeLoop {
await udp.close(); await udp.close();
} }
} }
Future<List<InternetAddress>> _addresses(String host) async {
final cached = _resolved;
if (cached != null) {
return cached;
}
final found = await (lookup ?? lookupAll)(host);
_resolved = found;
onResolved?.call(found);
return found;
}
Future<_TcpOpen> _openTcp(
ProbeRequest request,
bool Function() cancelled,
) async {
List<InternetAddress> addresses;
try {
addresses = await _addresses(request.host);
} on SocketException catch (error) {
return _TcpOpen.fail(classifySocket(error));
}
final skipped = <String>[];
Object? last;
for (final address in addresses) {
if (cancelled()) {
return _TcpOpen.fail(
const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '已停止',
),
);
}
_announce(address);
final watch = Stopwatch()..start();
try {
final socket = await Socket.connect(
address,
request.port,
timeout: request.timeout,
);
watch.stop();
final fallback = skipped.isEmpty
? ''
: '候选未连通:${skipped.join(';')}。已改用 ${address.address}(${addressFamily(address)})。这些失败没有计入正式丢包或失败率。';
return _TcpOpen.ok(socket, address, watch, fallback, skipped.length);
} on SocketException catch (error) {
last = error;
skipped.add(
'${addressFamily(address)} ${address.address}:${classifySocket(error).note}',
);
} on TimeoutException {
last = TimeoutException('连接超时');
skipped.add('${addressFamily(address)} ${address.address}:连接超时');
}
}
final failure = last is SocketException
? classifySocket(last)
: const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '连接超时',
);
final attempted = skipped.join(';');
return _TcpOpen.fail(
Outcome(
status: failure.status,
kind: failure.kind,
note: skipped.length > 1 ? '没有地址连通。$attempted' : failure.note,
detail: attempted.isEmpty
? const {}
: {'fallback': '已尝试 $attempted。没有地址连通,这次记为失败。'},
),
);
}
}
class _TcpOpen {
const _TcpOpen.ok(
this.socket,
this.used,
this.watch,
this.fallback,
this.skipped,
) : failure = null;
const _TcpOpen.fail(this.failure)
: socket = null,
used = null,
watch = null,
fallback = '',
skipped = 0;
final Socket? socket;
final InternetAddress? used;
final Stopwatch? watch;
final Outcome? failure;
final String fallback;
final int skipped;
}
Outcome _withUsed(
Outcome outcome,
InternetAddress? used,
String fallback,
int skipped,
) {
if (used == null && fallback.isEmpty && skipped == 0) {
return outcome;
}
final detail = {...outcome.detail};
if (used != null) {
detail['address'] = used.address;
detail['family'] = addressFamily(used);
}
if (fallback.isNotEmpty) {
detail['fallback'] = fallback;
}
return Outcome(
status: outcome.status,
kind: outcome.kind,
rttMs: outcome.rttMs,
note: outcome.note,
reconnect: outcome.reconnect,
selectionSkipped: skipped,
detail: detail,
);
} }
bool _usesDatagram(String profileId) { bool _usesDatagram(String profileId) {
@@ -572,7 +799,12 @@ Outcome _stampAddress(Outcome outcome, InternetAddress peer) {
rttMs: outcome.rttMs, rttMs: outcome.rttMs,
note: outcome.note, note: outcome.note,
reconnect: outcome.reconnect, reconnect: outcome.reconnect,
detail: {...outcome.detail, 'address': peer.address}, selectionSkipped: outcome.selectionSkipped,
detail: {
...outcome.detail,
'address': peer.address,
'family': addressFamily(peer),
},
); );
} }
+19 -4
View File
@@ -4,6 +4,7 @@ import 'dart:io';
import '../metrics/sample_book.dart'; import '../metrics/sample_book.dart';
import '../models/session_config.dart'; import '../models/session_config.dart';
import '../ui/address_text.dart';
class RemoteProbe { class RemoteProbe {
HttpClient? _client; HttpClient? _client;
@@ -16,6 +17,7 @@ class RemoteProbe {
required ProbeBody body, required ProbeBody body,
required void Function(ProbeSample sample) onSample, required void Function(ProbeSample sample) onSample,
required bool Function() cancelled, required bool Function() cancelled,
void Function(List<ResolvedAddress> resolved)? onResolved,
}) async { }) async {
final normalized = normalizeNodeUrl(baseUrl); final normalized = normalizeNodeUrl(baseUrl);
if (normalized == null) { if (normalized == null) {
@@ -52,6 +54,7 @@ class RemoteProbe {
throw RemoteException('节点返回的任务无效'); throw RemoteException('节点返回的任务无效');
} }
_jobId = parsed['jobId'] as String; _jobId = parsed['jobId'] as String;
onResolved?.call(readResolvedList(parsed));
if (cancelled()) { if (cancelled()) {
return; return;
} }
@@ -86,7 +89,13 @@ class RemoteProbe {
_jobId = null; _jobId = null;
if (client != null && id != null && base != null) { if (client != null && id != null && base != null) {
try { try {
await _send(client, 'DELETE', base.resolve('/v1/jobs/$id'), nodeToken, const []); await _send(
client,
'DELETE',
base.resolve('/v1/jobs/$id'),
nodeToken,
const [],
);
} on Object { } on Object {
// The stream ending already asks the node to drop the job. // The stream ending already asks the node to drop the job.
} }
@@ -101,7 +110,9 @@ class RemoteProbe {
void Function(ProbeSample sample) onSample, void Function(ProbeSample sample) onSample,
bool Function() cancelled, bool Function() cancelled,
) async { ) async {
final request = await client.getUrl(_base!.resolve('/v1/jobs/$_jobId/stream')); final request = await client.getUrl(
_base!.resolve('/v1/jobs/$_jobId/stream'),
);
request.followRedirects = false; request.followRedirects = false;
_auth(request, nodeToken); _auth(request, nodeToken);
final response = await request.close().timeout(const Duration(seconds: 20)); final response = await request.close().timeout(const Duration(seconds: 20));
@@ -194,7 +205,9 @@ Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
} }
final client = HttpClient(); final client = HttpClient();
try { try {
final request = await client.getUrl(Uri.parse(normalized).resolve('/v1/info')); final request = await client.getUrl(
Uri.parse(normalized).resolve('/v1/info'),
);
request.followRedirects = false; request.followRedirects = false;
final response = await request.close().timeout(const Duration(seconds: 8)); final response = await request.close().timeout(const Duration(seconds: 8));
final body = await response.transform(utf8.decoder).join(); final body = await response.transform(utf8.decoder).join();
@@ -206,7 +219,9 @@ Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
throw RemoteException('节点信息无效'); throw RemoteException('节点信息无效');
} }
return NodeInfo( return NodeInfo(
visibility: json['visibility'] is String ? json['visibility'] as String : '', visibility: json['visibility'] is String
? json['visibility'] as String
: '',
authRequired: json['authRequired'] == true, authRequired: json['authRequired'] == true,
); );
} on RemoteException { } on RemoteException {
+125
View File
@@ -0,0 +1,125 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:io';
class ResolvedAddress {
const ResolvedAddress({required this.address, required this.family});
final String address;
final String family;
}
String addressFamily(InternetAddress address) {
return address.type == InternetAddressType.IPv6 ? 'IPv6' : 'IPv4';
}
String familyOfAddress(String address) {
final parsed = InternetAddress.tryParse(address);
if (parsed == null) {
return '';
}
return addressFamily(parsed);
}
class AddressLines {
const AddressLines({
this.used,
this.trying,
this.resolved,
this.fallback,
this.unreported,
this.fake = false,
});
final String? used;
final String? trying;
final String? resolved;
final String? fallback;
final String? unreported;
final bool fake;
}
/// [used] is an address a probe actually connected to or sent to.
/// [resolved] is only the lookup result and is never labeled as the address
/// in use. A remote sample that omits the address stays unreported.
AddressLines describeAddress({
required List<ResolvedAddress> resolved,
String? usedAddress,
String? usedFamily,
String? tryingAddress,
String? tryingFamily,
String fallbackText = '',
bool addressUnreported = false,
bool usedIsFake = false,
}) {
final hasUsed = usedAddress != null && usedAddress.isNotEmpty;
String? used;
if (hasUsed) {
final family = (usedFamily == null || usedFamily.isEmpty)
? familyOfAddress(usedAddress)
: usedFamily;
used = family.isEmpty ? '实际地址 $usedAddress' : '实际地址 $usedAddress($family)';
}
String? trying;
if (!hasUsed && tryingAddress != null && tryingAddress.isNotEmpty) {
final family = (tryingFamily == null || tryingFamily.isEmpty)
? ''
: '($tryingFamily)';
trying = '正在尝试 $tryingAddress$family,还没有正式结果';
}
String? resolvedLine;
if (resolved.isNotEmpty) {
final sameSingle =
resolved.length == 1 &&
hasUsed &&
resolved.single.address == usedAddress;
if (!sameSingle) {
final text = resolved
.map((item) {
final family = item.family.isEmpty ? '' : '(${item.family})';
return '${item.address}$family';
})
.join('、');
resolvedLine = '解析到 $text';
}
}
return AddressLines(
used: used,
trying: trying,
resolved: resolvedLine,
fallback: fallbackText.isEmpty ? null : fallbackText,
unreported: addressUnreported && !hasUsed ? '节点没有报告实际使用的地址' : null,
fake: usedIsFake && hasUsed,
);
}
List<ResolvedAddress> readResolvedList(Object? parsed) {
if (parsed is! Map) {
return const [];
}
final raw = parsed['resolved'];
if (raw is! List) {
return const [];
}
final out = <ResolvedAddress>[];
for (final item in raw) {
if (item is! Map) {
continue;
}
final address = item['address'];
if (address is! String || address.isEmpty) {
continue;
}
final family = item['family'];
out.add(
ResolvedAddress(
address: address,
family: family is String && family.isNotEmpty
? family
: familyOfAddress(address),
),
);
}
return out;
}
+50
View File
@@ -0,0 +1,50 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
const chartPinEpsilon = 0.0001;
class ChartSelection {
const ChartSelection({required this.sec, required this.sessionId});
final double sec;
final int sessionId;
}
/// A tap chooses the nearest sample and keeps it after the pointer is
/// released. A new session, an empty series, or a point that has scrolled
/// off the front of the window clears the pin instead of jumping to another
/// sample. [tappedSec] null means "keep the current pin if it is still valid".
ChartSelection? nextChartSelection({
required ChartSelection? current,
required int sessionId,
required List<double> sampleSecs,
double? tappedSec,
}) {
if (tappedSec != null) {
double? nearest;
var best = double.infinity;
for (final sec in sampleSecs) {
final distance = (sec - tappedSec).abs();
if (distance < best) {
best = distance;
nearest = sec;
}
}
if (nearest == null) {
return null;
}
return ChartSelection(sec: nearest, sessionId: sessionId);
}
if (current == null || current.sessionId != sessionId || sampleSecs.isEmpty) {
return null;
}
if (current.sec + chartPinEpsilon < sampleSecs.first) {
return null;
}
for (final sec in sampleSecs) {
if ((sec - current.sec).abs() <= chartPinEpsilon) {
return current;
}
}
return null;
}
+90
View File
@@ -0,0 +1,90 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'package:flutter/material.dart';
import '../content/release_history.dart';
import '../version.dart';
import 'quality_charts.dart';
class HistoryPage extends StatelessWidget {
const HistoryPage({super.key});
@override
Widget build(BuildContext context) {
final wide = MediaQuery.sizeOf(context).width >= 720;
return Scaffold(
appBar: AppBar(
title: const Text('更新历史'),
backgroundColor: const Color(0xFFF3F1EC),
),
body: SafeArea(
child: Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 760),
child: ListView(
padding: EdgeInsets.fromLTRB(
wide ? 24 : 12,
8,
wide ? 24 : 12,
28,
),
children: [
Text(
'当前版本 $appVersion(构建 $appBuild) · 署名 $appAttribution · $appLicense',
style: const TextStyle(
color: ink,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 8),
const Text(
releaseHistoryNote,
style: TextStyle(color: muted, height: 1.4),
),
const SizedBox(height: 12),
for (final entry in releaseHistory) _entry(entry),
],
),
),
),
),
);
}
Widget _entry(ReleaseEntry entry) {
return Card(
margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: line),
),
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
entry.title,
style: const TextStyle(fontWeight: FontWeight.w700, color: ink),
),
const SizedBox(height: 6),
Text(
entry.published == null
? entry.source
: '${entry.published} · ${entry.source}',
style: const TextStyle(color: muted, fontSize: 13, height: 1.4),
),
const SizedBox(height: 8),
for (final point in entry.points)
Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Text('· $point', style: const TextStyle(height: 1.4)),
),
],
),
),
);
}
}
+269 -46
View File
@@ -2,6 +2,8 @@ import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../models/node_edit.dart';
import '../models/port_field.dart';
import '../models/probe_profile.dart'; import '../models/probe_profile.dart';
import '../models/session_config.dart'; import '../models/session_config.dart';
import '../probe/endpoint_picker.dart'; import '../probe/endpoint_picker.dart';
@@ -9,7 +11,11 @@ import '../probe/probe_controller.dart';
import '../probe/remote_client.dart'; import '../probe/remote_client.dart';
import '../storage/app_store.dart'; import '../storage/app_store.dart';
import '../storage/token_vault.dart'; import '../storage/token_vault.dart';
import 'address_text.dart';
import 'format.dart'; import 'format.dart';
import 'history_page.dart';
import 'metric_guide_page.dart';
import 'metrics_panel.dart';
import 'quality_charts.dart'; import 'quality_charts.dart';
class HomePage extends StatefulWidget { class HomePage extends StatefulWidget {
@@ -134,7 +140,11 @@ class _HomePageState extends State<HomePage> {
final nodeToken = config.node == null final nodeToken = config.node == null
? '' ? ''
: (await _vault.read(nodeTokenKey(config.node!.id)) ?? ''); : (await _vault.read(nodeTokenKey(config.node!.id)) ?? '');
await _controller.start(config, nodeToken: nodeToken, echoToken: _echo.text); await _controller.start(
config,
nodeToken: nodeToken,
echoToken: _echo.text,
);
} }
void _changeProfile(String? id) { void _changeProfile(String? id) {
@@ -144,9 +154,11 @@ class _HomePageState extends State<HomePage> {
final previous = ProbeProfile.byId(_profileId); final previous = ProbeProfile.byId(_profileId);
final next = ProbeProfile.byId(id); final next = ProbeProfile.byId(id);
setState(() { setState(() {
if (_port.text.trim() == '${previous.port}') { _port.text = portAfterProfileChange(
_port.text = '${next.port}'; current: _port.text,
} previousDefault: previous.port,
nextDefault: next.port,
);
_profileId = id; _profileId = id;
}); });
} }
@@ -160,6 +172,22 @@ class _HomePageState extends State<HomePage> {
appBar: AppBar( appBar: AppBar(
title: const Text('网络质量探测'), title: const Text('网络质量探测'),
backgroundColor: const Color(0xFFF3F1EC), backgroundColor: const Color(0xFFF3F1EC),
actions: [
PopupMenuButton<String>(
tooltip: '说明',
onSelected: (value) {
final page = value == 'history'
? const HistoryPage()
: const MetricGuidePage();
Navigator.of(context)
.push(MaterialPageRoute<void>(builder: (_) => page));
},
itemBuilder: (context) => const [
PopupMenuItem(value: 'metrics', child: Text('指标说明')),
PopupMenuItem(value: 'history', child: Text('更新历史')),
],
),
],
), ),
body: SafeArea( body: SafeArea(
child: Align( child: Align(
@@ -167,12 +195,14 @@ class _HomePageState extends State<HomePage> {
child: ConstrainedBox( child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 880), constraints: const BoxConstraints(maxWidth: 880),
child: ListView( child: ListView(
padding: EdgeInsets.fromLTRB(wide ? 24 : 12, 8, wide ? 24 : 12, 28), padding: EdgeInsets.fromLTRB(
wide ? 24 : 12,
8,
wide ? 24 : 12,
28,
),
children: [ children: [
_card( _card(title: '探测来源', child: _source(view, wide)),
title: '探测来源',
child: _source(view, wide),
),
_card( _card(
title: '目标', title: '目标',
child: Column( child: Column(
@@ -181,7 +211,13 @@ class _HomePageState extends State<HomePage> {
_pair( _pair(
wide, wide,
_field(_host, '目标地址', '域名或 IP'), _field(_host, '目标地址', '域名或 IP'),
_field(_port, '端口', '1–65535'), _field(
_port,
'端口',
portHint(profile),
fieldKey: const Key('port-field'),
helper: portHelperText,
),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
DropdownButtonFormField<String>( DropdownButtonFormField<String>(
@@ -190,12 +226,18 @@ class _HomePageState extends State<HomePage> {
decoration: const InputDecoration(labelText: '探测类型'), decoration: const InputDecoration(labelText: '探测类型'),
items: [ items: [
for (final item in ProbeProfile.all) for (final item in ProbeProfile.all)
DropdownMenuItem(value: item.id, child: Text(item.label)), DropdownMenuItem(
value: item.id,
child: Text(item.label),
),
], ],
onChanged: view.running ? null : _changeProfile, onChanged: view.running ? null : _changeProfile,
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text(profile.blurb, style: const TextStyle(color: muted, fontSize: 13)), Text(
profile.blurb,
style: const TextStyle(color: muted, fontSize: 13),
),
], ],
), ),
), ),
@@ -206,7 +248,11 @@ class _HomePageState extends State<HomePage> {
children: [ children: [
_pair( _pair(
wide, wide,
_field(_interval, '间隔(毫秒)', _remote ? '至少 200' : '至少 100'), _field(
_interval,
'间隔(毫秒)',
_remote ? '至少 200' : '至少 100',
),
_field(_timeout, '超时(毫秒)', '100–15000'), _field(_timeout, '超时(毫秒)', '100–15000'),
), ),
if (profile.needsPacketSize) ...[ if (profile.needsPacketSize) ...[
@@ -252,11 +298,44 @@ class _HomePageState extends State<HomePage> {
_banner(view.banner!), _banner(view.banner!),
], ],
const SizedBox(height: 12), const SizedBox(height: 12),
_card(title: '结果', child: _result(view)), _card(
title: '结果',
child: _result(
view,
view.profileId.isEmpty ? profile.id : view.profileId,
),
),
if (view.report != null)
SessionSummaryCard(
report: view.report!,
profileId: view.report!.profileId,
),
QualityCharts( QualityCharts(
samples: view.samples, samples: view.samples,
rateLabel: view.rateLabel, rateLabel: view.rateLabel,
running: view.running, running: view.running,
sessionId: view.sessionId,
),
Wrap(
spacing: 8,
children: [
TextButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => const MetricGuidePage(),
),
),
child: const Text('指标说明'),
),
TextButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => const HistoryPage(),
),
),
child: const Text('更新历史'),
),
],
), ),
const Text( const Text(
'延迟用发包一侧的单调时钟计算。远程探测时,这个时间在节点上量好再传回来,不包含手机到节点的控制通道耗时。TCP 超时不是物理丢包。没有协议应答的 UDP 记为无应答/未知,不会在探测完成前显示 100%。', '延迟用发包一侧的单调时钟计算。远程探测时,这个时间在节点上量好再传回来,不包含手机到节点的控制通道耗时。TCP 超时不是物理丢包。没有协议应答的 UDP 记为无应答/未知,不会在探测完成前显示 100%。',
@@ -271,17 +350,25 @@ class _HomePageState extends State<HomePage> {
} }
Widget _source(ProbeView view, bool wide) { Widget _source(ProbeView view, bool wide) {
final selected = _nodes.cast<RemoteNode?>().followedBy(const [null]).firstWhere( final selected = _nodes
(node) => node?.id == _nodeId, .cast<RemoteNode?>()
orElse: () => null, .followedBy(const [null])
); .firstWhere((node) => node?.id == _nodeId, orElse: () => null);
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
SegmentedButton<bool>( SegmentedButton<bool>(
segments: const [ segments: const [
ButtonSegment(value: false, label: Text('本机'), icon: Icon(Icons.phone_android)), ButtonSegment(
ButtonSegment(value: true, label: Text('远程节点'), icon: Icon(Icons.dns_outlined)), value: false,
label: Text('本机'),
icon: Icon(Icons.phone_android),
),
ButtonSegment(
value: true,
label: Text('远程节点'),
icon: Icon(Icons.dns_outlined),
),
], ],
selected: {_remote}, selected: {_remote},
onSelectionChanged: view.running onSelectionChanged: view.running
@@ -290,9 +377,7 @@ class _HomePageState extends State<HomePage> {
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
_remote _remote ? '由选中的节点向目标发包,这台设备只负责控制和显示。' : '由这台设备直接向目标发包。可以探测本机上的反射器。',
? '由选中的节点向目标发包,这台设备只负责控制和显示。'
: '由这台设备直接向目标发包。可以探测本机上的反射器。',
style: const TextStyle(color: muted, fontSize: 13), style: const TextStyle(color: muted, fontSize: 13),
), ),
if (_remote) ...[ if (_remote) ...[
@@ -338,13 +423,18 @@ class _HomePageState extends State<HomePage> {
return '${node.name} · $vis'; return '${node.name} · $vis';
} }
Widget _result(ProbeView view) { Widget _result(ProbeView view, String profileId) {
final summary = view.summary; final summary = view.summary;
final rate = view.rateLabel == '探测无应答' final address = describeAddress(
? summary.probeLossPct resolved: view.resolved,
: view.rateLabel == '失败率' usedAddress: view.usedAddress,
? summary.failurePct usedFamily: view.usedFamily,
: summary.unknownPct; tryingAddress: view.tryingAddress,
tryingFamily: view.tryingFamily,
fallbackText: view.fallbackText,
addressUnreported: view.addressUnreported,
usedIsFake: view.usedIsFake,
);
final motd = view.detail['motd']; final motd = view.detail['motd'];
final version = view.detail['version']; final version = view.detail['version'];
final players = view.detail['players']; final players = view.detail['players'];
@@ -357,13 +447,42 @@ class _HomePageState extends State<HomePage> {
children: [ children: [
_chip(view.phase), _chip(view.phase),
_chip('来源 ${view.sourceLabel}'), _chip('来源 ${view.sourceLabel}'),
if (view.targetAddress != null) _chip('发往 ${view.targetAddress}'), if (view.targetHost.isNotEmpty) _chip(view.targetHost),
_chip('延迟 ${formatMs(summary.rttMs)}'),
_chip('抖动 ${formatMs(summary.jitterMs)}'),
_chip('${view.rateLabel} ${formatPct(rate)}'),
], ],
), ),
if (view.targetIsFake) ...[ const SizedBox(height: 8),
MetricsPanel(
summary: summary,
profileId: profileId,
elapsed: view.elapsed,
),
if (address.trying != null) ...[
const SizedBox(height: 8),
Text(address.trying!, style: const TextStyle(color: ink)),
],
if (address.used != null) ...[
const SizedBox(height: 8),
Text(address.used!, style: const TextStyle(color: ink)),
],
if (address.resolved != null) ...[
const SizedBox(height: 8),
Text(
address.resolved!,
style: const TextStyle(color: muted, fontSize: 13),
),
],
if (address.unreported != null) ...[
const SizedBox(height: 8),
Text(
address.unreported!,
style: const TextStyle(color: Color(0xFF9A3412)),
),
],
if (address.fallback != null) ...[
const SizedBox(height: 8),
Text(address.fallback!, style: const TextStyle(color: ink)),
],
if (address.fake) ...[
const SizedBox(height: 8), const SizedBox(height: 8),
const Text( const Text(
clashFakeIpNote, clashFakeIpNote,
@@ -386,7 +505,10 @@ class _HomePageState extends State<HomePage> {
), ),
], ],
const SizedBox(height: 8), const SizedBox(height: 8),
Text(summaryLine(summary), style: const TextStyle(color: muted, fontSize: 13)), Text(
summaryLine(summary),
style: const TextStyle(color: muted, fontSize: 13),
),
], ],
); );
} }
@@ -434,6 +556,7 @@ class _NodeDialogState extends State<_NodeDialog> {
final _name = TextEditingController(); final _name = TextEditingController();
final _url = TextEditingController(); final _url = TextEditingController();
final _token = TextEditingController(); final _token = TextEditingController();
String? _editingId;
String? _hint; String? _hint;
@override @override
@@ -450,6 +573,41 @@ class _NodeDialogState extends State<_NodeDialog> {
setState(() => _hint = '请填写名称,以及不带口令的 http 或 https 地址'); setState(() => _hint = '请填写名称,以及不带口令的 http 或 https 地址');
return; return;
} }
final editing = _editingId;
if (editing != null) {
RemoteNode? previous;
for (final node in _nodes) {
if (node.id == editing) {
previous = node;
}
}
if (previous == null) {
return;
}
final next = applyNodeEdit(
previous,
name: _name.text.trim(),
baseUrl: url,
);
final replaced = await saveEditedNodeToken(
widget.vault,
editing,
_token.text,
);
setState(() {
_nodes = [
for (final node in _nodes)
if (node.id == editing) next else node,
];
_editingId = null;
_hint = replaced ? '已更新,口令已替换,仍只留在本机。' : '已更新。口令留空,原来的口令未改。';
_name.clear();
_url.clear();
_token.clear();
});
widget.onChanged(_nodes, editing);
return;
}
final id = DateTime.now().microsecondsSinceEpoch.toString(); final id = DateTime.now().microsecondsSinceEpoch.toString();
final node = RemoteNode(id: id, name: _name.text.trim(), baseUrl: url); final node = RemoteNode(id: id, name: _name.text.trim(), baseUrl: url);
await widget.vault.write(nodeTokenKey(id), _token.text.trim()); await widget.vault.write(nodeTokenKey(id), _token.text.trim());
@@ -463,6 +621,26 @@ class _NodeDialogState extends State<_NodeDialog> {
widget.onChanged(_nodes, id); widget.onChanged(_nodes, id);
} }
void _beginEdit(RemoteNode node) {
setState(() {
_editingId = node.id;
_name.text = node.name;
_url.text = node.baseUrl;
_token.clear();
_hint = '正在修改「${node.name}」。口令留空则保留已保存的口令,不会显示原口令。';
});
}
void _cancelEdit() {
setState(() {
_editingId = null;
_name.clear();
_url.clear();
_token.clear();
_hint = null;
});
}
Future<void> _check(RemoteNode node) async { Future<void> _check(RemoteNode node) async {
try { try {
final info = await fetchNodeInfo(node.baseUrl); final info = await fetchNodeInfo(node.baseUrl);
@@ -487,7 +665,10 @@ class _NodeDialogState extends State<_NodeDialog> {
Future<void> _delete(RemoteNode node) async { Future<void> _delete(RemoteNode node) async {
await widget.vault.delete(nodeTokenKey(node.id)); await widget.vault.delete(nodeTokenKey(node.id));
final next = [for (final item in _nodes) if (item.id != node.id) item]; final next = [
for (final item in _nodes)
if (item.id != node.id) item,
];
setState(() => _nodes = next); setState(() => _nodes = next);
widget.onChanged(next, null); widget.onChanged(next, null);
} }
@@ -510,22 +691,41 @@ class _NodeDialogState extends State<_NodeDialog> {
for (final node in _nodes) for (final node in _nodes)
ListTile( ListTile(
contentPadding: EdgeInsets.zero, contentPadding: EdgeInsets.zero,
title: Text(_nodes.isEmpty ? '' : '${node.name} · ${visibilityLabel(node.visibility)}'), title: Text(
subtitle: Text(node.baseUrl, maxLines: 1, overflow: TextOverflow.ellipsis), '${node.name} · ${visibilityLabel(node.visibility)}',
),
subtitle: Text(
node.baseUrl,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
trailing: Wrap( trailing: Wrap(
spacing: 4, spacing: 4,
children: [ children: [
TextButton(onPressed: () => _check(node), child: const Text('检查')), TextButton(
TextButton(onPressed: () => _delete(node), child: const Text('删除')), key: Key('edit-node-${node.id}'),
onPressed: () => _beginEdit(node),
child: const Text('编辑'),
),
TextButton(
onPressed: () => _check(node),
child: const Text('检查'),
),
TextButton(
onPressed: () => _delete(node),
child: const Text('删除'),
),
], ],
), ),
), ),
TextField( TextField(
key: const Key('node-name'),
controller: _name, controller: _name,
decoration: const InputDecoration(labelText: '名称'), decoration: const InputDecoration(labelText: '名称'),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
TextField( TextField(
key: const Key('node-url'),
controller: _url, controller: _url,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: '节点地址', labelText: '节点地址',
@@ -534,10 +734,14 @@ class _NodeDialogState extends State<_NodeDialog> {
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
TextField( TextField(
key: const Key('node-token'),
controller: _token, controller: _token,
obscureText: true, obscureText: true,
decoration: const InputDecoration( decoration: InputDecoration(
labelText: '节点口令(公开节点留空)', labelText: _editingId == null ? '节点口令(公开节点留空)' : '新口令(留空则保留)',
helperText: _editingId == null
? null
: '留空则保留已保存的口令,不会显示原口令。',
), ),
), ),
if (_hint != null) ...[ if (_hint != null) ...[
@@ -549,8 +753,17 @@ class _NodeDialogState extends State<_NodeDialog> {
), ),
), ),
actions: [ actions: [
TextButton(onPressed: _save, child: const Text('添加节点')), if (_editingId != null)
TextButton(onPressed: () => Navigator.pop(context), child: const Text('完成')), TextButton(onPressed: _cancelEdit, child: const Text('取消编辑')),
TextButton(
key: const Key('node-save'),
onPressed: _save,
child: Text(_editingId == null ? '添加节点' : '保存修改'),
),
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('完成'),
),
], ],
); );
} }
@@ -568,7 +781,10 @@ Widget _card({required String title, required Widget child}) {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
Text(title, style: const TextStyle(fontWeight: FontWeight.w700, color: ink)), Text(
title,
style: const TextStyle(fontWeight: FontWeight.w700, color: ink),
),
const SizedBox(height: 10), const SizedBox(height: 10),
child, child,
], ],
@@ -582,11 +798,18 @@ Widget _field(
String label, String label,
String hint, { String hint, {
bool secret = false, bool secret = false,
Key? fieldKey,
String? helper,
}) { }) {
return TextField( return TextField(
key: fieldKey,
controller: controller, controller: controller,
obscureText: secret, obscureText: secret,
decoration: InputDecoration(labelText: label, hintText: hint), decoration: InputDecoration(
labelText: label,
hintText: hint,
helperText: helper,
),
); );
} }
+103
View File
@@ -0,0 +1,103 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'package:flutter/material.dart';
import 'quality_charts.dart';
class MetricGuidePage extends StatelessWidget {
const MetricGuidePage({super.key});
@override
Widget build(BuildContext context) {
final wide = MediaQuery.sizeOf(context).width >= 720;
return Scaffold(
appBar: AppBar(
title: const Text('指标说明'),
backgroundColor: const Color(0xFFF3F1EC),
),
body: SafeArea(
child: Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 760),
child: ListView(
padding: EdgeInsets.fromLTRB(
wide ? 24 : 12,
8,
wide ? 24 : 12,
28,
),
children: const [
_Section(
title: '这些数字从哪来',
body: '曲线和百分比只来自已经完成、并且计入正式结果的探测。还在途中的请求不会画成 100%,停止时被取消的请求也不算丢包。没有内置样本。',
),
_Section(
title: '已发送、已收到、超时',
body: '已发送是计入正式结果的次数。已收到是其中成功的次数:合作反射收到了对上序号的回显,普通 TCP 是连上了,其他类型是收到了符合协议的应答。\n\n合作反射的「超时」只计已经把探测帧写出去、但超时前没有对上序号的次数。还没连上、连接被拒绝,不算进这个超时,也不算进探测无应答。\n\n普通 UDP、DNS、自定义 UDP 和基岩版如果根本没有协议应答,记为「无应答」,超时这一项显示不适用。收到了包但内容不对,记为协议错误。UDP 沉默不能当成已经证实的丢包:对端可以合法地不回答。',
),
_Section(
title: '探测无应答、失败率、无应答',
body: '合作反射 TCP / UDP:探测无应答 = 超时 ÷(超时 + 成功)× 100%。分母只含已经写出的回显尝试。分母为 0 时显示 —,而不是 0%。TCP 会重传,所以这不是网卡上的物理丢包。\n\n普通 TCP 和 Minecraft Java:失败率 = 未成功的正式尝试 ÷ 已完成的正式尝试 × 100%。这里没有丢包百分比。\n\n其余 UDP 类探测:无应答 = 无应答次数 ÷ 已完成次数 × 100%。它回答的是「没有看到协议应答」,不是「丢了多少包」。',
),
_Section(
title: '延迟、中位数、P95 和抖动',
body: '延迟只来自成功的样本,单位是毫秒。当前延迟是最近一次成功的往返时间。最小、平均、最大都是这些成功样本的最小、算术平均和最大。\n\n中位数:把成功样本从小到大排列。奇数个取中间那个;偶数个取中间两个的平均。\n\nP95 用最近秩:秩 = ceil(0.95 × 次数),用整数 (95 × 次数 + 99) / 100 计算,从 1 开始,取排序后这个位置的值。次数为 1 时,P95 就是那一次。\n\n抖动按 RFC 3550:D 是相邻两次成功往返时间之差,J = J + (|D| − J) / 16。第一次成功时 J 为 0;没有成功时显示 —。远程探测的往返时间在节点上用单调时钟量好再传回来,不包含手机到节点的控制通道耗时。\n\n旧版本节点不会上报最小、平均、中位、P95 和最大。这时这些格子显示「节点未提供」,当前延迟和抖动仍用它原来上报的值。',
),
_Section(
title: '用时',
body: '用时是这次会话从按下开始到停止(或到当前)的墙钟时间。它不是各次往返时间相加,也不包括节点在创建任务之前花掉的时间。',
),
_Section(
title: '选址失败和正式丢包',
body: '一个域名可能同时有 IPv6 和 IPv4。程序会先试一个地址。还没有任何地址应答时,连不上或没有应答会换下一个。这种只为挑选地址而失败的尝试,如果后面有地址成功,就不计入已发送、超时和丢包,界面单独写明回退了哪个地址。\n\n一旦某个地址已经应答,之后对它的超时或失败都算正式结果,不会因为后来又换地址而被抹掉。只有一个地址时,失败从一开始就算正式结果。\n\n如果每一个候选都失败,这些失败会计入正式结果。界面显示失败或 100% 的无应答/失败率,不会显示 0% 成功。\n\n1.1.1 的远程节点还不会做这层区分,它的统计可能仍把第一次选址失败算进去。要分开看,节点也需要 1.1.2。',
),
_Section(
title: '实际地址和 IPv6 回退',
body: '「实际地址」是这次真正连通或真正发包的 IP,并注明 IPv4 或 IPv6。「解析到」只是域名解析的结果,不会被说成已经在用的地址。\n\n正在尝试、还没有正式结果时,会标明正在尝试,而不是写成已经发往。远程节点如果没有在结果里带上地址(旧版本就是这样),界面写「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。\n\n地址落在 198.18.0.0/15 时,会提示这是 VPN 假地址,只有这个 VPN 开着时才能用。',
),
_Section(
title: '停止以后',
body: '点停止会保留曲线,并给出开始、结束、用时、目标、类型、来源、实际地址和同一套最终指标。正在进行、因为停止而被取消的请求不计入丢包。重新开始会换一次新的会话,旧曲线不会混进来。\n\n点曲线上的一点可以钉住该时刻的延迟和比率,松手后仍然留着。再点另一点会换。新会话或这个点滚出窗口后,选择会被清掉,不会跳到别的点上。',
),
],
),
),
),
),
);
}
}
class _Section extends StatelessWidget {
const _Section({required this.title, required this.body});
final String title;
final String body;
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: line),
),
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
title,
style: const TextStyle(fontWeight: FontWeight.w700, color: ink),
),
const SizedBox(height: 8),
Text(body, style: const TextStyle(height: 1.45, color: ink)),
],
),
),
);
}
}
+271
View File
@@ -0,0 +1,271 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'package:flutter/material.dart';
import '../metrics/sample_book.dart';
import '../probe/endpoint_picker.dart';
import '../probe/probe_controller.dart';
import 'address_text.dart';
import 'format.dart';
import 'quality_charts.dart';
class MetricLine {
const MetricLine(this.label, this.value, {this.detail});
final String label;
final String value;
final String? detail;
}
/// Rows use the same summary the live view and the stopped session share.
/// A metric that this profile does not measure is marked unsupported instead
/// of being shown as zero.
List<MetricLine> metricLines({
required ProbeSummary summary,
required String profileId,
required Duration elapsed,
}) {
final lines = <MetricLine>[
MetricLine(
'已发送',
'${summary.sent}',
detail: summary.selectionSkipped > 0
? '正式结果 ${summary.sent} 次。另有 ${summary.selectionSkipped} 次选址失败未计入。'
: '只计已经计入正式结果的次数,不含还在途中的探测。',
),
MetricLine('已收到', '${summary.ok}', detail: '成功收到应答,或成功连通的次数。'),
_timeoutLine(summary, profileId),
_rateLine(summary, profileId),
_latency('当前延迟', summary.rttMs, summary, recent: true),
_latency('最小延迟', summary.minRttMs, summary),
_latency('平均延迟', summary.meanRttMs, summary),
_latency('中位延迟', summary.medianRttMs, summary),
_latency('P95 延迟', summary.p95RttMs, summary),
_latency('最大延迟', summary.maxRttMs, summary),
MetricLine(
'抖动',
summary.jitterMs == null ? '—' : formatMs(summary.jitterMs),
detail: 'RFC 3550:J = J + (|D| − J) / 16。D 是相邻两次成功往返时间之差。只有一次成功时 J 为 0。',
),
MetricLine(
'用时',
formatDuration(elapsed),
detail: '从这次探测开始到现在或到停止的墙钟时间,不是往返时间相加。',
),
];
return lines;
}
MetricLine _timeoutLine(ProbeSummary summary, String profileId) {
switch (profileId) {
case 'nq-tcp':
case 'nq-udp':
return MetricLine(
'超时',
'${summary.timeout}',
detail: '已经写出回显帧、在超时前没有对上序号的次数。连接失败另计,不在这里。',
);
case 'tcp-connect':
case 'minecraft-java':
return const MetricLine('超时', '不适用', detail: '这种探测把连不上记为失败,不单独叫探测超时。');
default:
return MetricLine(
'超时',
'不适用',
detail: '没有协议应答时记为无应答 ${summary.unknown} 次,不能据此断定丢包。',
);
}
}
MetricLine _rateLine(ProbeSummary summary, String profileId) {
switch (profileId) {
case 'nq-tcp':
case 'nq-udp':
final denom = summary.timeout + summary.ok;
return MetricLine(
'探测无应答',
formatPct(summary.probeLossPct),
detail: denom == 0
? '还没有完成的回显尝试,所以不显示 0%。'
: '超时 ÷(超时 + 成功)= ${summary.timeout} ÷ $denom。连接失败不在分母里。',
);
case 'tcp-connect':
case 'minecraft-java':
return MetricLine(
'失败率',
formatPct(summary.failurePct),
detail: '未成功的正式尝试 ÷ 已完成的正式尝试。这不是物理丢包。',
);
default:
return MetricLine(
'无应答(未知)',
formatPct(summary.unknownPct),
detail: '无应答 ÷ 已完成。沉默不是丢包;明确的协议错误、拒绝和域名失败另看失败次数。',
);
}
}
MetricLine _latency(
String label,
double? value,
ProbeSummary summary, {
bool recent = false,
}) {
if (!summary.latencyStats && summary.ok > 0 && !recent) {
return MetricLine(label, '节点未提供', detail: '这份结果来自没有上报延迟分布的节点。当前延迟仍然可用。');
}
return MetricLine(
label,
formatMs(value),
detail: recent ? '最近一次成功的往返时间。没有成功时为 —。' : '只统计成功样本。没有成功时为 —。',
);
}
String formatDuration(Duration duration) {
final ms = duration.inMilliseconds;
if (ms < 0) {
return '—';
}
if (ms < 1000) {
return '$ms 毫秒';
}
final seconds = ms / 1000;
if (seconds < 60) {
return '${seconds.toStringAsFixed(1)} 秒';
}
final minutes = duration.inMinutes;
final rest = duration.inSeconds % 60;
return '$minutes 分 $rest 秒';
}
String formatClock(DateTime time) {
final local = time.toLocal();
String two(int value) => value.toString().padLeft(2, '0');
return '${local.year}-${two(local.month)}-${two(local.day)} ${two(local.hour)}:${two(local.minute)}:${two(local.second)}';
}
class MetricsPanel extends StatelessWidget {
const MetricsPanel({
super.key,
required this.summary,
required this.profileId,
required this.elapsed,
});
final ProbeSummary summary;
final String profileId;
final Duration elapsed;
@override
Widget build(BuildContext context) {
final lines = metricLines(
summary: summary,
profileId: profileId,
elapsed: elapsed,
);
return Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final line in lines)
Tooltip(
message: line.detail ?? '',
child: _chip('${line.label} ${line.value}'),
),
],
);
}
}
class SessionSummaryCard extends StatelessWidget {
const SessionSummaryCard({
super.key,
required this.report,
required this.profileId,
});
final SessionReport report;
final String profileId;
@override
Widget build(BuildContext context) {
final address = describeAddress(
resolved: report.resolved,
usedAddress: report.usedAddress,
usedFamily: report.usedFamily,
fallbackText: report.fallbackText,
addressUnreported: report.addressUnreported,
usedIsFake: report.usedIsFake,
);
return _panel(
title: '本次结果',
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('开始 ${formatClock(report.startedAt)}'),
Text('结束 ${formatClock(report.endedAt)}'),
Text('用时 ${formatDuration(report.elapsed)}'),
Text('目标 ${report.target}'),
Text('类型 ${report.profileLabel}'),
Text('来源 ${report.sourceLabel}'),
if (address.used != null) Text(address.used!),
if (address.resolved != null) Text(address.resolved!),
if (address.unreported != null) Text(address.unreported!),
if (address.fallback != null) Text(address.fallback!),
if (address.fake)
const Text(
clashFakeIpNote,
style: TextStyle(color: Color(0xFF9A3412)),
),
const SizedBox(height: 8),
MetricsPanel(
summary: report.summary,
profileId: profileId,
elapsed: report.elapsed,
),
const SizedBox(height: 8),
Text(
summaryLine(report.summary),
style: const TextStyle(color: muted, fontSize: 13),
),
],
),
);
}
}
Widget _panel({required String title, required Widget child}) {
return Card(
margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: line),
),
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
title,
style: const TextStyle(fontWeight: FontWeight.w700, color: ink),
),
const SizedBox(height: 10),
child,
],
),
),
);
}
Widget _chip(String text) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFFE7EEF5),
borderRadius: BorderRadius.circular(99),
),
child: Text(text, style: const TextStyle(fontSize: 12, color: ink)),
);
}
+126 -16
View File
@@ -2,6 +2,8 @@ import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../probe/probe_controller.dart'; import '../probe/probe_controller.dart';
import 'chart_selection.dart';
import 'format.dart';
const rttColor = Color(0xFF1F4E79); const rttColor = Color(0xFF1F4E79);
const rateColor = Color(0xFF9A3412); const rateColor = Color(0xFF9A3412);
@@ -9,20 +11,67 @@ const ink = Color(0xFF1C2430);
const muted = Color(0xFF5E6872); const muted = Color(0xFF5E6872);
const line = Color(0xFFE4DFD4); const line = Color(0xFFE4DFD4);
class QualityCharts extends StatelessWidget { class QualityCharts extends StatefulWidget {
const QualityCharts({ const QualityCharts({
super.key, super.key,
required this.samples, required this.samples,
required this.rateLabel, required this.rateLabel,
required this.running, required this.running,
required this.sessionId,
}); });
final List<ChartSample> samples; final List<ChartSample> samples;
final String rateLabel; final String rateLabel;
final bool running; final bool running;
final int sessionId;
@override
State<QualityCharts> createState() => _QualityChartsState();
}
class _QualityChartsState extends State<QualityCharts> {
ChartSelection? _pin;
@override
void didUpdateWidget(QualityCharts oldWidget) {
super.didUpdateWidget(oldWidget);
final kept = nextChartSelection(
current: _pin,
sessionId: widget.sessionId,
sampleSecs: [for (final sample in widget.samples) sample.sec],
);
if (kept?.sec != _pin?.sec || kept?.sessionId != _pin?.sessionId) {
_pin = kept;
}
}
void _pinAt(double sec) {
setState(() {
_pin = nextChartSelection(
current: _pin,
sessionId: widget.sessionId,
sampleSecs: [for (final sample in widget.samples) sample.sec],
tappedSec: sec,
);
});
}
ChartSample? get _pinnedSample {
final pin = _pin;
if (pin == null || pin.sessionId != widget.sessionId) {
return null;
}
for (final sample in widget.samples) {
if ((sample.sec - pin.sec).abs() <= chartPinEpsilon) {
return sample;
}
}
return null;
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final pinned = _pinnedSample;
return Column( return Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
@@ -34,29 +83,51 @@ class QualityCharts extends StatelessWidget {
], ],
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text(
pinned == null
? '点曲线上的一点可以钉住该时刻,松手后仍会保留。再点另一点会更换。'
: pinnedReadout(pinned, widget.rateLabel),
key: const Key('chart-pin'),
style: const TextStyle(color: ink, fontSize: 13, height: 1.4),
),
const SizedBox(height: 8),
_ChartCard( _ChartCard(
title: '延迟', title: '延迟',
unit: 'ms', unit: 'ms',
samples: samples, samples: widget.samples,
read: (sample) => sample.rttMs, read: (sample) => sample.rttMs,
color: rttColor, color: rttColor,
floor: 1, floor: 1,
running: running, running: widget.running,
pinnedSec: pinned?.sec,
onPin: _pinAt,
), ),
_ChartCard( _ChartCard(
title: rateLabel, title: widget.rateLabel,
unit: '%', unit: '%',
samples: samples, samples: widget.samples,
read: (sample) => sample.ratePct, read: (sample) => sample.ratePct,
color: rateColor, color: rateColor,
floor: 10, floor: 10,
running: running, running: widget.running,
pinnedSec: pinned?.sec,
onPin: _pinAt,
), ),
], ],
); );
} }
} }
String pinnedReadout(ChartSample sample, String rateLabel) {
final latency = sample.rttMs == null
? '这一刻没有延迟'
: '延迟 ${formatMs(sample.rttMs)}';
final rate = sample.ratePct == null
? '$rateLabel —'
: '$rateLabel ${formatPct(sample.ratePct)}';
return '已选 ${sample.sec.toStringAsFixed(1)} 秒 · $latency · $rate';
}
class _Swatch extends StatelessWidget { class _Swatch extends StatelessWidget {
const _Swatch({required this.color, required this.label}); const _Swatch({required this.color, required this.label});
@@ -92,6 +163,8 @@ class _ChartCard extends StatelessWidget {
required this.color, required this.color,
required this.floor, required this.floor,
required this.running, required this.running,
required this.pinnedSec,
required this.onPin,
}); });
final String title; final String title;
@@ -101,6 +174,8 @@ class _ChartCard extends StatelessWidget {
final Color color; final Color color;
final double floor; final double floor;
final bool running; final bool running;
final double? pinnedSec;
final void Function(double sec) onPin;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -132,9 +207,7 @@ class _ChartCard extends StatelessWidget {
? _lineChart(spots) ? _lineChart(spots)
: Center( : Center(
child: Text( child: Text(
running running ? '正在等待第一次完成的探测。未完成的不会画成 100%。' : '暂无已完成的探测',
? '正在等待第一次完成的探测。未完成的不会画成 100%。'
: '暂无已完成的探测',
style: const TextStyle(color: muted), style: const TextStyle(color: muted),
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
@@ -190,7 +263,8 @@ class _ChartCard extends StatelessWidget {
show: true, show: true,
drawVerticalLine: false, drawVerticalLine: false,
horizontalInterval: yInterval, horizontalInterval: yInterval,
getDrawingHorizontalLine: (_) => const FlLine(color: line, strokeWidth: 1), getDrawingHorizontalLine: (_) =>
const FlLine(color: line, strokeWidth: 1),
), ),
borderData: FlBorderData( borderData: FlBorderData(
show: true, show: true,
@@ -200,14 +274,19 @@ class _ChartCard extends StatelessWidget {
), ),
), ),
titlesData: FlTitlesData( titlesData: FlTitlesData(
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)), topTitles: const AxisTitles(
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)), sideTitles: SideTitles(showTitles: false),
),
rightTitles: const AxisTitles(
sideTitles: SideTitles(showTitles: false),
),
leftTitles: AxisTitles( leftTitles: AxisTitles(
sideTitles: SideTitles( sideTitles: SideTitles(
showTitles: true, showTitles: true,
reservedSize: 40, reservedSize: 40,
interval: yInterval, interval: yInterval,
getTitlesWidget: (value, meta) => _axisLabel(_formatTick(value, maxY)), getTitlesWidget: (value, meta) =>
_axisLabel(_formatTick(value, maxY)),
), ),
), ),
bottomTitles: AxisTitles( bottomTitles: AxisTitles(
@@ -220,15 +299,46 @@ class _ChartCard extends StatelessWidget {
), ),
), ),
), ),
lineTouchData: const LineTouchData(handleBuiltInTouches: true), extraLinesData: ExtraLinesData(
verticalLines: [
if (pinnedSec != null)
VerticalLine(
x: pinnedSec!,
color: color.withValues(alpha: 0.85),
strokeWidth: 1.5,
),
],
),
lineTouchData: LineTouchData(
handleBuiltInTouches: false,
touchSpotThreshold: 18,
touchCallback: (event, response) {
if (event is! FlTapUpEvent) {
return;
}
final spots = response?.lineBarSpots;
if (spots == null || spots.isEmpty) {
return;
}
onPin(spots.first.x);
},
),
lineBarsData: [ lineBarsData: [
LineChartBarData( LineChartBarData(
spots: spots, spots: spots,
isCurved: false, isCurved: false,
color: color, color: color,
barWidth: 2, barWidth: 2,
dotData: const FlDotData(show: false), dotData: FlDotData(
belowBarData: BarAreaData(show: true, color: color.withValues(alpha: 0.10)), show: pinnedSec != null,
checkToShowDot: (spot, _) =>
pinnedSec != null &&
(spot.x - pinnedSec!).abs() <= chartPinEpsilon,
),
belowBarData: BarAreaData(
show: true,
color: color.withValues(alpha: 0.10),
),
), ),
], ],
), ),
+7
View File
@@ -0,0 +1,7 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
const appVersion = '1.1.2';
const appBuild = 5;
const appAttribution = '言灸';
const appLicense = 'AGPL-3.0-only';
+1 -1
View File
@@ -1,6 +1,6 @@
# 网络质量探测 · Linux 桌面客户端 # 网络质量探测 · Linux 桌面客户端
这是 1.1.1 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。 这是 1.1.2 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。
## 先安装系统库 ## 先安装系统库
+1 -1
View File
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts # In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix. # of the product and file versions while build-number is used as the build suffix.
version: 1.1.1+4 version: 1.1.2+5
environment: environment:
sdk: ^3.13.7 sdk: ^3.13.7
+99
View File
@@ -0,0 +1,99 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/content/release_history.dart';
import 'package:netquality/metrics/sample_book.dart';
import 'package:netquality/ui/address_text.dart';
import 'package:netquality/ui/chart_selection.dart';
import 'package:netquality/version.dart';
void main() {
test('resolved addresses are not shown as the address in use', () {
const resolved = [
ResolvedAddress(address: '2001:db8::1', family: 'IPv6'),
ResolvedAddress(address: '203.0.113.5', family: 'IPv4'),
];
final onlyResolved = describeAddress(resolved: resolved);
expect(onlyResolved.used, isNull);
expect(onlyResolved.resolved, contains('解析到'));
expect(onlyResolved.resolved, contains('2001:db8::1'));
expect(onlyResolved.resolved, isNot(contains('实际地址')));
final used = describeAddress(
resolved: resolved,
usedAddress: '203.0.113.5',
usedFamily: 'IPv4',
fallbackText: '已改用 IPv4',
);
expect(used.used, '实际地址 203.0.113.5(IPv4)');
expect(used.resolved, contains('2001:db8::1'));
expect(used.fallback, '已改用 IPv4');
final oldNode = describeAddress(
resolved: const [],
addressUnreported: true,
);
expect(oldNode.used, isNull);
expect(oldNode.unreported, '节点没有报告实际使用的地址');
final missing = ProbeSample.fromJson({
'seq': 1,
'status': 'ok',
'kind': 'probe',
'rttMs': 3,
'summary': {'sent': 1, 'ok': 1},
});
expect(missing.detail['address'], isNull);
final parsed = readResolvedList({
'resolved': [
{'address': '2001:db8::1', 'family': 'IPv6'},
],
});
expect(parsed.single.address, '2001:db8::1');
expect(readResolvedList({'jobId': 'abc'}), isEmpty);
});
test('a pinned chart point stays put until it scrolls off or the session changes', () {
const first = ChartSelection(sec: 1.5, sessionId: 3);
final kept = nextChartSelection(
current: first,
sessionId: 3,
sampleSecs: [1.5, 2.5, 3.5],
);
expect(kept, same(first));
final moved = nextChartSelection(
current: first,
sessionId: 3,
sampleSecs: [1.5, 2.5, 3.5],
tappedSec: 2.4,
);
expect(moved!.sec, 2.5);
expect(moved.sessionId, 3);
expect(
nextChartSelection(current: moved, sessionId: 4, sampleSecs: [0.2, 0.4]),
isNull,
);
expect(
nextChartSelection(current: first, sessionId: 3, sampleSecs: [2.5, 3.5]),
isNull,
);
expect(
nextChartSelection(current: first, sessionId: 3, sampleSecs: const []),
isNull,
);
});
test('history only lists the real tag and this version', () {
expect(appVersion, '1.1.2');
expect(appBuild, 5);
expect(appAttribution, '言灸');
expect(releaseHistory.map((entry) => entry.version), ['1.1.2', '1.1.1']);
expect(releaseHistory.last.published, '2026-11-09');
expect(releaseHistory.last.source, contains('v1.1.1'));
expect(releaseHistoryNote, contains('不写成另一个版本'));
for (final entry in releaseHistory) {
expect(entry.version, isNot('1.1.0'));
expect(entry.version, isNot('1.0.0'));
}
});
}
+118
View File
@@ -0,0 +1,118 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
// The plot surface is not part of fl_chart's public API. The tap has to land
// on that surface, not on the axis titles around it.
// ignore_for_file: implementation_imports
import 'package:fl_chart/src/chart/line_chart/line_chart_renderer.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/probe/probe_controller.dart';
import 'package:netquality/ui/chart_selection.dart';
import 'package:netquality/ui/quality_charts.dart';
void main() {
test('a tap pins the nearest time and a later tap replaces it', () {
final first = nextChartSelection(
current: null,
sessionId: 3,
sampleSecs: const [1, 2, 4],
tappedSec: 2.2,
);
expect(first, isNotNull);
expect(first!.sec, 2);
expect(first.sessionId, 3);
final second = nextChartSelection(
current: first,
sessionId: 3,
sampleSecs: const [1, 2, 4],
tappedSec: 3.6,
);
expect(second!.sec, 4);
final kept = nextChartSelection(
current: second,
sessionId: 3,
sampleSecs: const [1, 2, 4],
);
expect(kept, same(second));
});
test('a new session or a point that rolled off does not jump', () {
const pin = ChartSelection(sec: 1, sessionId: 3);
expect(
nextChartSelection(current: pin, sessionId: 4, sampleSecs: const [1, 2]),
isNull,
);
expect(
nextChartSelection(current: pin, sessionId: 3, sampleSecs: const [2, 3]),
isNull,
);
expect(
nextChartSelection(current: pin, sessionId: 3, sampleSecs: const []),
isNull,
);
});
testWidgets('releasing a chart tap keeps the pinned readout', (tester) async {
const samples = [
ChartSample(sec: 0, rttMs: 10, ratePct: 0),
ChartSample(sec: 1, rttMs: 30, ratePct: 50),
];
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: QualityCharts(
samples: samples,
rateLabel: '探测无应答',
running: false,
sessionId: 1,
),
),
),
);
await tester.pumpAndSettle();
expect(find.textContaining('点曲线上的一点'), findsOneWidget);
final box = tester.getRect(find.byType(LineChartLeaf).first);
const maxY = 30 * 1.2;
Offset at(double sec, double value) {
final x = box.left + box.width * sec;
final y = box.top + (1 - value / maxY) * box.height;
return Offset(x.clamp(box.left + 2, box.right - 2), y);
}
await tester.tapAt(at(0, 10));
await tester.pump();
expect(find.textContaining('已选 0.0 秒'), findsOneWidget);
expect(find.textContaining('延迟'), findsWidgets);
final mouse = await tester.startGesture(
at(1, 30),
kind: PointerDeviceKind.mouse,
);
await mouse.up();
await tester.pump();
expect(find.textContaining('已选 1.0 秒'), findsOneWidget);
expect(find.textContaining('已选 0.0 秒'), findsNothing);
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: QualityCharts(
samples: [ChartSample(sec: 2, rttMs: 8, ratePct: 0)],
rateLabel: '探测无应答',
running: false,
sessionId: 1,
),
),
),
);
await tester.pump();
expect(find.textContaining('已选'), findsNothing);
expect(find.textContaining('点曲线上的一点'), findsOneWidget);
});
}
+102
View File
@@ -0,0 +1,102 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/metrics/latency.dart';
import 'package:netquality/metrics/sample_book.dart';
import 'package:netquality/ui/metrics_panel.dart';
void main() {
test('percentile ranks match the documented integer formula', () {
expect(nearestRank95(1), 1);
expect(nearestRank95(2), 2);
expect(nearestRank95(4), 4);
expect(nearestRank95(5), 5);
expect(nearestRank95(20), 19);
final one = LatencyStats.from([10]);
expect(one!.min, 10);
expect(one.mean, 10);
expect(one.median, 10);
expect(one.p95, 10);
expect(one.max, 10);
final two = LatencyStats.from([10, 30]);
expect(two!.median, 20);
expect(two.p95, 30);
expect(two.mean, 20);
final four = LatencyStats.from([1, 2, 3, 4]);
expect(four!.median, 2.5);
expect(four.p95, 4);
expect(four.min, 1);
expect(four.max, 4);
final five = LatencyStats.from([1, 2, 3, 4, 10]);
expect(five!.median, 3);
expect(five.p95, 10);
expect(five.mean, 4);
});
test('sample book keeps current rtt separate from the distribution', () {
final book = SampleBook('nq-udp');
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 1));
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 2));
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 3));
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 4));
final summary = book.summary();
expect(summary.rttMs, 4);
expect(summary.minRttMs, 1);
expect(summary.maxRttMs, 4);
expect(summary.medianRttMs, 2.5);
expect(summary.p95RttMs, 4);
expect(summary.meanRttMs, 2.5);
expect(summary.latencyStats, isTrue);
expect(summary.jitterMs, isNotNull);
});
test('unsupported rates stay blank instead of a false zero', () {
final silent = SampleBook('udp-generic')
..add(const Outcome(status: Outcome.unknown, kind: Outcome.query));
final lines = metricLines(
summary: silent.summary(),
profileId: 'udp-generic',
elapsed: const Duration(seconds: 2),
);
expect(_value(lines, '超时'), '不适用');
expect(_value(lines, '无应答(未知)'), '100%');
expect(_value(lines, '探测无应答'), isNull);
expect(_value(lines, '当前延迟'), '—');
final connect = SampleBook('tcp-connect');
final empty = metricLines(
summary: connect.summary(),
profileId: 'tcp-connect',
elapsed: Duration.zero,
);
expect(_value(empty, '失败率'), '—');
expect(_value(empty, '探测无应答'), isNull);
final oldNode = ProbeSummary.fromJson({
'sent': 1,
'completed': 1,
'ok': 1,
'rttMs': 8,
'probeLossPct': 0,
});
final remote = metricLines(
summary: oldNode,
profileId: 'nq-udp',
elapsed: const Duration(seconds: 3),
);
expect(_value(remote, '当前延迟'), '8.00 ms');
expect(_value(remote, 'P95 延迟'), '节点未提供');
expect(_value(remote, '探测无应答'), '0%');
});
}
String? _value(List<MetricLine> lines, String label) {
for (final line in lines) {
if (line.label == label) {
return line.value;
}
}
return null;
}
+101
View File
@@ -0,0 +1,101 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/models/node_edit.dart';
import 'package:netquality/models/port_field.dart';
import 'package:netquality/models/probe_profile.dart';
import 'package:netquality/models/session_config.dart';
import 'package:netquality/storage/token_vault.dart';
void main() {
test(
'editing keeps the node id and replaces only a non-blank token',
() async {
const original = RemoteNode(
id: 'node-7',
name: '机房',
baseUrl: 'https://probe.example:8443',
visibility: 'private',
);
final renamed = applyNodeEdit(
original,
name: '机房乙',
baseUrl: 'https://probe.example:8443',
);
expect(renamed.id, 'node-7');
expect(renamed.name, '机房乙');
expect(renamed.visibility, 'private');
final moved = applyNodeEdit(
renamed,
name: '机房乙',
baseUrl: 'https://other.example:8443',
);
expect(moved.id, 'node-7');
expect(moved.visibility, '');
final vault = MemoryTokenVault();
await vault.write(nodeTokenKey('node-7'), 'saved-secret');
expect(await saveEditedNodeToken(vault, 'node-7', ' '), isFalse);
expect(await vault.read(nodeTokenKey('node-7')), 'saved-secret');
expect(replacementNodeToken(' '), isNull);
expect(
await saveEditedNodeToken(vault, 'node-7', ' next-secret '),
isTrue,
);
expect(await vault.read(nodeTokenKey('node-7')), 'next-secret');
final encoded = moved.toJson();
expect(encoded.containsKey('token'), isFalse);
expect(encoded.values, isNot(contains('saved-secret')));
expect(encoded.values, isNot(contains('next-secret')));
},
);
test(
'port follows the profile default unless the user typed another port',
() {
expect(ProbeProfile.nqTcp.port, 19090);
expect(ProbeProfile.nqUdp.port, 19091);
expect(portHint(ProbeProfile.nqTcp), '合作反射 TCP 默认 19090');
expect(portHint(ProbeProfile.nqUdp), '合作反射 UDP 默认 19091');
expect(
portAfterProfileChange(
current: '19090',
previousDefault: 19090,
nextDefault: 19091,
),
'19091',
);
expect(
portAfterProfileChange(
current: ' 19090 ',
previousDefault: 19090,
nextDefault: 19132,
),
'19132',
);
expect(
portAfterProfileChange(
current: '',
previousDefault: 19090,
nextDefault: 19091,
),
'19091',
);
expect(
portAfterProfileChange(
current: '25565',
previousDefault: 19090,
nextDefault: 19091,
),
'25565',
);
expect(
portAfterProfileChange(
current: '25565',
previousDefault: 19091,
nextDefault: 80,
),
'25565',
);
},
);
}
+253 -226
View File
@@ -25,238 +25,261 @@ void main() {
expect(build.exitCode, 0, reason: '${build.stdout}\n${build.stderr}'); expect(build.exitCode, 0, reason: '${build.stdout}\n${build.stderr}');
}); });
test('local nq tcp and udp get real rtt and do not call connect failure loss', () async { test(
final reflector = await _reflector(); 'local nq tcp and udp get real rtt and do not call connect failure loss',
addTearDown(() => reflector.process.kill()); () async {
final tcp = await _collect( final reflector = await _reflector();
ProbeRequest( addTearDown(() => reflector.process.kill());
host: '127.0.0.1', final tcp = await _collect(
port: reflector.tcp, ProbeRequest(
profileId: 'nq-tcp', host: '127.0.0.1',
interval: const Duration(milliseconds: 200), port: reflector.tcp,
timeout: const Duration(milliseconds: 800), profileId: 'nq-tcp',
packetSize: 80, interval: const Duration(milliseconds: 200),
echoToken: '', timeout: const Duration(milliseconds: 800),
dnsName: '', packetSize: 80,
payloadHex: '', echoToken: '',
expectHex: '', dnsName: '',
), payloadHex: '',
count: 2, expectHex: '',
); ),
expect(tcp.last.status, Outcome.ok); count: 2,
expect(tcp.last.rttMs, greaterThan(0)); );
expect(tcp.last.summary.probeLossPct, 0); expect(tcp.last.status, Outcome.ok);
expect(tcp.last.rttMs, greaterThan(0));
expect(tcp.last.summary.probeLossPct, 0);
final udp = await _collect( final udp = await _collect(
ProbeRequest( ProbeRequest(
host: '127.0.0.1', host: '127.0.0.1',
port: reflector.udp, port: reflector.udp,
profileId: 'nq-udp', profileId: 'nq-udp',
interval: const Duration(milliseconds: 200), interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 800), timeout: const Duration(milliseconds: 800),
packetSize: 80, packetSize: 80,
echoToken: '', echoToken: '',
dnsName: '', dnsName: '',
payloadHex: '', payloadHex: '',
expectHex: '', expectHex: '',
), ),
count: 1, count: 1,
); );
expect(udp.single.status, Outcome.ok); expect(udp.single.status, Outcome.ok);
expect(udp.single.summary.probeLossPct, 0); expect(udp.single.summary.probeLossPct, 0);
final refused = await _collect( final refused = await _collect(
ProbeRequest( ProbeRequest(
host: '127.0.0.1', host: '127.0.0.1',
port: 1, port: 1,
profileId: 'tcp-connect', profileId: 'tcp-connect',
interval: const Duration(milliseconds: 200), interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 400), timeout: const Duration(milliseconds: 400),
packetSize: 64, packetSize: 64,
echoToken: '', echoToken: '',
dnsName: '', dnsName: '',
payloadHex: '', payloadHex: '',
expectHex: '', expectHex: '',
), ),
count: 1, count: 1,
); );
expect(refused.single.status, Outcome.refused); expect(refused.single.status, Outcome.refused);
expect(refused.single.summary.failurePct, 100); expect(refused.single.summary.failurePct, 100);
expect(refused.single.summary.probeLossPct, isNull); expect(refused.single.summary.probeLossPct, isNull);
}); },
);
test('silence is unknown, games answer, and a remote node measures rtt', () async { test(
final hole = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0); 'silence is unknown, games answer, and a remote node measures rtt',
addTearDown(hole.close); () async {
hole.listen((event) { final hole = await RawDatagramSocket.bind(
if (event == RawSocketEvent.read) { InternetAddress.loopbackIPv4,
hole.receive(); 0,
} );
}); addTearDown(hole.close);
final unknown = await _collect( hole.listen((event) {
ProbeRequest( if (event == RawSocketEvent.read) {
host: '127.0.0.1', hole.receive();
port: hole.port,
profileId: 'udp-generic',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 200),
packetSize: 16,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(unknown.single.status, Outcome.unknown);
expect(unknown.single.summary.probeLossPct, isNull);
expect(unknown.single.summary.unknownPct, 100);
expect(unknown.single.detail['address'], '127.0.0.1');
final java = await _javaServer();
addTearDown(java.close);
final javaSample = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: java.port,
profileId: 'minecraft-java',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 800),
packetSize: 64,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(javaSample.single.status, Outcome.ok);
expect(javaSample.single.detail['motd'], 'Hello');
expect(javaSample.single.rttMs, greaterThan(0));
expect(javaSample.single.summary.failurePct, 0);
final bedrock = await _bedrockServer();
addTearDown(bedrock.close);
final bedrockSample = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: bedrock.port,
profileId: 'minecraft-bedrock',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 800),
packetSize: 64,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(bedrockSample.single.status, Outcome.ok);
expect(bedrockSample.single.detail['motd'], 'Bed');
final node = await _node();
addTearDown(node.kill);
final samples = <ProbeSample>[];
final remote = RemoteProbe();
final done = Completer<void>();
unawaited(() async {
try {
await remote.run(
baseUrl: 'http://127.0.0.1:${node.control}',
nodeToken: '',
body: ProbeBody(
target: '127.0.0.1',
port: node.udp,
profile: 'nq-udp',
intervalMs: 200,
timeoutMs: 800,
durationSec: 3,
packetSize: 80,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
onSample: (sample) {
samples.add(sample);
if (samples.length == 1 && !done.isCompleted) {
done.complete();
}
},
cancelled: () => done.isCompleted,
);
} finally {
if (!done.isCompleted) {
done.complete();
} }
} });
}()); final unknown = await _collect(
await done.future.timeout(const Duration(seconds: 5)); ProbeRequest(
await remote.stop(''); host: '127.0.0.1',
expect(samples, isNotEmpty); port: hole.port,
expect(samples.first.status, Outcome.ok); profileId: 'udp-generic',
expect(samples.first.rttMs, greaterThan(0)); interval: const Duration(milliseconds: 200),
expect(samples.first.summary.probeLossPct, 0); timeout: const Duration(milliseconds: 200),
}); packetSize: 16,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(unknown.single.status, Outcome.unknown);
expect(unknown.single.summary.probeLossPct, isNull);
expect(unknown.single.summary.unknownPct, 100);
expect(unknown.single.detail['address'], '127.0.0.1');
test('plain udp leaves a silent address and keeps one that answers', () async { final java = await _javaServer();
final drop = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0); addTearDown(java.close);
addTearDown(drop.close); final javaSample = await _collect(
final port = drop.port; ProbeRequest(
drop.listen((event) { host: '127.0.0.1',
if (event == RawSocketEvent.read) { port: java.port,
drop.receive(); profileId: 'minecraft-java',
} interval: const Duration(milliseconds: 200),
}); timeout: const Duration(milliseconds: 800),
final RawDatagramSocket echo; packetSize: 64,
try { echoToken: '',
echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv6, port); dnsName: '',
} on SocketException { payloadHex: '',
markTestSkipped('IPv6 loopback is not available'); expectHex: '',
return; ),
} count: 1,
addTearDown(echo.close); );
echo.listen((event) { expect(javaSample.single.status, Outcome.ok);
if (event != RawSocketEvent.read) { expect(javaSample.single.detail['motd'], 'Hello');
expect(javaSample.single.rttMs, greaterThan(0));
expect(javaSample.single.summary.failurePct, 0);
final bedrock = await _bedrockServer();
addTearDown(bedrock.close);
final bedrockSample = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: bedrock.port,
profileId: 'minecraft-bedrock',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 800),
packetSize: 64,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(bedrockSample.single.status, Outcome.ok);
expect(bedrockSample.single.detail['motd'], 'Bed');
final node = await _node();
addTearDown(node.kill);
final samples = <ProbeSample>[];
final remote = RemoteProbe();
final done = Completer<void>();
unawaited(() async {
try {
await remote.run(
baseUrl: 'http://127.0.0.1:${node.control}',
nodeToken: '',
body: ProbeBody(
target: '127.0.0.1',
port: node.udp,
profile: 'nq-udp',
intervalMs: 200,
timeoutMs: 800,
durationSec: 3,
packetSize: 80,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
onSample: (sample) {
samples.add(sample);
if (samples.length == 1 && !done.isCompleted) {
done.complete();
}
},
cancelled: () => done.isCompleted,
);
} finally {
if (!done.isCompleted) {
done.complete();
}
}
}());
await done.future.timeout(const Duration(seconds: 5));
await remote.stop('');
expect(samples, isNotEmpty);
expect(samples.first.status, Outcome.ok);
expect(samples.first.rttMs, greaterThan(0));
expect(samples.first.summary.probeLossPct, 0);
},
);
test(
'a silent candidate is not a measured miss once another address answers',
() async {
final drop = await RawDatagramSocket.bind(
InternetAddress.loopbackIPv4,
0,
);
addTearDown(drop.close);
final port = drop.port;
drop.listen((event) {
if (event == RawSocketEvent.read) {
drop.receive();
}
});
final RawDatagramSocket echo;
try {
echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv6, port);
} on SocketException {
markTestSkipped('IPv6 loopback is not available');
return; return;
} }
final datagram = echo.receive(); addTearDown(echo.close);
if (datagram == null) { echo.listen((event) {
return; if (event != RawSocketEvent.read) {
} return;
echo.send(datagram.data, datagram.address, datagram.port); }
}); final datagram = echo.receive();
if (datagram == null) {
return;
}
echo.send(datagram.data, datagram.address, datagram.port);
});
final seen = <String>[]; final seen = <String>[];
final samples = await _collect( final samples = await _collect(
ProbeRequest( ProbeRequest(
host: 'example.test', host: 'example.test',
port: port, port: port,
profileId: 'udp-generic', profileId: 'udp-generic',
interval: const Duration(milliseconds: 40), interval: const Duration(milliseconds: 40),
timeout: const Duration(milliseconds: 250), timeout: const Duration(milliseconds: 250),
packetSize: 16, packetSize: 16,
echoToken: '', echoToken: '',
dnsName: '', dnsName: '',
payloadHex: '', payloadHex: '',
expectHex: '', expectHex: '',
), ),
count: 2, count: 2,
loop: ProbeLoop( loop: ProbeLoop(
lookup: (host) async { lookup: (host) async {
expect(host, 'example.test'); expect(host, 'example.test');
return [InternetAddress('127.0.0.1'), InternetAddress('::1')]; return [InternetAddress('127.0.0.1'), InternetAddress('::1')];
}, },
onEndpoint: (address) => seen.add(address.address), onEndpoint: (address) => seen.add(address.address),
), ),
); );
expect(samples.first.status, Outcome.unknown); expect(samples.first.status, Outcome.ok);
expect(samples.first.detail['address'], '127.0.0.1'); expect(samples.first.detail['address'], '::1');
expect(samples.last.status, Outcome.ok); expect(samples.first.detail['family'], 'IPv6');
expect(samples.last.detail['address'], '::1'); expect(samples.first.detail['fallback'], contains('127.0.0.1'));
expect(seen, ['127.0.0.1', '::1']); expect(samples.first.detail['fallback'], contains('没有计入'));
}); expect(samples.first.summary.sent, 1);
expect(samples.first.summary.unknown, 0);
expect(samples.first.summary.selectionSkipped, 1);
expect(samples.first.summary.unknownPct, 0);
expect(samples.last.status, Outcome.ok);
expect(samples.last.detail['address'], '::1');
expect(samples.last.summary.unknown, 0);
expect(seen, ['127.0.0.1', '::1']);
},
);
test('a responding address is not replaced while it still answers', () async { test('a responding address is not replaced while it still answers', () async {
final echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0); final echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
@@ -293,7 +316,10 @@ void main() {
), ),
); );
expect(samples.map((sample) => sample.status), everyElement(Outcome.ok)); expect(samples.map((sample) => sample.status), everyElement(Outcome.ok));
expect(samples.map((sample) => sample.detail['address']), everyElement('127.0.0.1')); expect(
samples.map((sample) => sample.detail['address']),
everyElement('127.0.0.1'),
);
}); });
} }
@@ -337,7 +363,8 @@ Future<({Process process, int tcp, int udp})> _reflector() async {
return (process: process, tcp: tcp, udp: udp); return (process: process, tcp: tcp, udp: udp);
} }
Future<({Process process, int control, int udp, void Function() kill})> _node() async { Future<({Process process, int control, int udp, void Function() kill})>
_node() async {
final udp = await _freeUdp(); final udp = await _freeUdp();
final control = await _freeTcp(); final control = await _freeTcp();
final process = await Process.start(binary, [ final process = await Process.start(binary, [
+135
View File
@@ -0,0 +1,135 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/metrics/sample_book.dart';
import 'package:netquality/metrics/selection_ledger.dart';
void main() {
const v6 = Outcome(
status: Outcome.timeout,
kind: Outcome.probe,
note: '未收到回显',
detail: {'address': '2001:db8::1', 'family': 'IPv6'},
);
const v4ok = Outcome(
status: Outcome.ok,
kind: Outcome.probe,
rttMs: 5,
note: '收到回显',
detail: {'address': '203.0.113.5', 'family': 'IPv4'},
);
const v4timeout = Outcome(
status: Outcome.timeout,
kind: Outcome.probe,
note: '未收到回显',
detail: {'address': '203.0.113.5', 'family': 'IPv4'},
);
test('ipv6 miss then ipv4 success is not formal loss', () {
final ledger = SelectionLedger(2);
expect(ledger.take(v6, responded: false).commit, isEmpty);
final decision = ledger.take(v4ok, responded: true);
expect(decision.skipped, 1);
expect(decision.commit.single.selectionSkipped, 1);
expect(decision.commit.single.detail['fallback'], contains('2001:db8::1'));
expect(decision.commit.single.detail['fallback'], contains('203.0.113.5'));
expect(decision.commit.single.detail['fallback'], contains('没有计入'));
final book = SampleBook('nq-udp');
book.add(decision.commit.single);
final summary = book.summary();
expect(summary.sent, 1);
expect(summary.ok, 1);
expect(summary.timeout, 0);
expect(summary.probeLossPct, 0);
expect(summary.selectionSkipped, 1);
});
test('every candidate failing is loss, not a false zero', () {
final ledger = SelectionLedger(2);
expect(ledger.take(v6, responded: false).commit, isEmpty);
final decision = ledger.take(v4timeout, responded: false);
expect(decision.commit, hasLength(2));
final book = SampleBook('nq-udp');
for (final outcome in decision.commit) {
book.add(outcome);
}
final summary = book.summary();
expect(summary.ok, 0);
expect(summary.sent, 2);
expect(summary.timeout, 2);
expect(summary.probeLossPct, 100);
expect(summary.selectionSkipped, 0);
});
test('timeouts after an address is selected still count', () {
final ledger = SelectionLedger(2);
final first = ledger.take(v4ok, responded: true);
expect(ledger.measuring, isTrue);
final again = ledger.take(v4timeout, responded: false);
expect(again.commit, hasLength(1));
final book = SampleBook('nq-udp');
book.add(first.commit.single);
book.add(again.commit.single);
expect(book.summary().probeLossPct, 50);
expect(book.summary().sent, 2);
});
test('one address never hides a failure', () {
final ledger = SelectionLedger(1);
final decision = ledger.take(v4timeout, responded: false);
expect(decision.commit, hasLength(1));
final book = SampleBook('nq-tcp');
book.add(decision.commit.single);
expect(book.summary().probeLossPct, 100);
});
test('a stopped in-flight attempt is not recorded', () {
expect(
countsAfterStop(
const Outcome(
status: Outcome.timeout,
kind: Outcome.probe,
note: '已停止',
),
cancelled: false,
),
isFalse,
);
expect(
countsAfterStop(
const Outcome(status: Outcome.timeout, kind: Outcome.probe),
cancelled: true,
),
isFalse,
);
expect(
countsAfterStop(
const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 1),
cancelled: false,
),
isTrue,
);
expect(countsAfterStop(null, cancelled: false), isFalse);
});
test(
'leaving a measured address does not drop the failure that caused it',
() {
final ledger = SelectionLedger(2);
ledger.take(v4ok, responded: true);
final miss = ledger.take(v4timeout, responded: false);
expect(miss.commit, hasLength(1));
ledger.endMeasurement();
expect(ledger.measuring, isFalse);
final held = ledger.take(v6, responded: false);
expect(held.commit, isEmpty);
final recovered = ledger.take(v4ok, responded: true);
expect(recovered.skipped, 1);
final book = SampleBook('nq-udp');
book.add(v4ok);
book.add(miss.commit.single);
book.add(recovered.commit.single);
expect(book.summary().sent, 3);
expect(book.summary().timeout, 1);
expect(book.summary().probeLossPct, closeTo(100 / 3, 0.0001));
},
);
}
+116 -1
View File
@@ -1,3 +1,5 @@
import 'dart:convert';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/main.dart'; import 'package:netquality/main.dart';
@@ -27,7 +29,9 @@ void main() {
const config = SessionConfig( const config = SessionConfig(
remote: true, remote: true,
nodeId: 'n1', nodeId: 'n1',
nodes: [RemoteNode(id: 'n1', name: '机房', baseUrl: 'https://probe.example:8443')], nodes: [
RemoteNode(id: 'n1', name: '机房', baseUrl: 'https://probe.example:8443'),
],
host: '203.0.113.8', host: '203.0.113.8',
port: 25565, port: 25565,
profileId: 'minecraft-java', profileId: 'minecraft-java',
@@ -47,4 +51,115 @@ void main() {
expect(again.toJson().containsKey('nodeToken'), isFalse); expect(again.toJson().containsKey('nodeToken'), isFalse);
expect(SessionConfig.defaults.validate(), isNull); expect(SessionConfig.defaults.validate(), isNull);
}); });
testWidgets(
'profile default port updates until the user types another port',
(tester) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(1280, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const NetQualityApp());
await tester.pumpAndSettle();
expect(find.text('合作反射 TCP 默认 19090'), findsOneWidget);
await tester.ensureVisible(find.byKey(const Key('profile')));
await tester.tap(find.byKey(const Key('profile')));
await tester.pumpAndSettle();
await tester.tap(find.text('合作反射 UDP').last);
await tester.pumpAndSettle();
expect(find.text('19091'), findsWidgets);
expect(find.text('合作反射 UDP 默认 19091'), findsOneWidget);
await tester.enterText(find.byKey(const Key('port-field')), '25565');
await tester.tap(find.byKey(const Key('profile')));
await tester.pumpAndSettle();
await tester.tap(find.text('合作反射 TCP').last);
await tester.pumpAndSettle();
expect(find.text('25565'), findsOneWidget);
},
);
testWidgets('editing a node keeps its id and does not reveal the token', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(1280, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const NetQualityApp());
await tester.pumpAndSettle();
await tester.tap(find.text('远程节点').first);
await tester.pumpAndSettle();
await tester.tap(find.text('管理节点'));
await tester.pumpAndSettle();
await tester.enterText(find.byKey(const Key('node-name')), '机房');
await tester.enterText(
find.byKey(const Key('node-url')),
'http://127.0.0.1:8443',
);
await tester.enterText(find.byKey(const Key('node-token')), 'saved-secret');
await tester.tap(find.byKey(const Key('node-save')));
await tester.pumpAndSettle();
await tester.tap(find.text('编辑'));
await tester.pumpAndSettle();
final token = tester.widget<TextField>(find.byKey(const Key('node-token')));
expect(token.controller?.text, isEmpty);
expect(find.text('saved-secret'), findsNothing);
await tester.enterText(find.byKey(const Key('node-name')), '机房乙');
await tester.tap(find.text('保存修改'));
await tester.pumpAndSettle();
expect(find.textContaining('机房乙'), findsWidgets);
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString('netquality.settings.v2') ?? '';
expect(raw, contains('机房乙'));
expect(raw, isNot(contains('saved-secret')));
final decoded = jsonDecode(raw) as Map<String, dynamic>;
final nodes = decoded['nodes'] as List<dynamic>;
expect(nodes, hasLength(1));
final node = nodes.single as Map<String, dynamic>;
expect(node['name'], '机房乙');
expect(node['baseUrl'], 'http://127.0.0.1:8443');
expect(decoded['nodeId'], node['id']);
});
testWidgets('guide and history screens use the real versions', (
tester,
) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(900, 1400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const NetQualityApp());
await tester.pumpAndSettle();
await tester.tap(find.byType(PopupMenuButton<String>));
await tester.pumpAndSettle();
await tester.tap(find.text('指标说明'));
await tester.pumpAndSettle();
expect(find.textContaining('没有协议应答'), findsWidgets);
await tester.scrollUntilVisible(find.text('选址失败和正式丢包'), 200);
expect(find.text('选址失败和正式丢包'), findsOneWidget);
await tester.scrollUntilVisible(find.textContaining('RFC 3550'), 200);
expect(find.textContaining('RFC 3550'), findsOneWidget);
await tester.pageBack();
await tester.pumpAndSettle();
await tester.tap(find.byType(PopupMenuButton<String>));
await tester.pumpAndSettle();
await tester.tap(find.text('更新历史'));
await tester.pumpAndSettle();
expect(find.text('网络质量探测 1.1.2'), findsOneWidget);
await tester.scrollUntilVisible(find.text('网络质量探测 1.1.1'), 200);
expect(find.text('网络质量探测 1.1.1'), findsOneWidget);
expect(find.textContaining('言灸'), findsOneWidget);
expect(find.textContaining('v1.1.1'), findsWidgets);
expect(find.text('网络质量探测 1.1.0'), findsNothing);
});
} }
+3 -1
View File
@@ -44,7 +44,9 @@
- **普通 TCP**:只记录连接耗时、成功或失败、连续失败。没有自定义帧。 - **普通 TCP**:只记录连接耗时、成功或失败、连续失败。没有自定义帧。
- **普通 UDP、DNS、自定义 UDP、基岩版**:没有收到符合协议的包时记为无应答/未知,不叫丢包。内容不对记为协议错误。 - **普通 UDP、DNS、自定义 UDP、基岩版**:没有收到符合协议的包时记为无应答/未知,不叫丢包。内容不对记为协议错误。
- **Minecraft Java**:状态握手加上 ping/pong。往返时间只算 ping 到对上 nonce 的 pong。连不上或协议不对记为失败率。 - **Minecraft Java**:状态握手加上 ping/pong。往返时间只算 ping 到对上 nonce 的 pong。连不上或协议不对记为失败率。
- **抖动**:RFC 3550。相邻两次成功的往返时间差 `D`,`J = J + (|D| - J) / 16`。 - **抖动**:RFC 3550。相邻两次成功的往返时间差 `D`,`J = J + (|D| - J) / 16`。第一次成功时 J 为 0。
- **延迟分布**:只统计成功样本。当前延迟是最近一次成功。最小、最大是极值。平均是算术平均。中位数在奇数个时取排序后的中间值,偶数个时取中间两个的平均。P95 用最近秩,秩 = ceil(0.95 × 次数),用整数 `(95 × 次数 + 99) / 100` 计算,从 1 起计。
- **选址**:一个名字解析出多个地址时,还没有任何地址应答之前的失败只用于挑选地址。后面有地址成功时,这些失败不进入已发送、超时和丢包,并在 `detail.fallback` 里说明。选定之后的失败照常计入。每个候选都失败时,这些失败计入正式结果,不能显示成 0% 成功。每条样本的 `detail.address` 和 `detail.family` 是这次实际连通或发包的地址;没有这个字段就表示节点没有报告,不能用解析结果代替。`summary` 另有 `minRttMs`、`meanRttMs`、`medianRttMs`、`p95RttMs`、`maxRttMs` 和 `selectionSkipped`。旧客户端会忽略不认识的字段。
## 控制接口 ## 控制接口
+39
View File
@@ -0,0 +1,39 @@
# 网络质量探测 1.1.2
构建号 5。署名:言灸。许可:GNU Affero General Public License v3.0(AGPL-3.0-only)。
这一版还没有打 Git 标签,也还没有发布安装包。下面是准备发布的说明。
## 节点和端口
- 已有远程节点可以改名称、控制地址和口令。节点编号和当前选择保持不变。
- 修改时口令留空表示继续使用已经保存在本机的口令。界面不会把原口令填出来。填写新口令才会替换。
- 端口框标明当前探测类型的默认端口。合作反射 TCP 默认 19090,合作反射 UDP 默认 19091。
- 只有端口仍是上一种类型的默认值,或者端口是空的,切换类型才会自动更换。自己填过的端口会留下。
## 实际地址
- 本机和 1.1.2 节点都会显示这次真正连通或真正发包的 IP,并注明 IPv4 或 IPv6。
- 域名解析出的地址单独标成「解析到」,不会被说成已经使用的地址。
- 1.1.2 之前的远程节点不会在结果里带地址。界面会写「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。
## 选址和丢包
- 还没有任何地址应答时,用来挑选地址的失败(例如 IPv6 没有应答,随后 IPv4 成功)不计入已发送、超时和正式丢包,并单独说明回退。
- 某个地址已经应答之后,对它的超时和失败仍然计入,不会因为后来又换地址而被抹掉。
- 只有一个地址时,失败从一开始就算正式结果。
- 每一个候选都失败时,这些失败计入正式结果。不会显示 0% 成功。
- 1.1.1 的节点仍可能把第一次选址失败算进统计。要分开看,节点也需要这一版。
## 指标和停止
- 结果给出已发送、已收到、超时、比率、当前/最小/平均/中位/P95/最大延迟、抖动和用时。
- 探测无应答 = 超时 ÷(超时 + 成功)。分母只含已经写出的回显尝试。分母为 0 时显示 —,不是 0%。
- 普通 TCP 和 Minecraft Java 显示失败率,不显示丢包百分比。
- 普通 UDP、DNS、自定义 UDP 和基岩版把沉默记为无应答。UDP 没有应答不能当成已经证实的丢包。
- 延迟分布只统计成功样本。P95 用最近秩,秩 = ceil(0.95 × 次数)。抖动沿用 RFC 3550。
- 手动停止后保留曲线,并给出开始、结束、用时、目标、来源、实际地址和同一套最终指标。
- 停止时还没完成的请求不计入丢包。
- 点曲线可以钉住该时刻的延迟和比率,松手后仍然保留。再点另一点会更换。新的一次探测,或该点滚出窗口后,选择不会跳到别的点上。
应用里增加了「指标说明」和「更新历史」。更新历史只列出仓库里真实存在的标签 v1.1.1,以及这一版。
+1 -1
View File
@@ -63,7 +63,7 @@ ss -lunp | grep 19091
```bash ```bash
sudo mkdir -p /opt/netquality sudo mkdir -p /opt/netquality
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.1-linux-amd64.tar.gz sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.2-linux-amd64.tar.gz
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
sudo systemctl daemon-reload sudo systemctl daemon-reload
sudo systemctl enable --now netquality sudo systemctl enable --now netquality
+1 -1
View File
@@ -110,7 +110,7 @@ sudo firewall-cmd --reload
```bash ```bash
sudo mkdir -p /opt/netquality sudo mkdir -p /opt/netquality
sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.1-linux-amd64.tar.gz sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.2-linux-amd64.tar.gz
sudo chmod 755 /opt/netquality/netquality-reflector sudo chmod 755 /opt/netquality/netquality-reflector
sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service
sudo systemctl daemon-reload sudo systemctl daemon-reload
+1
View File
@@ -26,6 +26,7 @@ func main() {
} }
log.Fatal(err) log.Fatal(err)
} }
log.Printf("netquality %s", appVersion)
log.Printf("%s", cfg.Summary()) log.Printf("%s", cfg.Summary())
tok, err := tokenBytes(cfg.Token) tok, err := tokenBytes(cfg.Token)
+30 -11
View File
@@ -19,13 +19,14 @@ const (
// Outcome is one finished attempt. Pending attempts are never turned into // Outcome is one finished attempt. Pending attempts are never turned into
// a sample, so a chart cannot show a fake 100% before the probe completes. // a sample, so a chart cannot show a fake 100% before the probe completes.
type Outcome struct { type Outcome struct {
Status string Status string
Kind string Kind string
Rtt time.Duration Rtt time.Duration
HasRtt bool HasRtt bool
Note string Note string
Detail map[string]string Detail map[string]string
Reconnect bool Reconnect bool
SelectionSkipped int
} }
type jitter struct { type jitter struct {
@@ -64,15 +65,18 @@ type sampleBook struct {
reconnect int reconnect int
consecutive int consecutive int
lastRttMs *float64 lastRttMs *float64
jitter jitter jitter jitter
lastNote string rtts []float64
detail map[string]string selectionSkipped int
lastNote string
detail map[string]string
} }
func (b *sampleBook) add(o Outcome) { func (b *sampleBook) add(o Outcome) {
b.sent++ b.sent++
b.completed++ b.completed++
b.selectionSkipped += o.SelectionSkipped
if o.Reconnect { if o.Reconnect {
b.reconnect++ b.reconnect++
} }
@@ -94,6 +98,7 @@ func (b *sampleBook) add(o Outcome) {
if o.HasRtt { if o.HasRtt {
ms := float64(o.Rtt) / float64(time.Millisecond) ms := float64(o.Rtt) / float64(time.Millisecond)
b.lastRttMs = &ms b.lastRttMs = &ms
b.rtts = append(b.rtts, ms)
b.jitter.push(ms) b.jitter.push(ms)
} }
case statusTimeout: case statusTimeout:
@@ -138,6 +143,14 @@ func (b *sampleBook) summary() summaryMsg {
ConsecutiveFailures: b.consecutive, ConsecutiveFailures: b.consecutive,
LastNote: b.lastNote, LastNote: b.lastNote,
Detail: b.detail, Detail: b.detail,
SelectionSkipped: b.selectionSkipped,
}
if min, mean, median, p95, max, ok := latencyOf(b.rtts); ok {
s.MinRttMs = &min
s.MeanRttMs = &mean
s.MedianRttMs = &median
s.P95RttMs = &p95
s.MaxRttMs = &max
} }
if b.lastRttMs != nil { if b.lastRttMs != nil {
v := *b.lastRttMs v := *b.lastRttMs
@@ -197,6 +210,12 @@ type summaryMsg struct {
ProbeLossPct *float64 `json:"probeLossPct,omitempty"` ProbeLossPct *float64 `json:"probeLossPct,omitempty"`
FailurePct *float64 `json:"failurePct,omitempty"` FailurePct *float64 `json:"failurePct,omitempty"`
UnknownPct *float64 `json:"unknownPct,omitempty"` UnknownPct *float64 `json:"unknownPct,omitempty"`
MinRttMs *float64 `json:"minRttMs,omitempty"`
MeanRttMs *float64 `json:"meanRttMs,omitempty"`
MedianRttMs *float64 `json:"medianRttMs,omitempty"`
P95RttMs *float64 `json:"p95RttMs,omitempty"`
MaxRttMs *float64 `json:"maxRttMs,omitempty"`
SelectionSkipped int `json:"selectionSkipped,omitempty"`
LastNote string `json:"lastNote,omitempty"` LastNote string `json:"lastNote,omitempty"`
Detail map[string]string `json:"detail,omitempty"` Detail map[string]string `json:"detail,omitempty"`
} }
+48 -4
View File
@@ -21,6 +21,7 @@ type jobSpec struct {
Port int Port int
Profile string Profile string
IP net.IP IP net.IP
state *dialState
Interval time.Duration Interval time.Duration
Timeout time.Duration Timeout time.Duration
Duration time.Duration Duration time.Duration
@@ -110,6 +111,7 @@ func (n *Node) info(w http.ResponseWriter, _ *http.Request) {
vis = "public" vis = "public"
} }
writeJSON(w, http.StatusOK, map[string]any{ writeJSON(w, http.StatusOK, map[string]any{
"version": appVersion,
"visibility": vis, "visibility": vis,
"authRequired": !n.Public(), "authRequired": !n.Public(),
"profiles": []string{ "profiles": []string{
@@ -185,10 +187,19 @@ func (n *Node) create(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "error", "任务没有启动") writeErr(w, http.StatusInternalServerError, "error", "任务没有启动")
return return
} }
resolved := make([]map[string]string, 0, len(spec.candidates()))
for _, ip := range spec.candidates() {
resolved = append(resolved, map[string]string{
"address": ip.String(),
"family": familyOf(ip),
})
}
writeJSON(w, http.StatusCreated, map[string]any{ writeJSON(w, http.StatusCreated, map[string]any{
"jobId": job.id, "jobId": job.id,
"expiresAt": job.expires.UTC().Format(time.RFC3339), "expiresAt": job.expires.UTC().Format(time.RFC3339),
"visibility": map[bool]string{true: "public", false: "private"}[n.Public()], "visibility": map[bool]string{true: "public", false: "private"}[n.Public()],
"version": appVersion,
"resolved": resolved,
}) })
} }
@@ -246,7 +257,7 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
} }
} }
} }
ip, err := targetOK(ctx, n.Resolver, req.Target, n.AllowPrivate, n.ExtraNets) ips, err := resolveTargets(ctx, n.Resolver, req.Target, n.AllowPrivate, n.ExtraNets)
if err != nil { if err != nil {
var dnsErr *net.DNSError var dnsErr *net.DNSError
if errors.As(err, &dnsErr) { if errors.As(err, &dnsErr) {
@@ -258,7 +269,8 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) {
return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", "目标地址无效"} return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", "目标地址无效"}
} }
return jobSpec{ return jobSpec{
Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ip, Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ips[0],
state: &dialState{picker: newEndpointPicker(ips)},
Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size, Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size,
Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect, Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect,
}, nil }, nil
@@ -334,18 +346,50 @@ func (n *Node) run(ctx context.Context, job *probeJob, spec jobSpec, p prober) {
case <-ctx.Done(): case <-ctx.Done():
} }
} }
ledger := &selectionLedger{candidates: len(spec.candidates())}
datagram := datagramProfile(spec.Profile)
for { for {
if err := n.pace.wait(ctx, spec.PacketSize); err != nil { if err := n.pace.wait(ctx, spec.PacketSize); err != nil {
return return
} }
started := time.Now() started := time.Now()
pctx, cancel := context.WithTimeout(ctx, spec.Timeout) budget := spec.Timeout
if budget <= 0 {
budget = 1500 * time.Millisecond
}
if !datagram && spec.state != nil && spec.state.picker != nil && !spec.state.picker.locked && len(spec.state.picker.ips) > 1 {
budget *= time.Duration(len(spec.state.picker.ips))
}
if datagram && spec.state != nil {
if ip := spec.dialIP(); ip != nil {
spec.state.used = append(net.IP(nil), ip...)
}
}
pctx, cancel := context.WithTimeout(ctx, budget)
out := p.Probe(pctx) out := p.Probe(pctx)
cancel() cancel()
if ctx.Err() != nil { if ctx.Err() != nil {
return return
} }
emit(out) out = spec.decorate(out)
var commit []Outcome
if datagram && spec.state != nil && spec.state.picker != nil {
responded := selectionResponded(out.Status)
wasMeasuring := ledger.measuring
changed := spec.state.picker.record(responded)
commit, _ = ledger.take(out, responded)
if wasMeasuring && changed {
ledger.measuring = false
}
if len(commit) == 0 {
continue
}
} else {
commit = []Outcome{out}
}
for _, item := range commit {
emit(item)
}
wait := spec.Interval - time.Since(started) wait := spec.Interval - time.Since(started)
if wait < 0 { if wait < 0 {
wait = 0 wait = 0
+6
View File
@@ -163,6 +163,12 @@ func TestNodeNQAndTCPAndUDP(t *testing.T) {
if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 { if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 {
t.Fatalf("nq tcp %+v", sample) t.Fatalf("nq tcp %+v", sample)
} }
if sample.Detail["address"] != "127.0.0.1" || sample.Detail["family"] != "IPv4" {
t.Fatalf("tcp did not report the connected address %+v", sample.Detail)
}
if sample.Summary.MinRttMs == nil || sample.Summary.P95RttMs == nil {
t.Fatalf("latency stats missing %+v", sample.Summary)
}
if sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 { if sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 {
t.Fatalf("loss %+v", sample.Summary) t.Fatalf("loss %+v", sample.Summary)
} }
+8 -8
View File
@@ -1,8 +1,8 @@
@echo off @echo off
chcp 65001 >nul chcp 65001 >nul
cd /d "%~dp0" cd /d "%~dp0"
echo 正在启动网络质量探测节点。端口和口令请改同目录下的 .env echo 正在启动网络质量探测节点。端口和口令请改同目录下的 .env
netquality-reflector.exe netquality-reflector.exe
echo. echo.
echo 程序已退出。如果上面有报错,请检查 .env 后重新双击本文件。 echo 程序已退出。如果上面有报错,请检查 .env 后重新双击本文件。
pause pause
+23 -25
View File
@@ -127,7 +127,7 @@ func (p *nqTCP) Close() error {
} }
func (p *nqTCP) dial(ctx context.Context) error { func (p *nqTCP) dial(ctx context.Context) error {
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port) conn, err := dialSpecTCP(ctx, &p.spec)
if err != nil { if err != nil {
return err return err
} }
@@ -208,11 +208,9 @@ func (p *nqUDP) Close() error {
} }
func (p *nqUDP) ensure() error { func (p *nqUDP) ensure() error {
if p.conn != nil { c, err := ensureUDP(p.conn, p.spec)
return nil
}
c, err := dialUDP(p.spec.IP, p.spec.Port)
if err != nil { if err != nil {
p.conn = nil
return err return err
} }
p.conn = c p.conn = c
@@ -273,7 +271,7 @@ func (p *tcpConnect) Close() error { return nil }
func (p *tcpConnect) Probe(ctx context.Context) Outcome { func (p *tcpConnect) Probe(ctx context.Context) Outcome {
start := time.Now() start := time.Now()
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port) conn, err := dialSpecTCP(ctx, &p.spec)
if err != nil { if err != nil {
return classifyDial(err) return classifyDial(err)
} }
@@ -297,13 +295,12 @@ func (p *udpQuery) Close() error {
} }
func (p *udpQuery) Probe(ctx context.Context) Outcome { func (p *udpQuery) Probe(ctx context.Context) Outcome {
if p.conn == nil { c, err := ensureUDP(p.conn, p.spec)
c, err := dialUDP(p.spec.IP, p.spec.Port) if err != nil {
if err != nil { p.conn = nil
return classifyDial(err) return classifyDial(err)
}
p.conn = c
} }
p.conn = c
payload := p.spec.Payload payload := p.spec.Payload
if p.generic { if p.generic {
n := p.spec.PacketSize n := p.spec.PacketSize
@@ -358,13 +355,12 @@ func (p *dnsQuery) Close() error {
} }
func (p *dnsQuery) Probe(ctx context.Context) Outcome { func (p *dnsQuery) Probe(ctx context.Context) Outcome {
if p.conn == nil { c, err := ensureUDP(p.conn, p.spec)
c, err := dialUDP(p.spec.IP, p.spec.Port) if err != nil {
if err != nil { p.conn = nil
return classifyDial(err) return classifyDial(err)
}
p.conn = c
} }
p.conn = c
p.id++ p.id++
if p.id == 0 { if p.id == 0 {
p.id = 1 p.id = 1
@@ -449,12 +445,14 @@ func (p *mcBedrock) Close() error {
} }
func (p *mcBedrock) Probe(ctx context.Context) Outcome { func (p *mcBedrock) Probe(ctx context.Context) Outcome {
if p.conn == nil { fresh := p.conn == nil
c, err := dialUDP(p.spec.IP, p.spec.Port) c, err := ensureUDP(p.conn, p.spec)
if err != nil { if err != nil {
return classifyDial(err) p.conn = nil
} return classifyDial(err)
p.conn = c }
p.conn = c
if fresh || p.guid == 0 {
p.guid = uint64(time.Now().UnixNano()) p.guid = uint64(time.Now().UnixNano())
} }
ts := uint64(time.Now().UnixNano()) ts := uint64(time.Now().UnixNano())
@@ -529,7 +527,7 @@ type mcJava struct{ spec jobSpec }
func (p *mcJava) Close() error { return nil } func (p *mcJava) Close() error { return nil }
func (p *mcJava) Probe(ctx context.Context) Outcome { func (p *mcJava) Probe(ctx context.Context) Outcome {
conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port) conn, err := dialSpecTCP(ctx, &p.spec)
if err != nil { if err != nil {
return classifyDial(err) return classifyDial(err)
} }
+12 -3
View File
@@ -25,8 +25,17 @@ var metadataIP = net.ParseIP("169.254.169.254")
// Loopback, private, link-local and cloud metadata are rejected unless // Loopback, private, link-local and cloud metadata are rejected unless
// allowPrivate is set. Metadata addresses stay blocked either way. // allowPrivate is set. Metadata addresses stay blocked either way.
// Every resolved address is checked so a later DNS answer cannot rebind // Every resolved address is checked so a later DNS answer cannot rebind
// the dial onto a forbidden IP; the caller dials only the returned IP. // the dial onto a forbidden IP. targetOK returns the first allowed address;
// resolveTargets returns every allowed address in resolver order.
func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) (net.IP, error) { func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) (net.IP, error) {
ips, err := resolveTargets(ctx, resolver, host, allowPrivate, extra)
if err != nil {
return nil, err
}
return ips[0], nil
}
func resolveTargets(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) ([]net.IP, error) {
host = strings.TrimSpace(host) host = strings.TrimSpace(host)
host = strings.Trim(host, "[]") host = strings.Trim(host, "[]")
if host == "" { if host == "" {
@@ -39,7 +48,7 @@ func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate
if !ipAllowed(ip, allowPrivate, extra) { if !ipAllowed(ip, allowPrivate, extra) {
return nil, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String()) return nil, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String())
} }
return ip, nil return []net.IP{ip}, nil
} }
if resolver == nil { if resolver == nil {
resolver = net.DefaultResolver resolver = net.DefaultResolver
@@ -65,7 +74,7 @@ func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate
if len(allowed) != len(addrs) { if len(allowed) != len(addrs) {
return nil, fmt.Errorf("%w: %s resolved to a mix of public and blocked addresses", errForbiddenTarget, host) return nil, fmt.Errorf("%w: %s resolved to a mix of public and blocked addresses", errForbiddenTarget, host)
} }
return allowed[0], nil return allowed, nil
} }
func ipAllowed(ip net.IP, allowPrivate bool, extra []*net.IPNet) bool { func ipAllowed(ip net.IP, allowPrivate bool, extra []*net.IPNet) bool {
+368
View File
@@ -0,0 +1,368 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"context"
"errors"
"fmt"
"net"
"sort"
"strings"
"time"
)
const appVersion = "1.1.2"
// dialState is shared by the job runner and the prober. Both hold a copy of
// jobSpec, so the mutable address choice has to live behind a pointer.
type dialState struct {
picker *endpointPicker
used net.IP
fallback string
skipped int
}
type endpointPicker struct {
ips []net.IP
index int
misses int
locked bool
sticky int
}
func newEndpointPicker(ips []net.IP) *endpointPicker {
return &endpointPicker{ips: append([]net.IP(nil), ips...), sticky: 3}
}
func (p *endpointPicker) current() net.IP {
if p == nil || len(p.ips) == 0 {
return nil
}
return p.ips[p.index]
}
func (p *endpointPicker) lock(ip net.IP) {
for i, cand := range p.ips {
if cand.Equal(ip) {
p.index = i
p.locked = true
p.misses = 0
return
}
}
}
// record matches the client EndpointPicker: one miss rotates until some
// address has answered; after that, sticky misses are required.
func (p *endpointPicker) record(responded bool) bool {
if responded {
p.locked = true
p.misses = 0
return false
}
p.misses++
limit := 1
if p.locked {
limit = p.sticky
}
if len(p.ips) < 2 || p.misses < limit {
return false
}
p.misses = 0
p.locked = false
p.index = (p.index + 1) % len(p.ips)
return true
}
func (s jobSpec) candidates() []net.IP {
if s.state != nil && s.state.picker != nil && len(s.state.picker.ips) > 0 {
return s.state.picker.ips
}
if s.IP != nil {
return []net.IP{s.IP}
}
return nil
}
func (s jobSpec) dialIP() net.IP {
if s.state != nil && s.state.picker != nil {
if ip := s.state.picker.current(); ip != nil {
return ip
}
}
if s.IP != nil {
return s.IP
}
return nil
}
func familyOf(ip net.IP) string {
if ip == nil {
return ""
}
if ip.To4() != nil {
return "IPv4"
}
return "IPv6"
}
func copyDetail(in map[string]string) map[string]string {
out := make(map[string]string, len(in)+2)
for k, v := range in {
out[k] = v
}
return out
}
func stampIP(o Outcome, ip net.IP) Outcome {
if ip == nil {
return o
}
o.Detail = copyDetail(o.Detail)
o.Detail["address"] = ip.String()
o.Detail["family"] = familyOf(ip)
return o
}
// decorate attaches the address actually dialed. Candidate-connect failures
// that were skipped in favor of a working address are copied onto this one
// outcome and then cleared, so they are not repeated on later probes.
func (s jobSpec) decorate(o Outcome) Outcome {
if s.state == nil {
if s.IP != nil {
return stampIP(o, s.IP)
}
return o
}
if s.state.used != nil {
o = stampIP(o, s.state.used)
}
if s.state.fallback != "" {
o.Detail = copyDetail(o.Detail)
o.Detail["fallback"] = s.state.fallback
s.state.fallback = ""
}
if s.state.skipped > 0 {
o.SelectionSkipped += s.state.skipped
s.state.skipped = 0
}
return o
}
func selectionResponded(status string) bool {
switch status {
case statusOK, statusProtocol, statusRefused:
return true
default:
return false
}
}
func datagramProfile(profile string) bool {
switch profile {
case "nq-udp", "udp-generic", "custom-udp", "dns", "minecraft-bedrock":
return true
default:
return false
}
}
type selectionLedger struct {
candidates int
measuring bool
held []Outcome
}
func (l *selectionLedger) take(o Outcome, responded bool) (commit []Outcome, skipped int) {
if l.candidates <= 1 {
if responded {
l.measuring = true
}
return []Outcome{o}, 0
}
if l.measuring {
return []Outcome{o}, 0
}
if responded {
skipped = len(l.held)
if skipped > 0 {
o.Detail = copyDetail(o.Detail)
o.Detail["fallback"] = fallbackFromHeld(l.held, o)
o.SelectionSkipped += skipped
}
l.held = nil
l.measuring = true
return []Outcome{o}, skipped
}
l.held = append(l.held, o)
if len(l.held) >= l.candidates {
commit = append([]Outcome(nil), l.held...)
l.held = nil
return commit, 0
}
return nil, 0
}
func fallbackFromHeld(held []Outcome, success Outcome) string {
parts := make([]string, 0, len(held))
for _, o := range held {
addr := ""
fam := ""
if o.Detail != nil {
addr = o.Detail["address"]
fam = o.Detail["family"]
}
where := "未知地址"
if addr != "" {
where = addr
if fam != "" {
where = addr + "(" + fam + ")"
}
}
why := o.Note
if why == "" {
why = "没有成功"
}
parts = append(parts, where+":"+why)
}
used := ""
usedFam := ""
if success.Detail != nil {
used = success.Detail["address"]
usedFam = success.Detail["family"]
}
usedText := "另一个地址"
if used != "" {
usedText = used
if usedFam != "" {
usedText = used + "(" + usedFam + ")"
}
}
return "候选未成功:" + strings.Join(parts, ";") + "。已改用 " + usedText + "。这些失败没有计入正式丢包或失败率。"
}
type dialFunc func(context.Context, net.IP) (net.Conn, error)
// dialFirst tries each address with its own timeout. A failure is described
// and not returned as a separate measured attempt. If a later address
// connects, the skipped notes are returned for the diagnostic. If every
// address fails, err is the last error. A cancelled parent context does not
// become a measured timeout.
func dialFirst(ctx context.Context, ips []net.IP, timeout time.Duration, dial dialFunc) (net.Conn, net.IP, []string, error) {
if len(ips) == 0 {
return nil, nil, nil, errors.New("no address")
}
if timeout <= 0 {
timeout = 1500 * time.Millisecond
}
var skipped []string
var last error
for _, ip := range ips {
if err := ctx.Err(); err != nil {
return nil, nil, skipped, err
}
dialCtx, cancel := context.WithTimeout(ctx, timeout)
conn, err := dial(dialCtx, ip)
cancel()
if err == nil {
return conn, ip, skipped, nil
}
if errors.Is(err, context.Canceled) && ctx.Err() != nil {
return nil, nil, skipped, ctx.Err()
}
skipped = append(skipped, fmt.Sprintf("%s %s %s", familyOf(ip), ip.String(), classifyDial(err).Note))
last = err
}
if last == nil {
last = errors.New("连接失败")
}
return nil, nil, skipped, last
}
func dialSpecTCP(ctx context.Context, spec *jobSpec) (net.Conn, error) {
ips := spec.candidates()
start := 0
if spec.state != nil && spec.state.picker != nil {
start = spec.state.picker.index
}
rotated := make([]net.IP, 0, len(ips))
for n := 0; n < len(ips); n++ {
rotated = append(rotated, ips[(start+n)%len(ips)])
}
conn, ip, skipped, err := dialFirst(ctx, rotated, spec.Timeout, func(ctx context.Context, ip net.IP) (net.Conn, error) {
return dialTCP(ctx, ip, spec.Port)
})
if spec.state != nil {
spec.state.used = nil
spec.state.fallback = ""
spec.state.skipped = 0
}
if err != nil {
if spec.state != nil && len(skipped) > 0 && !errors.Is(err, context.Canceled) {
spec.state.fallback = "已尝试 " + strings.Join(skipped, ";") + "。没有地址连通,这次记为失败。"
}
return nil, err
}
if spec.state != nil {
if spec.state.picker != nil {
spec.state.picker.lock(ip)
}
spec.state.used = append(net.IP(nil), ip...)
if len(skipped) > 0 {
spec.state.skipped = len(skipped)
spec.state.fallback = "候选未连通:" + strings.Join(skipped, ";") + "。已改用 " + ip.String() + "(" + familyOf(ip) + ")。这些失败没有计入正式丢包或失败率。"
}
}
return conn, nil
}
func ensureUDP(conn *net.UDPConn, spec jobSpec) (*net.UDPConn, error) {
want := spec.dialIP()
if want == nil {
return nil, errors.New("no address")
}
if conn != nil {
if ra, ok := conn.RemoteAddr().(*net.UDPAddr); ok && ra.IP.Equal(want) {
return conn, nil
}
_ = conn.Close()
}
return dialUDP(want, spec.Port)
}
// nearestRank95 is ceil(0.95*n) in integer arithmetic.
func nearestRank95(n int) int {
if n <= 1 {
return 1
}
rank := (95*n + 99) / 100
if rank < 1 {
return 1
}
if rank > n {
return n
}
return rank
}
func latencyOf(samples []float64) (min, mean, median, p95, max float64, ok bool) {
if len(samples) == 0 {
return 0, 0, 0, 0, 0, false
}
sorted := append([]float64(nil), samples...)
sort.Float64s(sorted)
var sum float64
for _, v := range sorted {
sum += v
}
n := len(sorted)
if n%2 == 1 {
median = sorted[n/2]
} else {
median = (sorted[n/2-1] + sorted[n/2]) / 2
}
rank := nearestRank95(n)
return sorted[0], sum / float64(n), median, sorted[rank-1], sorted[n-1], true
}
+266
View File
@@ -0,0 +1,266 @@
package main
import (
"context"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestSelectionLedgerDoesNotCountFallback(t *testing.T) {
ledger := &selectionLedger{candidates: 2}
miss := Outcome{
Status: statusTimeout,
Kind: kindProbe,
Note: "未收到回显",
Detail: map[string]string{"address": "2001:db8::1", "family": "IPv6"},
}
commit, skipped := ledger.take(miss, false)
if commit != nil || skipped != 0 {
t.Fatalf("held failure was counted: %+v %d", commit, skipped)
}
ok := Outcome{
Status: statusOK,
Kind: kindProbe,
HasRtt: true,
Rtt: 5 * time.Millisecond,
Note: "收到回显",
Detail: map[string]string{"address": "203.0.113.5", "family": "IPv4"},
}
commit, skipped = ledger.take(ok, true)
if skipped != 1 || len(commit) != 1 || commit[0].SelectionSkipped != 1 {
t.Fatalf("success %+v skipped %d", commit, skipped)
}
if commit[0].Detail["fallback"] == "" || !containsAll(commit[0].Detail["fallback"], "2001:db8::1", "203.0.113.5", "没有计入") {
t.Fatalf("fallback %q", commit[0].Detail["fallback"])
}
book := &sampleBook{profile: "nq-udp"}
book.add(commit[0])
summary := book.summary()
if summary.Sent != 1 || summary.OK != 1 || summary.Timeout != 0 || summary.ProbeLossPct == nil || *summary.ProbeLossPct != 0 {
t.Fatalf("summary %+v", summary)
}
if summary.SelectionSkipped != 1 || summary.MinRttMs == nil || *summary.MinRttMs != 5 || summary.P95RttMs == nil || *summary.P95RttMs != 5 {
t.Fatalf("stats %+v", summary)
}
}
func TestSelectionLedgerCommitsTotalFailure(t *testing.T) {
ledger := &selectionLedger{candidates: 2}
first := Outcome{Status: statusTimeout, Kind: kindProbe, Detail: map[string]string{"address": "2001:db8::1", "family": "IPv6"}}
second := Outcome{Status: statusTimeout, Kind: kindProbe, Detail: map[string]string{"address": "203.0.113.5", "family": "IPv4"}}
if commit, _ := ledger.take(first, false); commit != nil {
t.Fatal("first failure committed early")
}
commit, _ := ledger.take(second, false)
if len(commit) != 2 {
t.Fatalf("commit %+v", commit)
}
book := &sampleBook{profile: "nq-udp"}
for _, outcome := range commit {
book.add(outcome)
}
summary := book.summary()
if summary.OK != 0 || summary.Sent != 2 || summary.ProbeLossPct == nil || *summary.ProbeLossPct != 100 {
t.Fatalf("summary %+v", summary)
}
}
func TestMeasuredTimeoutStillCounts(t *testing.T) {
ledger := &selectionLedger{candidates: 2}
ok := Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: 4 * time.Millisecond}
if commit, _ := ledger.take(ok, true); len(commit) != 1 {
t.Fatal(commit)
}
miss := Outcome{Status: statusTimeout, Kind: kindProbe}
commit, _ := ledger.take(miss, false)
if len(commit) != 1 || commit[0].Status != statusTimeout {
t.Fatalf("post-selection miss hidden: %+v", commit)
}
book := &sampleBook{profile: "nq-udp"}
book.add(ok)
book.add(commit[0])
summary := book.summary()
if summary.ProbeLossPct == nil || *summary.ProbeLossPct != 50 || summary.Sent != 2 {
t.Fatalf("summary %+v", summary)
}
}
func TestLatencyRanks(t *testing.T) {
if nearestRank95(1) != 1 || nearestRank95(2) != 2 || nearestRank95(4) != 4 || nearestRank95(5) != 5 || nearestRank95(20) != 19 {
t.Fatalf("ranks %d %d %d %d %d", nearestRank95(1), nearestRank95(2), nearestRank95(4), nearestRank95(5), nearestRank95(20))
}
min, mean, median, p95, max, ok := latencyOf([]float64{1, 2, 3, 4})
if !ok || min != 1 || mean != 2.5 || median != 2.5 || p95 != 4 || max != 4 {
t.Fatalf("four %v %v %v %v %v", min, mean, median, p95, max)
}
_, _, median, p95, _, ok = latencyOf([]float64{1, 2, 3, 4, 10})
if !ok || median != 3 || p95 != 10 {
t.Fatalf("five median %v p95 %v", median, p95)
}
_, _, _, _, _, ok = latencyOf(nil)
if ok {
t.Fatal("empty latency")
}
book := &sampleBook{profile: "nq-udp"}
book.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: time.Millisecond})
book.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: 4 * time.Millisecond})
summary := book.summary()
if summary.MinRttMs == nil || *summary.MinRttMs != 1 || summary.MaxRttMs == nil || *summary.MaxRttMs != 4 || summary.MedianRttMs == nil || *summary.MedianRttMs != 2.5 {
t.Fatalf("aliased latency %+v", summary)
}
}
func TestDialFirstSkipsFailedCandidate(t *testing.T) {
good, bad := net.Pipe()
defer good.Close()
defer bad.Close()
v6 := net.ParseIP("2001:db8::1")
v4 := net.ParseIP("203.0.113.5")
calls := 0
conn, used, skipped, err := dialFirst(context.Background(), []net.IP{v6, v4}, time.Second, func(ctx context.Context, ip net.IP) (net.Conn, error) {
calls++
if ip.Equal(v6) {
return nil, errors.New("network unreachable")
}
return good, nil
})
if err != nil || !used.Equal(v4) || len(skipped) != 1 || calls != 2 {
t.Fatalf("used %v skipped %v err %v calls %d", used, skipped, err, calls)
}
_ = conn.Close()
_, _, skipped, err = dialFirst(context.Background(), []net.IP{v6, v4}, time.Second, func(context.Context, net.IP) (net.Conn, error) {
return nil, context.DeadlineExceeded
})
if err == nil || len(skipped) != 2 {
t.Fatalf("all-fail err %v skipped %v", err, skipped)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, _, _, err = dialFirst(ctx, []net.IP{v6, v4}, time.Second, func(context.Context, net.IP) (net.Conn, error) {
t.Fatal("dialled after cancel")
return nil, nil
})
if !errors.Is(err, context.Canceled) {
t.Fatalf("cancel err %v", err)
}
}
func TestResolveTargetsKeepsOrder(t *testing.T) {
resolver := stubResolver{[]net.IP{net.ParseIP("2001:db8::1"), net.ParseIP("203.0.113.5")}}
ips, err := resolveTargets(context.Background(), resolver, "example.com", false, nil)
if err != nil || len(ips) != 2 || ips[0].String() != "2001:db8::1" || ips[1].String() != "203.0.113.5" {
t.Fatalf("ips %v err %v", ips, err)
}
first, err := targetOK(context.Background(), resolver, "example.com", false, nil)
if err != nil || first.String() != "2001:db8::1" {
t.Fatalf("first %v err %v", first, err)
}
}
func TestStopDoesNotRecordInFlight(t *testing.T) {
blackhole, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
defer blackhole.Close()
node := newNode("", true, nil, testLimits())
srv := httptest.NewServer(node.Handler())
defer srv.Close()
id := createJob(t, srv.URL, "", map[string]any{
"target": "127.0.0.1", "port": blackhole.LocalAddr().(*net.UDPAddr).Port,
"profile": "nq-udp", "intervalMs": 200, "timeoutMs": 4000, "durationSec": 5, "packetSize": 80,
})
time.Sleep(50 * time.Millisecond)
req, err := http.NewRequest(http.MethodDelete, srv.URL+"/v1/jobs/"+id, nil)
if err != nil {
t.Fatal(err)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
time.Sleep(100 * time.Millisecond)
snapReq, err := http.NewRequest(http.MethodGet, srv.URL+"/v1/jobs/"+id, nil)
if err != nil {
t.Fatal(err)
}
snapRes, err := http.DefaultClient.Do(snapReq)
if err != nil {
t.Fatal(err)
}
defer snapRes.Body.Close()
if snapRes.StatusCode == http.StatusNotFound {
return
}
body, _ := io.ReadAll(snapRes.Body)
var msg sampleMsg
if err := json.Unmarshal(body, &msg); err != nil {
t.Fatal(err)
}
if msg.Summary.Sent > 0 || msg.Status == statusTimeout || msg.Status == statusUnknown {
t.Fatalf("cancelled probe counted %s", body)
}
}
func TestNodeUDPFallbackIsNotLoss(t *testing.T) {
drop, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.2")})
if err != nil {
t.Skipf("127.0.0.2 unavailable: %v", err)
}
defer drop.Close()
go func() {
buf := make([]byte, 2048)
for {
if _, _, err := drop.ReadFromUDP(buf); err != nil {
return
}
}
}()
port := drop.LocalAddr().(*net.UDPAddr).Port
echo, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port})
if err != nil {
t.Skipf("paired echo: %v", err)
}
defer echo.Close()
reflector := &Server{}
go reflector.ServeUDP(echo)
defer reflector.Close()
node := newNode("", true, nil, testLimits())
node.Resolver = stubResolver{[]net.IP{net.ParseIP("127.0.0.2"), net.ParseIP("127.0.0.1")}}
srv := httptest.NewServer(node.Handler())
defer srv.Close()
id := createJob(t, srv.URL, "", map[string]any{
"target": "example.test", "port": port, "profile": "nq-udp",
"intervalMs": 200, "timeoutMs": 300, "durationSec": 5, "packetSize": 80,
})
sample := readOneSample(t, srv.URL, "", id)
if sample.Status != statusOK || sample.Detail["address"] != "127.0.0.1" || sample.Detail["family"] != "IPv4" {
t.Fatalf("sample %+v", sample)
}
if sample.Summary.Sent != 1 || sample.Summary.Timeout != 0 || sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 || sample.Summary.SelectionSkipped != 1 {
t.Fatalf("loss polluted %+v", sample.Summary)
}
if !strings.Contains(sample.Detail["fallback"], "127.0.0.2") || !strings.Contains(sample.Detail["fallback"], "没有计入") {
t.Fatalf("fallback %q", sample.Detail["fallback"])
}
}
func containsAll(text string, parts ...string) bool {
for _, part := range parts {
if !strings.Contains(text, part) {
return false
}
}
return true
}