Add netquality 1.1.2 client and node behavior.
Show the address actually probed, keep address-selection misses out of formal loss, and add session metrics, a stop summary, pinned chart points, and in-app metric and release-history screens. Client version is 1.1.2+5. Attribution remains 言灸 under AGPL-3.0-only. Co-authored-by: yanjiu0721 <yanjiu0721@users.noreply.github.com>
This commit is contained in:
1 parent
8ca2185c01
commit
aeb08ec049
40 files changed
+3827
-545
No files matched your search
+1
-1
@@ -7,4 +7,4 @@ flutter pub get
|
||||
flutter run -d linux
|
||||
```
|
||||
|
||||
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。
|
||||
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。合作反射 UDP 默认 `19091`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。当前版本是 1.1.2。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。
|
||||
@@ -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,所以这里不写成另一个版本。';
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'latency.dart';
|
||||
|
||||
class Outcome {
|
||||
const Outcome({
|
||||
required this.status,
|
||||
@@ -6,6 +8,7 @@ class Outcome {
|
||||
this.note = '',
|
||||
this.detail = const {},
|
||||
this.reconnect = false,
|
||||
this.selectionSkipped = 0,
|
||||
});
|
||||
|
||||
final String status;
|
||||
@@ -15,6 +18,10 @@ class Outcome {
|
||||
final Map<String, String> detail;
|
||||
final bool reconnect;
|
||||
|
||||
/// Candidate failures folded into this measured attempt. They are not
|
||||
/// themselves samples.
|
||||
final int selectionSkipped;
|
||||
|
||||
static const ok = 'ok';
|
||||
static const timeout = 'timeout';
|
||||
static const unknown = 'unknown';
|
||||
@@ -48,6 +55,13 @@ class ProbeSummary {
|
||||
required this.unknownPct,
|
||||
required this.lastNote,
|
||||
required this.detail,
|
||||
this.minRttMs,
|
||||
this.meanRttMs,
|
||||
this.medianRttMs,
|
||||
this.p95RttMs,
|
||||
this.maxRttMs,
|
||||
this.selectionSkipped = 0,
|
||||
this.latencyStats = false,
|
||||
});
|
||||
|
||||
final int sent;
|
||||
@@ -68,6 +82,15 @@ class ProbeSummary {
|
||||
final double? unknownPct;
|
||||
final String lastNote;
|
||||
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(
|
||||
sent: 0,
|
||||
@@ -110,6 +133,16 @@ class ProbeSummary {
|
||||
unknownPct: _double(json['unknownPct']),
|
||||
lastNote: json['lastNote'] is String ? json['lastNote'] as String : '',
|
||||
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) {
|
||||
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;
|
||||
return ProbeSample(
|
||||
seq: _int(json['seq']),
|
||||
@@ -171,12 +206,15 @@ class SampleBook {
|
||||
double jitterMs = 0;
|
||||
bool _hasJitter = false;
|
||||
double _lastTransit = 0;
|
||||
final List<double> _rtts = [];
|
||||
int selectionSkipped = 0;
|
||||
String lastNote = '';
|
||||
Map<String, String> detail = {};
|
||||
|
||||
void add(Outcome outcome) {
|
||||
sent += 1;
|
||||
completed += 1;
|
||||
selectionSkipped += outcome.selectionSkipped;
|
||||
if (outcome.reconnect) {
|
||||
reconnects += 1;
|
||||
}
|
||||
@@ -193,6 +231,7 @@ class SampleBook {
|
||||
final rtt = outcome.rttMs;
|
||||
if (rtt != null) {
|
||||
lastRttMs = rtt;
|
||||
_rtts.add(rtt);
|
||||
if (_hasJitter) {
|
||||
final delta = (rtt - _lastTransit).abs();
|
||||
jitterMs += (delta - jitterMs) / 16;
|
||||
@@ -250,6 +289,7 @@ class SampleBook {
|
||||
}
|
||||
}
|
||||
}
|
||||
final latency = LatencyStats.from(_rtts);
|
||||
return ProbeSummary(
|
||||
sent: sent,
|
||||
completed: completed,
|
||||
@@ -269,6 +309,13 @@ class SampleBook {
|
||||
unknownPct: unknownPct,
|
||||
lastNote: lastNote,
|
||||
detail: detail,
|
||||
minRttMs: latency?.min,
|
||||
meanRttMs: latency?.mean,
|
||||
medianRttMs: latency?.median,
|
||||
p95RttMs: latency?.p95,
|
||||
maxRttMs: latency?.max,
|
||||
selectionSkipped: selectionSkipped,
|
||||
latencyStats: true,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 != '已停止';
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
@@ -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。只有当前端口仍是上一种类型的默认值或为空时,切换类型才会自动更换。';
|
||||
@@ -1,22 +1,67 @@
|
||||
// Copyright (C) 2026 言灸
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../metrics/sample_book.dart';
|
||||
import '../models/probe_profile.dart';
|
||||
import '../models/session_config.dart';
|
||||
import '../ui/address_text.dart';
|
||||
import 'endpoint_picker.dart';
|
||||
import 'probe_loop.dart';
|
||||
import 'remote_client.dart';
|
||||
|
||||
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? rttMs;
|
||||
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 {
|
||||
const ProbeView({
|
||||
required this.running,
|
||||
@@ -28,8 +73,22 @@ class ProbeView {
|
||||
required this.samples,
|
||||
required this.rateLabel,
|
||||
required this.sourceLabel,
|
||||
this.targetAddress,
|
||||
this.targetIsFake = false,
|
||||
required this.sessionId,
|
||||
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(
|
||||
@@ -42,6 +101,8 @@ class ProbeView {
|
||||
samples: [],
|
||||
rateLabel: '探测无应答',
|
||||
sourceLabel: '本机',
|
||||
sessionId: 0,
|
||||
elapsed: Duration.zero,
|
||||
);
|
||||
|
||||
final bool running;
|
||||
@@ -53,8 +114,22 @@ class ProbeView {
|
||||
final List<ChartSample> samples;
|
||||
final String rateLabel;
|
||||
final String sourceLabel;
|
||||
final String? targetAddress;
|
||||
final bool targetIsFake;
|
||||
final int sessionId;
|
||||
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({
|
||||
bool? running,
|
||||
@@ -67,8 +142,24 @@ class ProbeView {
|
||||
List<ChartSample>? samples,
|
||||
String? rateLabel,
|
||||
String? sourceLabel,
|
||||
String? targetAddress,
|
||||
bool? targetIsFake,
|
||||
int? sessionId,
|
||||
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(
|
||||
running: running ?? this.running,
|
||||
@@ -80,8 +171,22 @@ class ProbeView {
|
||||
samples: samples ?? this.samples,
|
||||
rateLabel: rateLabel ?? this.rateLabel,
|
||||
sourceLabel: sourceLabel ?? this.sourceLabel,
|
||||
targetAddress: targetAddress ?? this.targetAddress,
|
||||
targetIsFake: targetIsFake ?? this.targetIsFake,
|
||||
sessionId: sessionId ?? this.sessionId,
|
||||
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;
|
||||
String _nodeToken = '';
|
||||
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 {
|
||||
final problem = config.validate();
|
||||
if (problem != null) {
|
||||
view = view.copyWith(banner: problem, phase: '无法开始');
|
||||
notifyListeners();
|
||||
Future<void> start(
|
||||
SessionConfig config, {
|
||||
required String nodeToken,
|
||||
required String echoToken,
|
||||
}) async {
|
||||
if (_busy) {
|
||||
return;
|
||||
}
|
||||
final echoProblem = _echoProblem(config.profileId, echoToken);
|
||||
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;
|
||||
_busy = true;
|
||||
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),
|
||||
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: '已停止');
|
||||
final problem = config.validate();
|
||||
if (problem != null) {
|
||||
view = view.copyWith(banner: problem, phase: '无法开始');
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
} on RemoteException catch (error) {
|
||||
if (generation == _token) {
|
||||
view = view.copyWith(running: false, phase: '出错', banner: error.message);
|
||||
final echoProblem = _echoProblem(config.profileId, echoToken);
|
||||
if (echoProblem != null) {
|
||||
view = view.copyWith(banner: echoProblem, phase: '无法开始');
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
} on Object {
|
||||
if (generation == _token) {
|
||||
view = view.copyWith(running: false, phase: '出错', banner: '探测中断');
|
||||
notifyListeners();
|
||||
await stop();
|
||||
_nodeToken = nodeToken;
|
||||
_remoteMode = config.remote;
|
||||
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 {
|
||||
if (generation == _token) {
|
||||
_local = null;
|
||||
_remote = null;
|
||||
}
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,11 +363,73 @@ class ProbeController extends ChangeNotifier {
|
||||
_nodeToken = '';
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
if (generation != _token) {
|
||||
return;
|
||||
@@ -246,6 +454,16 @@ class ProbeController extends ChangeNotifier {
|
||||
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(
|
||||
phase: phaseFor(sample.status),
|
||||
note: sample.note,
|
||||
@@ -253,9 +471,24 @@ class ProbeController extends ChangeNotifier {
|
||||
summary: sample.summary,
|
||||
samples: samples,
|
||||
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();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_tick?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
String? _echoProblem(String profileId, String echoToken) {
|
||||
|
||||
@@ -3,7 +3,9 @@ import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../metrics/sample_book.dart';
|
||||
import '../metrics/selection_ledger.dart';
|
||||
import '../protocol/probe_packet.dart';
|
||||
import '../ui/address_text.dart';
|
||||
import 'endpoint_picker.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
|
||||
/// recorded, so stopping cannot paint a fake loss sample.
|
||||
class ProbeLoop {
|
||||
ProbeLoop({
|
||||
this.lookup,
|
||||
this.onEndpoint,
|
||||
});
|
||||
ProbeLoop({this.lookup, this.onEndpoint, this.onResolved});
|
||||
|
||||
/// Replaces [lookupAll] in tests.
|
||||
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.
|
||||
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;
|
||||
_UdpPipe? _udp;
|
||||
EndpointPicker? _picker;
|
||||
SelectionLedger? _ledger;
|
||||
InternetAddress? _announced;
|
||||
InternetAddress? _tcpUsed;
|
||||
List<InternetAddress>? _resolved;
|
||||
int _seq = 0;
|
||||
int _dnsId = 1;
|
||||
final int _guid = DateTime.now().microsecondsSinceEpoch;
|
||||
@@ -65,20 +70,32 @@ class ProbeLoop {
|
||||
while (!cancelled()) {
|
||||
final started = DateTime.now();
|
||||
final outcome = await _once(request, cancelled);
|
||||
if (cancelled() || outcome == null) {
|
||||
if (!countsAfterStop(outcome, cancelled: cancelled())) {
|
||||
break;
|
||||
}
|
||||
if (_usesDatagram(request.profileId)) {
|
||||
final responded = outcome.status == Outcome.ok ||
|
||||
outcome.status == Outcome.protocol ||
|
||||
outcome.status == Outcome.refused;
|
||||
if (_picker != null && _picker!.record(responded)) {
|
||||
var commit = <Outcome>[outcome!];
|
||||
if (_usesDatagram(request.profileId) && _picker != null) {
|
||||
_ledger ??= SelectionLedger(_picker!.candidates.length);
|
||||
final responded = selectionResponded(outcome);
|
||||
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();
|
||||
_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 rest = request.interval - spent;
|
||||
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 {
|
||||
final outcome = await _dispatch(request, cancelled);
|
||||
final peer = _udp?.peer;
|
||||
@@ -160,45 +180,58 @@ class ProbeLoop {
|
||||
ProbeRequest request,
|
||||
bool Function() cancelled,
|
||||
) async {
|
||||
final watch = Stopwatch()..start();
|
||||
final socket = await Socket.connect(
|
||||
request.host,
|
||||
request.port,
|
||||
timeout: request.timeout,
|
||||
);
|
||||
watch.stop();
|
||||
final opened = await _openTcp(request, cancelled);
|
||||
final failure = opened.failure;
|
||||
if (failure != null) {
|
||||
return failure;
|
||||
}
|
||||
final socket = opened.socket!;
|
||||
opened.watch?.stop();
|
||||
await socket.close();
|
||||
if (cancelled()) {
|
||||
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
|
||||
return const Outcome(
|
||||
status: Outcome.timeout,
|
||||
kind: Outcome.connect,
|
||||
note: '已停止',
|
||||
);
|
||||
}
|
||||
return Outcome(
|
||||
status: Outcome.ok,
|
||||
kind: Outcome.connect,
|
||||
rttMs: watch.elapsedMicroseconds / 1000,
|
||||
note: 'TCP 已连通',
|
||||
return _withUsed(
|
||||
Outcome(
|
||||
status: Outcome.ok,
|
||||
kind: Outcome.connect,
|
||||
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) {
|
||||
try {
|
||||
final socket = await Socket.connect(
|
||||
request.host,
|
||||
request.port,
|
||||
timeout: request.timeout,
|
||||
);
|
||||
socket.setOption(SocketOption.tcpNoDelay, true);
|
||||
_tcp = _TcpPipe(socket);
|
||||
} on SocketException catch (error) {
|
||||
return classifySocket(error, reconnect: true);
|
||||
} on TimeoutException {
|
||||
return const Outcome(
|
||||
status: Outcome.timeout,
|
||||
kind: Outcome.connect,
|
||||
reconnect: true,
|
||||
note: '连接超时,将重试',
|
||||
final opened = await _openTcp(request, cancelled);
|
||||
final failure = opened.failure;
|
||||
if (failure != null) {
|
||||
return Outcome(
|
||||
status: failure.status,
|
||||
kind: failure.kind,
|
||||
note: failure.note,
|
||||
reconnect: failure.note != '已停止',
|
||||
detail: failure.detail,
|
||||
);
|
||||
}
|
||||
final socket = opened.socket!;
|
||||
socket.setOption(SocketOption.tcpNoDelay, true);
|
||||
_tcp = _TcpPipe(socket);
|
||||
_tcpUsed = opened.used;
|
||||
fallback = opened.fallback;
|
||||
skipped = opened.skipped;
|
||||
}
|
||||
final pipe = _tcp!;
|
||||
_seq += 1;
|
||||
@@ -232,21 +265,35 @@ class ProbeLoop {
|
||||
}
|
||||
});
|
||||
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) {
|
||||
await _dropTcp();
|
||||
return const Outcome(
|
||||
status: Outcome.timeout,
|
||||
kind: Outcome.probe,
|
||||
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
|
||||
return _withUsed(
|
||||
const Outcome(
|
||||
status: Outcome.timeout,
|
||||
kind: Outcome.probe,
|
||||
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
|
||||
),
|
||||
_tcpUsed,
|
||||
fallback,
|
||||
skipped,
|
||||
);
|
||||
}
|
||||
return Outcome(
|
||||
status: Outcome.ok,
|
||||
kind: Outcome.probe,
|
||||
rttMs: watch.elapsedMicroseconds / 1000,
|
||||
note: '收到回显',
|
||||
return _withUsed(
|
||||
Outcome(
|
||||
status: Outcome.ok,
|
||||
kind: Outcome.probe,
|
||||
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);
|
||||
_seq += 1;
|
||||
final seq = _seq;
|
||||
@@ -286,7 +336,11 @@ class ProbeLoop {
|
||||
}
|
||||
});
|
||||
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 (sawInvalid) {
|
||||
@@ -329,7 +383,11 @@ class ProbeLoop {
|
||||
pipe.send(payload, request.port);
|
||||
final reply = await pipe.waitMatch(request.timeout, (_) => true);
|
||||
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) {
|
||||
return const Outcome(
|
||||
@@ -339,7 +397,8 @@ class ProbeLoop {
|
||||
);
|
||||
}
|
||||
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(
|
||||
status: Outcome.protocol,
|
||||
kind: Outcome.query,
|
||||
@@ -358,7 +417,9 @@ class ProbeLoop {
|
||||
final pipe = await _datagram(request);
|
||||
_dnsId = _dnsId == 65535 ? 1 : _dnsId + 1;
|
||||
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();
|
||||
pipe.send(dnsQuery(id, name), request.port);
|
||||
var malformed = false;
|
||||
@@ -378,7 +439,11 @@ class ProbeLoop {
|
||||
return true;
|
||||
});
|
||||
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 (malformed) {
|
||||
@@ -422,7 +487,11 @@ class ProbeLoop {
|
||||
return true;
|
||||
});
|
||||
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 (sawInvalid) {
|
||||
@@ -448,11 +517,12 @@ class ProbeLoop {
|
||||
}
|
||||
|
||||
Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async {
|
||||
final socket = await Socket.connect(
|
||||
request.host,
|
||||
request.port,
|
||||
timeout: request.timeout,
|
||||
);
|
||||
final opened = await _openTcp(request, cancelled);
|
||||
final failure = opened.failure;
|
||||
if (failure != null) {
|
||||
return failure;
|
||||
}
|
||||
final socket = opened.socket!;
|
||||
final reader = _BytePipe(socket);
|
||||
try {
|
||||
socket.add(javaHandshake(request.host, request.port));
|
||||
@@ -460,18 +530,28 @@ class ProbeLoop {
|
||||
await socket.flush();
|
||||
final status = await reader.nextPacket(request.timeout);
|
||||
if (status == null || status.isEmpty || status[0] != 0x00) {
|
||||
return const Outcome(
|
||||
status: Outcome.protocol,
|
||||
kind: Outcome.query,
|
||||
note: 'Minecraft 状态响应无效',
|
||||
return _withUsed(
|
||||
const Outcome(
|
||||
status: Outcome.protocol,
|
||||
kind: Outcome.query,
|
||||
note: 'Minecraft 状态响应无效',
|
||||
),
|
||||
opened.used,
|
||||
opened.fallback,
|
||||
opened.skipped,
|
||||
);
|
||||
}
|
||||
final jsonText = readMcString(status, 1);
|
||||
if (jsonText == null) {
|
||||
return const Outcome(
|
||||
status: Outcome.protocol,
|
||||
kind: Outcome.query,
|
||||
note: 'Minecraft 状态内容无法解析',
|
||||
return _withUsed(
|
||||
const Outcome(
|
||||
status: Outcome.protocol,
|
||||
kind: Outcome.query,
|
||||
note: 'Minecraft 状态内容无法解析',
|
||||
),
|
||||
opened.used,
|
||||
opened.fallback,
|
||||
opened.skipped,
|
||||
);
|
||||
}
|
||||
final detail = minecraftStatusDetail(jsonText);
|
||||
@@ -481,30 +561,49 @@ class ProbeLoop {
|
||||
await socket.flush();
|
||||
final pong = await reader.nextPacket(request.timeout);
|
||||
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) {
|
||||
return Outcome(
|
||||
status: Outcome.protocol,
|
||||
kind: Outcome.query,
|
||||
note: '没有收到有效的 Minecraft pong',
|
||||
detail: detail,
|
||||
return _withUsed(
|
||||
Outcome(
|
||||
status: Outcome.protocol,
|
||||
kind: Outcome.query,
|
||||
note: '没有收到有效的 Minecraft pong',
|
||||
detail: detail,
|
||||
),
|
||||
opened.used,
|
||||
opened.fallback,
|
||||
opened.skipped,
|
||||
);
|
||||
}
|
||||
if (ByteData.sublistView(pong).getUint64(1) != nonce) {
|
||||
return Outcome(
|
||||
status: Outcome.protocol,
|
||||
kind: Outcome.query,
|
||||
note: 'Minecraft pong 的时间戳不匹配',
|
||||
detail: detail,
|
||||
return _withUsed(
|
||||
Outcome(
|
||||
status: Outcome.protocol,
|
||||
kind: Outcome.query,
|
||||
note: 'Minecraft pong 的时间戳不匹配',
|
||||
detail: detail,
|
||||
),
|
||||
opened.used,
|
||||
opened.fallback,
|
||||
opened.skipped,
|
||||
);
|
||||
}
|
||||
return Outcome(
|
||||
status: Outcome.ok,
|
||||
kind: Outcome.query,
|
||||
rttMs: watch.elapsedMicroseconds / 1000,
|
||||
note: '收到 Minecraft 状态和 ping 应答',
|
||||
detail: detail,
|
||||
return _withUsed(
|
||||
Outcome(
|
||||
status: Outcome.ok,
|
||||
kind: Outcome.query,
|
||||
rttMs: watch.elapsedMicroseconds / 1000,
|
||||
note: '收到 Minecraft 状态和 ping 应答',
|
||||
detail: detail,
|
||||
),
|
||||
opened.used,
|
||||
opened.fallback,
|
||||
opened.skipped,
|
||||
);
|
||||
} finally {
|
||||
await reader.close();
|
||||
@@ -513,7 +612,7 @@ class ProbeLoop {
|
||||
}
|
||||
|
||||
Future<_UdpPipe> _datagram(ProbeRequest request) async {
|
||||
_picker ??= EndpointPicker(await (lookup ?? lookupAll)(request.host));
|
||||
_picker ??= EndpointPicker(await _addresses(request.host));
|
||||
final want = _picker!.current;
|
||||
final existing = _udp;
|
||||
if (existing != null && existing.peer.address == want.address) {
|
||||
@@ -550,6 +649,134 @@ class ProbeLoop {
|
||||
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) {
|
||||
@@ -572,7 +799,12 @@ Outcome _stampAddress(Outcome outcome, InternetAddress peer) {
|
||||
rttMs: outcome.rttMs,
|
||||
note: outcome.note,
|
||||
reconnect: outcome.reconnect,
|
||||
detail: {...outcome.detail, 'address': peer.address},
|
||||
selectionSkipped: outcome.selectionSkipped,
|
||||
detail: {
|
||||
...outcome.detail,
|
||||
'address': peer.address,
|
||||
'family': addressFamily(peer),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'dart:io';
|
||||
|
||||
import '../metrics/sample_book.dart';
|
||||
import '../models/session_config.dart';
|
||||
import '../ui/address_text.dart';
|
||||
|
||||
class RemoteProbe {
|
||||
HttpClient? _client;
|
||||
@@ -16,6 +17,7 @@ class RemoteProbe {
|
||||
required ProbeBody body,
|
||||
required void Function(ProbeSample sample) onSample,
|
||||
required bool Function() cancelled,
|
||||
void Function(List<ResolvedAddress> resolved)? onResolved,
|
||||
}) async {
|
||||
final normalized = normalizeNodeUrl(baseUrl);
|
||||
if (normalized == null) {
|
||||
@@ -52,6 +54,7 @@ class RemoteProbe {
|
||||
throw RemoteException('节点返回的任务无效');
|
||||
}
|
||||
_jobId = parsed['jobId'] as String;
|
||||
onResolved?.call(readResolvedList(parsed));
|
||||
if (cancelled()) {
|
||||
return;
|
||||
}
|
||||
@@ -86,7 +89,13 @@ class RemoteProbe {
|
||||
_jobId = null;
|
||||
if (client != null && id != null && base != null) {
|
||||
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 {
|
||||
// The stream ending already asks the node to drop the job.
|
||||
}
|
||||
@@ -101,7 +110,9 @@ class RemoteProbe {
|
||||
void Function(ProbeSample sample) onSample,
|
||||
bool Function() cancelled,
|
||||
) 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;
|
||||
_auth(request, nodeToken);
|
||||
final response = await request.close().timeout(const Duration(seconds: 20));
|
||||
@@ -194,7 +205,9 @@ Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
|
||||
}
|
||||
final client = HttpClient();
|
||||
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;
|
||||
final response = await request.close().timeout(const Duration(seconds: 8));
|
||||
final body = await response.transform(utf8.decoder).join();
|
||||
@@ -206,7 +219,9 @@ Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
|
||||
throw RemoteException('节点信息无效');
|
||||
}
|
||||
return NodeInfo(
|
||||
visibility: json['visibility'] is String ? json['visibility'] as String : '',
|
||||
visibility: json['visibility'] is String
|
||||
? json['visibility'] as String
|
||||
: '',
|
||||
authRequired: json['authRequired'] == true,
|
||||
);
|
||||
} on RemoteException {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -2,6 +2,8 @@ import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../models/node_edit.dart';
|
||||
import '../models/port_field.dart';
|
||||
import '../models/probe_profile.dart';
|
||||
import '../models/session_config.dart';
|
||||
import '../probe/endpoint_picker.dart';
|
||||
@@ -9,7 +11,11 @@ import '../probe/probe_controller.dart';
|
||||
import '../probe/remote_client.dart';
|
||||
import '../storage/app_store.dart';
|
||||
import '../storage/token_vault.dart';
|
||||
import 'address_text.dart';
|
||||
import 'format.dart';
|
||||
import 'history_page.dart';
|
||||
import 'metric_guide_page.dart';
|
||||
import 'metrics_panel.dart';
|
||||
import 'quality_charts.dart';
|
||||
|
||||
class HomePage extends StatefulWidget {
|
||||
@@ -134,7 +140,11 @@ class _HomePageState extends State<HomePage> {
|
||||
final nodeToken = config.node == null
|
||||
? ''
|
||||
: (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) {
|
||||
@@ -144,9 +154,11 @@ class _HomePageState extends State<HomePage> {
|
||||
final previous = ProbeProfile.byId(_profileId);
|
||||
final next = ProbeProfile.byId(id);
|
||||
setState(() {
|
||||
if (_port.text.trim() == '${previous.port}') {
|
||||
_port.text = '${next.port}';
|
||||
}
|
||||
_port.text = portAfterProfileChange(
|
||||
current: _port.text,
|
||||
previousDefault: previous.port,
|
||||
nextDefault: next.port,
|
||||
);
|
||||
_profileId = id;
|
||||
});
|
||||
}
|
||||
@@ -160,6 +172,22 @@ class _HomePageState extends State<HomePage> {
|
||||
appBar: AppBar(
|
||||
title: const Text('网络质量探测'),
|
||||
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(
|
||||
child: Align(
|
||||
@@ -167,12 +195,14 @@ class _HomePageState extends State<HomePage> {
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 880),
|
||||
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: [
|
||||
_card(
|
||||
title: '探测来源',
|
||||
child: _source(view, wide),
|
||||
),
|
||||
_card(title: '探测来源', child: _source(view, wide)),
|
||||
_card(
|
||||
title: '目标',
|
||||
child: Column(
|
||||
@@ -181,7 +211,13 @@ class _HomePageState extends State<HomePage> {
|
||||
_pair(
|
||||
wide,
|
||||
_field(_host, '目标地址', '域名或 IP'),
|
||||
_field(_port, '端口', '1–65535'),
|
||||
_field(
|
||||
_port,
|
||||
'端口',
|
||||
portHint(profile),
|
||||
fieldKey: const Key('port-field'),
|
||||
helper: portHelperText,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
DropdownButtonFormField<String>(
|
||||
@@ -190,12 +226,18 @@ class _HomePageState extends State<HomePage> {
|
||||
decoration: const InputDecoration(labelText: '探测类型'),
|
||||
items: [
|
||||
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,
|
||||
),
|
||||
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: [
|
||||
_pair(
|
||||
wide,
|
||||
_field(_interval, '间隔(毫秒)', _remote ? '至少 200' : '至少 100'),
|
||||
_field(
|
||||
_interval,
|
||||
'间隔(毫秒)',
|
||||
_remote ? '至少 200' : '至少 100',
|
||||
),
|
||||
_field(_timeout, '超时(毫秒)', '100–15000'),
|
||||
),
|
||||
if (profile.needsPacketSize) ...[
|
||||
@@ -252,11 +298,44 @@ class _HomePageState extends State<HomePage> {
|
||||
_banner(view.banner!),
|
||||
],
|
||||
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(
|
||||
samples: view.samples,
|
||||
rateLabel: view.rateLabel,
|
||||
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(
|
||||
'延迟用发包一侧的单调时钟计算。远程探测时,这个时间在节点上量好再传回来,不包含手机到节点的控制通道耗时。TCP 超时不是物理丢包。没有协议应答的 UDP 记为无应答/未知,不会在探测完成前显示 100%。',
|
||||
@@ -271,17 +350,25 @@ class _HomePageState extends State<HomePage> {
|
||||
}
|
||||
|
||||
Widget _source(ProbeView view, bool wide) {
|
||||
final selected = _nodes.cast<RemoteNode?>().followedBy(const [null]).firstWhere(
|
||||
(node) => node?.id == _nodeId,
|
||||
orElse: () => null,
|
||||
);
|
||||
final selected = _nodes
|
||||
.cast<RemoteNode?>()
|
||||
.followedBy(const [null])
|
||||
.firstWhere((node) => node?.id == _nodeId, orElse: () => null);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
SegmentedButton<bool>(
|
||||
segments: const [
|
||||
ButtonSegment(value: false, label: Text('本机'), icon: Icon(Icons.phone_android)),
|
||||
ButtonSegment(value: true, label: Text('远程节点'), icon: Icon(Icons.dns_outlined)),
|
||||
ButtonSegment(
|
||||
value: false,
|
||||
label: Text('本机'),
|
||||
icon: Icon(Icons.phone_android),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: true,
|
||||
label: Text('远程节点'),
|
||||
icon: Icon(Icons.dns_outlined),
|
||||
),
|
||||
],
|
||||
selected: {_remote},
|
||||
onSelectionChanged: view.running
|
||||
@@ -290,9 +377,7 @@ class _HomePageState extends State<HomePage> {
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_remote
|
||||
? '由选中的节点向目标发包,这台设备只负责控制和显示。'
|
||||
: '由这台设备直接向目标发包。可以探测本机上的反射器。',
|
||||
_remote ? '由选中的节点向目标发包,这台设备只负责控制和显示。' : '由这台设备直接向目标发包。可以探测本机上的反射器。',
|
||||
style: const TextStyle(color: muted, fontSize: 13),
|
||||
),
|
||||
if (_remote) ...[
|
||||
@@ -338,13 +423,18 @@ class _HomePageState extends State<HomePage> {
|
||||
return '${node.name} · $vis';
|
||||
}
|
||||
|
||||
Widget _result(ProbeView view) {
|
||||
Widget _result(ProbeView view, String profileId) {
|
||||
final summary = view.summary;
|
||||
final rate = view.rateLabel == '探测无应答'
|
||||
? summary.probeLossPct
|
||||
: view.rateLabel == '失败率'
|
||||
? summary.failurePct
|
||||
: summary.unknownPct;
|
||||
final address = describeAddress(
|
||||
resolved: view.resolved,
|
||||
usedAddress: view.usedAddress,
|
||||
usedFamily: view.usedFamily,
|
||||
tryingAddress: view.tryingAddress,
|
||||
tryingFamily: view.tryingFamily,
|
||||
fallbackText: view.fallbackText,
|
||||
addressUnreported: view.addressUnreported,
|
||||
usedIsFake: view.usedIsFake,
|
||||
);
|
||||
final motd = view.detail['motd'];
|
||||
final version = view.detail['version'];
|
||||
final players = view.detail['players'];
|
||||
@@ -357,13 +447,42 @@ class _HomePageState extends State<HomePage> {
|
||||
children: [
|
||||
_chip(view.phase),
|
||||
_chip('来源 ${view.sourceLabel}'),
|
||||
if (view.targetAddress != null) _chip('发往 ${view.targetAddress}'),
|
||||
_chip('延迟 ${formatMs(summary.rttMs)}'),
|
||||
_chip('抖动 ${formatMs(summary.jitterMs)}'),
|
||||
_chip('${view.rateLabel} ${formatPct(rate)}'),
|
||||
if (view.targetHost.isNotEmpty) _chip(view.targetHost),
|
||||
],
|
||||
),
|
||||
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 Text(
|
||||
clashFakeIpNote,
|
||||
@@ -386,7 +505,10 @@ class _HomePageState extends State<HomePage> {
|
||||
),
|
||||
],
|
||||
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 _url = TextEditingController();
|
||||
final _token = TextEditingController();
|
||||
String? _editingId;
|
||||
String? _hint;
|
||||
|
||||
@override
|
||||
@@ -450,6 +573,41 @@ class _NodeDialogState extends State<_NodeDialog> {
|
||||
setState(() => _hint = '请填写名称,以及不带口令的 http 或 https 地址');
|
||||
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 node = RemoteNode(id: id, name: _name.text.trim(), baseUrl: url);
|
||||
await widget.vault.write(nodeTokenKey(id), _token.text.trim());
|
||||
@@ -463,6 +621,26 @@ class _NodeDialogState extends State<_NodeDialog> {
|
||||
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 {
|
||||
try {
|
||||
final info = await fetchNodeInfo(node.baseUrl);
|
||||
@@ -487,7 +665,10 @@ class _NodeDialogState extends State<_NodeDialog> {
|
||||
|
||||
Future<void> _delete(RemoteNode node) async {
|
||||
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);
|
||||
widget.onChanged(next, null);
|
||||
}
|
||||
@@ -510,22 +691,41 @@ class _NodeDialogState extends State<_NodeDialog> {
|
||||
for (final node in _nodes)
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(_nodes.isEmpty ? '' : '${node.name} · ${visibilityLabel(node.visibility)}'),
|
||||
subtitle: Text(node.baseUrl, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
title: Text(
|
||||
'${node.name} · ${visibilityLabel(node.visibility)}',
|
||||
),
|
||||
subtitle: Text(
|
||||
node.baseUrl,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
trailing: Wrap(
|
||||
spacing: 4,
|
||||
children: [
|
||||
TextButton(onPressed: () => _check(node), child: const Text('检查')),
|
||||
TextButton(onPressed: () => _delete(node), child: const Text('删除')),
|
||||
TextButton(
|
||||
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(
|
||||
key: const Key('node-name'),
|
||||
controller: _name,
|
||||
decoration: const InputDecoration(labelText: '名称'),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
key: const Key('node-url'),
|
||||
controller: _url,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '节点地址',
|
||||
@@ -534,10 +734,14 @@ class _NodeDialogState extends State<_NodeDialog> {
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
key: const Key('node-token'),
|
||||
controller: _token,
|
||||
obscureText: true,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '节点口令(公开节点留空)',
|
||||
decoration: InputDecoration(
|
||||
labelText: _editingId == null ? '节点口令(公开节点留空)' : '新口令(留空则保留)',
|
||||
helperText: _editingId == null
|
||||
? null
|
||||
: '留空则保留已保存的口令,不会显示原口令。',
|
||||
),
|
||||
),
|
||||
if (_hint != null) ...[
|
||||
@@ -549,8 +753,17 @@ class _NodeDialogState extends State<_NodeDialog> {
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(onPressed: _save, child: const Text('添加节点')),
|
||||
TextButton(onPressed: () => Navigator.pop(context), child: const Text('完成')),
|
||||
if (_editingId != null)
|
||||
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(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
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),
|
||||
child,
|
||||
],
|
||||
@@ -582,11 +798,18 @@ Widget _field(
|
||||
String label,
|
||||
String hint, {
|
||||
bool secret = false,
|
||||
Key? fieldKey,
|
||||
String? helper,
|
||||
}) {
|
||||
return TextField(
|
||||
key: fieldKey,
|
||||
controller: controller,
|
||||
obscureText: secret,
|
||||
decoration: InputDecoration(labelText: label, hintText: hint),
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
hintText: hint,
|
||||
helperText: helper,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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)),
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import 'package:fl_chart/fl_chart.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../probe/probe_controller.dart';
|
||||
import 'chart_selection.dart';
|
||||
import 'format.dart';
|
||||
|
||||
const rttColor = Color(0xFF1F4E79);
|
||||
const rateColor = Color(0xFF9A3412);
|
||||
@@ -9,20 +11,67 @@ const ink = Color(0xFF1C2430);
|
||||
const muted = Color(0xFF5E6872);
|
||||
const line = Color(0xFFE4DFD4);
|
||||
|
||||
class QualityCharts extends StatelessWidget {
|
||||
class QualityCharts extends StatefulWidget {
|
||||
const QualityCharts({
|
||||
super.key,
|
||||
required this.samples,
|
||||
required this.rateLabel,
|
||||
required this.running,
|
||||
required this.sessionId,
|
||||
});
|
||||
|
||||
final List<ChartSample> samples;
|
||||
final String rateLabel;
|
||||
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
|
||||
Widget build(BuildContext context) {
|
||||
final pinned = _pinnedSample;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
@@ -34,29 +83,51 @@ class QualityCharts extends StatelessWidget {
|
||||
],
|
||||
),
|
||||
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(
|
||||
title: '延迟',
|
||||
unit: 'ms',
|
||||
samples: samples,
|
||||
samples: widget.samples,
|
||||
read: (sample) => sample.rttMs,
|
||||
color: rttColor,
|
||||
floor: 1,
|
||||
running: running,
|
||||
running: widget.running,
|
||||
pinnedSec: pinned?.sec,
|
||||
onPin: _pinAt,
|
||||
),
|
||||
_ChartCard(
|
||||
title: rateLabel,
|
||||
title: widget.rateLabel,
|
||||
unit: '%',
|
||||
samples: samples,
|
||||
samples: widget.samples,
|
||||
read: (sample) => sample.ratePct,
|
||||
color: rateColor,
|
||||
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 {
|
||||
const _Swatch({required this.color, required this.label});
|
||||
|
||||
@@ -92,6 +163,8 @@ class _ChartCard extends StatelessWidget {
|
||||
required this.color,
|
||||
required this.floor,
|
||||
required this.running,
|
||||
required this.pinnedSec,
|
||||
required this.onPin,
|
||||
});
|
||||
|
||||
final String title;
|
||||
@@ -101,6 +174,8 @@ class _ChartCard extends StatelessWidget {
|
||||
final Color color;
|
||||
final double floor;
|
||||
final bool running;
|
||||
final double? pinnedSec;
|
||||
final void Function(double sec) onPin;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -132,9 +207,7 @@ class _ChartCard extends StatelessWidget {
|
||||
? _lineChart(spots)
|
||||
: Center(
|
||||
child: Text(
|
||||
running
|
||||
? '正在等待第一次完成的探测。未完成的不会画成 100%。'
|
||||
: '暂无已完成的探测',
|
||||
running ? '正在等待第一次完成的探测。未完成的不会画成 100%。' : '暂无已完成的探测',
|
||||
style: const TextStyle(color: muted),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
@@ -190,7 +263,8 @@ class _ChartCard extends StatelessWidget {
|
||||
show: true,
|
||||
drawVerticalLine: false,
|
||||
horizontalInterval: yInterval,
|
||||
getDrawingHorizontalLine: (_) => const FlLine(color: line, strokeWidth: 1),
|
||||
getDrawingHorizontalLine: (_) =>
|
||||
const FlLine(color: line, strokeWidth: 1),
|
||||
),
|
||||
borderData: FlBorderData(
|
||||
show: true,
|
||||
@@ -200,14 +274,19 @@ class _ChartCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
titlesData: FlTitlesData(
|
||||
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||
topTitles: const AxisTitles(
|
||||
sideTitles: SideTitles(showTitles: false),
|
||||
),
|
||||
rightTitles: const AxisTitles(
|
||||
sideTitles: SideTitles(showTitles: false),
|
||||
),
|
||||
leftTitles: AxisTitles(
|
||||
sideTitles: SideTitles(
|
||||
showTitles: true,
|
||||
reservedSize: 40,
|
||||
interval: yInterval,
|
||||
getTitlesWidget: (value, meta) => _axisLabel(_formatTick(value, maxY)),
|
||||
getTitlesWidget: (value, meta) =>
|
||||
_axisLabel(_formatTick(value, maxY)),
|
||||
),
|
||||
),
|
||||
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: [
|
||||
LineChartBarData(
|
||||
spots: spots,
|
||||
isCurved: false,
|
||||
color: color,
|
||||
barWidth: 2,
|
||||
dotData: const FlDotData(show: false),
|
||||
belowBarData: BarAreaData(show: true, color: color.withValues(alpha: 0.10)),
|
||||
dotData: FlDotData(
|
||||
show: pinnedSec != null,
|
||||
checkToShowDot: (spot, _) =>
|
||||
pinnedSec != null &&
|
||||
(spot.x - pinnedSec!).abs() <= chartPinEpsilon,
|
||||
),
|
||||
belowBarData: BarAreaData(
|
||||
show: true,
|
||||
color: color.withValues(alpha: 0.10),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -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,6 +1,6 @@
|
||||
# 网络质量探测 · Linux 桌面客户端
|
||||
|
||||
这是 1.1.1 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。
|
||||
这是 1.1.2 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。
|
||||
|
||||
## 先安装系统库
|
||||
|
||||
|
||||
+1
-1
@@ -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
|
||||
# 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.
|
||||
version: 1.1.1+4
|
||||
version: 1.1.2+5
|
||||
|
||||
environment:
|
||||
sdk: ^3.13.7
|
||||
|
||||
@@ -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'));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
@@ -25,238 +25,261 @@ void main() {
|
||||
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 {
|
||||
final reflector = await _reflector();
|
||||
addTearDown(() => reflector.process.kill());
|
||||
final tcp = await _collect(
|
||||
ProbeRequest(
|
||||
host: '127.0.0.1',
|
||||
port: reflector.tcp,
|
||||
profileId: 'nq-tcp',
|
||||
interval: const Duration(milliseconds: 200),
|
||||
timeout: const Duration(milliseconds: 800),
|
||||
packetSize: 80,
|
||||
echoToken: '',
|
||||
dnsName: '',
|
||||
payloadHex: '',
|
||||
expectHex: '',
|
||||
),
|
||||
count: 2,
|
||||
);
|
||||
expect(tcp.last.status, Outcome.ok);
|
||||
expect(tcp.last.rttMs, greaterThan(0));
|
||||
expect(tcp.last.summary.probeLossPct, 0);
|
||||
test(
|
||||
'local nq tcp and udp get real rtt and do not call connect failure loss',
|
||||
() async {
|
||||
final reflector = await _reflector();
|
||||
addTearDown(() => reflector.process.kill());
|
||||
final tcp = await _collect(
|
||||
ProbeRequest(
|
||||
host: '127.0.0.1',
|
||||
port: reflector.tcp,
|
||||
profileId: 'nq-tcp',
|
||||
interval: const Duration(milliseconds: 200),
|
||||
timeout: const Duration(milliseconds: 800),
|
||||
packetSize: 80,
|
||||
echoToken: '',
|
||||
dnsName: '',
|
||||
payloadHex: '',
|
||||
expectHex: '',
|
||||
),
|
||||
count: 2,
|
||||
);
|
||||
expect(tcp.last.status, Outcome.ok);
|
||||
expect(tcp.last.rttMs, greaterThan(0));
|
||||
expect(tcp.last.summary.probeLossPct, 0);
|
||||
|
||||
final udp = await _collect(
|
||||
ProbeRequest(
|
||||
host: '127.0.0.1',
|
||||
port: reflector.udp,
|
||||
profileId: 'nq-udp',
|
||||
interval: const Duration(milliseconds: 200),
|
||||
timeout: const Duration(milliseconds: 800),
|
||||
packetSize: 80,
|
||||
echoToken: '',
|
||||
dnsName: '',
|
||||
payloadHex: '',
|
||||
expectHex: '',
|
||||
),
|
||||
count: 1,
|
||||
);
|
||||
expect(udp.single.status, Outcome.ok);
|
||||
expect(udp.single.summary.probeLossPct, 0);
|
||||
final udp = await _collect(
|
||||
ProbeRequest(
|
||||
host: '127.0.0.1',
|
||||
port: reflector.udp,
|
||||
profileId: 'nq-udp',
|
||||
interval: const Duration(milliseconds: 200),
|
||||
timeout: const Duration(milliseconds: 800),
|
||||
packetSize: 80,
|
||||
echoToken: '',
|
||||
dnsName: '',
|
||||
payloadHex: '',
|
||||
expectHex: '',
|
||||
),
|
||||
count: 1,
|
||||
);
|
||||
expect(udp.single.status, Outcome.ok);
|
||||
expect(udp.single.summary.probeLossPct, 0);
|
||||
|
||||
final refused = await _collect(
|
||||
ProbeRequest(
|
||||
host: '127.0.0.1',
|
||||
port: 1,
|
||||
profileId: 'tcp-connect',
|
||||
interval: const Duration(milliseconds: 200),
|
||||
timeout: const Duration(milliseconds: 400),
|
||||
packetSize: 64,
|
||||
echoToken: '',
|
||||
dnsName: '',
|
||||
payloadHex: '',
|
||||
expectHex: '',
|
||||
),
|
||||
count: 1,
|
||||
);
|
||||
expect(refused.single.status, Outcome.refused);
|
||||
expect(refused.single.summary.failurePct, 100);
|
||||
expect(refused.single.summary.probeLossPct, isNull);
|
||||
});
|
||||
final refused = await _collect(
|
||||
ProbeRequest(
|
||||
host: '127.0.0.1',
|
||||
port: 1,
|
||||
profileId: 'tcp-connect',
|
||||
interval: const Duration(milliseconds: 200),
|
||||
timeout: const Duration(milliseconds: 400),
|
||||
packetSize: 64,
|
||||
echoToken: '',
|
||||
dnsName: '',
|
||||
payloadHex: '',
|
||||
expectHex: '',
|
||||
),
|
||||
count: 1,
|
||||
);
|
||||
expect(refused.single.status, Outcome.refused);
|
||||
expect(refused.single.summary.failurePct, 100);
|
||||
expect(refused.single.summary.probeLossPct, isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test('silence is unknown, games answer, and a remote node measures rtt', () async {
|
||||
final hole = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
|
||||
addTearDown(hole.close);
|
||||
hole.listen((event) {
|
||||
if (event == RawSocketEvent.read) {
|
||||
hole.receive();
|
||||
}
|
||||
});
|
||||
final unknown = await _collect(
|
||||
ProbeRequest(
|
||||
host: '127.0.0.1',
|
||||
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();
|
||||
test(
|
||||
'silence is unknown, games answer, and a remote node measures rtt',
|
||||
() async {
|
||||
final hole = await RawDatagramSocket.bind(
|
||||
InternetAddress.loopbackIPv4,
|
||||
0,
|
||||
);
|
||||
addTearDown(hole.close);
|
||||
hole.listen((event) {
|
||||
if (event == RawSocketEvent.read) {
|
||||
hole.receive();
|
||||
}
|
||||
}
|
||||
}());
|
||||
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);
|
||||
});
|
||||
});
|
||||
final unknown = await _collect(
|
||||
ProbeRequest(
|
||||
host: '127.0.0.1',
|
||||
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');
|
||||
|
||||
test('plain udp leaves a silent address and keeps one that 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;
|
||||
}
|
||||
addTearDown(echo.close);
|
||||
echo.listen((event) {
|
||||
if (event != RawSocketEvent.read) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
}());
|
||||
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;
|
||||
}
|
||||
final datagram = echo.receive();
|
||||
if (datagram == null) {
|
||||
return;
|
||||
}
|
||||
echo.send(datagram.data, datagram.address, datagram.port);
|
||||
});
|
||||
addTearDown(echo.close);
|
||||
echo.listen((event) {
|
||||
if (event != RawSocketEvent.read) {
|
||||
return;
|
||||
}
|
||||
final datagram = echo.receive();
|
||||
if (datagram == null) {
|
||||
return;
|
||||
}
|
||||
echo.send(datagram.data, datagram.address, datagram.port);
|
||||
});
|
||||
|
||||
final seen = <String>[];
|
||||
final samples = await _collect(
|
||||
ProbeRequest(
|
||||
host: 'example.test',
|
||||
port: port,
|
||||
profileId: 'udp-generic',
|
||||
interval: const Duration(milliseconds: 40),
|
||||
timeout: const Duration(milliseconds: 250),
|
||||
packetSize: 16,
|
||||
echoToken: '',
|
||||
dnsName: '',
|
||||
payloadHex: '',
|
||||
expectHex: '',
|
||||
),
|
||||
count: 2,
|
||||
loop: ProbeLoop(
|
||||
lookup: (host) async {
|
||||
expect(host, 'example.test');
|
||||
return [InternetAddress('127.0.0.1'), InternetAddress('::1')];
|
||||
},
|
||||
onEndpoint: (address) => seen.add(address.address),
|
||||
),
|
||||
);
|
||||
expect(samples.first.status, Outcome.unknown);
|
||||
expect(samples.first.detail['address'], '127.0.0.1');
|
||||
expect(samples.last.status, Outcome.ok);
|
||||
expect(samples.last.detail['address'], '::1');
|
||||
expect(seen, ['127.0.0.1', '::1']);
|
||||
});
|
||||
final seen = <String>[];
|
||||
final samples = await _collect(
|
||||
ProbeRequest(
|
||||
host: 'example.test',
|
||||
port: port,
|
||||
profileId: 'udp-generic',
|
||||
interval: const Duration(milliseconds: 40),
|
||||
timeout: const Duration(milliseconds: 250),
|
||||
packetSize: 16,
|
||||
echoToken: '',
|
||||
dnsName: '',
|
||||
payloadHex: '',
|
||||
expectHex: '',
|
||||
),
|
||||
count: 2,
|
||||
loop: ProbeLoop(
|
||||
lookup: (host) async {
|
||||
expect(host, 'example.test');
|
||||
return [InternetAddress('127.0.0.1'), InternetAddress('::1')];
|
||||
},
|
||||
onEndpoint: (address) => seen.add(address.address),
|
||||
),
|
||||
);
|
||||
expect(samples.first.status, Outcome.ok);
|
||||
expect(samples.first.detail['address'], '::1');
|
||||
expect(samples.first.detail['family'], 'IPv6');
|
||||
expect(samples.first.detail['fallback'], contains('127.0.0.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 {
|
||||
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.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);
|
||||
}
|
||||
|
||||
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 control = await _freeTcp();
|
||||
final process = await Process.start(binary, [
|
||||
|
||||
@@ -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));
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:netquality/main.dart';
|
||||
@@ -27,7 +29,9 @@ void main() {
|
||||
const config = SessionConfig(
|
||||
remote: true,
|
||||
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',
|
||||
port: 25565,
|
||||
profileId: 'minecraft-java',
|
||||
@@ -47,4 +51,115 @@ void main() {
|
||||
expect(again.toJson().containsKey('nodeToken'), isFalse);
|
||||
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);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user