From bc39956b6cec1b2d9cde640212e97de02e9a9be2 Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 18:58:20 +0800 Subject: [PATCH 01/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=BA=90=E6=96=87=E4=BB=B6?= =?UTF-8?q?=EF=BC=88=E4=B8=80=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- client/lib/content/release_history.dart | 55 +++++++++++ client/lib/metrics/latency.dart | 65 ++++++++++++ client/lib/metrics/selection_ledger.dart | 120 +++++++++++++++++++++++ client/lib/models/node_edit.dart | 45 +++++++++ 4 files changed, 285 insertions(+) create mode 100644 client/lib/content/release_history.dart create mode 100644 client/lib/metrics/latency.dart create mode 100644 client/lib/metrics/selection_ledger.dart create mode 100644 client/lib/models/node_edit.dart diff --git a/client/lib/content/release_history.dart b/client/lib/content/release_history.dart new file mode 100644 index 0000000..2e3dd87 --- /dev/null +++ b/client/lib/content/release_history.dart @@ -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 points; +} + +const releaseHistory = [ + 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,所以这里不写成另一个版本。'; diff --git a/client/lib/metrics/latency.dart b/client/lib/metrics/latency.dart new file mode 100644 index 0000000..ccd9fae --- /dev/null +++ b/client/lib/metrics/latency.dart @@ -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 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; +} diff --git a/client/lib/metrics/selection_ledger.dart b/client/lib/metrics/selection_ledger.dart new file mode 100644 index 0000000..af019de --- /dev/null +++ b/client/lib/metrics/selection_ledger.dart @@ -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 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 _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.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 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 != '已停止'; +} diff --git a/client/lib/models/node_edit.dart b/client/lib/models/node_edit.dart new file mode 100644 index 0000000..256856f --- /dev/null +++ b/client/lib/models/node_edit.dart @@ -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 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, + ); +} From 6dcc2c4b892a1764feb47c378f60ec9aecca7214 Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 18:58:39 +0800 Subject: [PATCH 02/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=BA=90=E6=96=87=E4=BB=B6?= =?UTF-8?q?=EF=BC=88=E4=BA=8C=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- client/lib/models/port_field.dart | 32 ++++++++ client/lib/ui/address_text.dart | 125 +++++++++++++++++++++++++++++ client/lib/ui/chart_selection.dart | 50 ++++++++++++ client/lib/ui/history_page.dart | 90 +++++++++++++++++++++ 4 files changed, 297 insertions(+) create mode 100644 client/lib/models/port_field.dart create mode 100644 client/lib/ui/address_text.dart create mode 100644 client/lib/ui/chart_selection.dart create mode 100644 client/lib/ui/history_page.dart diff --git a/client/lib/models/port_field.dart b/client/lib/models/port_field.dart new file mode 100644 index 0000000..aa2432a --- /dev/null +++ b/client/lib/models/port_field.dart @@ -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。只有当前端口仍是上一种类型的默认值或为空时,切换类型才会自动更换。'; diff --git a/client/lib/ui/address_text.dart b/client/lib/ui/address_text.dart new file mode 100644 index 0000000..d696105 --- /dev/null +++ b/client/lib/ui/address_text.dart @@ -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 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 readResolvedList(Object? parsed) { + if (parsed is! Map) { + return const []; + } + final raw = parsed['resolved']; + if (raw is! List) { + return const []; + } + final out = []; + 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; +} diff --git a/client/lib/ui/chart_selection.dart b/client/lib/ui/chart_selection.dart new file mode 100644 index 0000000..1e410ab --- /dev/null +++ b/client/lib/ui/chart_selection.dart @@ -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 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; +} diff --git a/client/lib/ui/history_page.dart b/client/lib/ui/history_page.dart new file mode 100644 index 0000000..6393072 --- /dev/null +++ b/client/lib/ui/history_page.dart @@ -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)), + ), + ], + ), + ), + ); + } +} From d5da03d91bedf7bff1e46003ec37ef79ff44bac3 Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 18:58:53 +0800 Subject: [PATCH 03/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=BA=90=E6=96=87=E4=BB=B6?= =?UTF-8?q?=EF=BC=88=E4=B8=89=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- client/lib/ui/metric_guide_page.dart | 103 ++++++++++ client/lib/ui/metrics_panel.dart | 271 ++++++++++++++++++++++++++ client/lib/version.dart | 7 + client/test/address_display_test.dart | 99 ++++++++++ 4 files changed, 480 insertions(+) create mode 100644 client/lib/ui/metric_guide_page.dart create mode 100644 client/lib/ui/metrics_panel.dart create mode 100644 client/lib/version.dart create mode 100644 client/test/address_display_test.dart diff --git a/client/lib/ui/metric_guide_page.dart b/client/lib/ui/metric_guide_page.dart new file mode 100644 index 0000000..42cef5c --- /dev/null +++ b/client/lib/ui/metric_guide_page.dart @@ -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)), + ], + ), + ), + ); + } +} diff --git a/client/lib/ui/metrics_panel.dart b/client/lib/ui/metrics_panel.dart new file mode 100644 index 0000000..1149d20 --- /dev/null +++ b/client/lib/ui/metrics_panel.dart @@ -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 metricLines({ + required ProbeSummary summary, + required String profileId, + required Duration elapsed, +}) { + final lines = [ + 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)), + ); +} diff --git a/client/lib/version.dart b/client/lib/version.dart new file mode 100644 index 0000000..0aef720 --- /dev/null +++ b/client/lib/version.dart @@ -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'; diff --git a/client/test/address_display_test.dart b/client/test/address_display_test.dart new file mode 100644 index 0000000..ab066bd --- /dev/null +++ b/client/test/address_display_test.dart @@ -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')); + } + }); +} From 7cc4e042bd8cf688727745369964510f420ac04a Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 18:59:06 +0800 Subject: [PATCH 04/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E6=B5=8B=E8=AF=95=E4=B8=8E=E8=8A=82=E7=82=B9=E9=80=89?= =?UTF-8?q?=E5=9D=80=E6=BA=90=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- client/test/chart_selection_test.dart | 118 +++++++++++++++++++++ client/test/latency_test.dart | 102 +++++++++++++++++++ client/test/node_edit_test.dart | 101 ++++++++++++++++++ client/test/selection_ledger_test.dart | 135 +++++++++++++++++++++++++ 4 files changed, 456 insertions(+) create mode 100644 client/test/chart_selection_test.dart create mode 100644 client/test/latency_test.dart create mode 100644 client/test/node_edit_test.dart create mode 100644 client/test/selection_ledger_test.dart diff --git a/client/test/chart_selection_test.dart b/client/test/chart_selection_test.dart new file mode 100644 index 0000000..102aa92 --- /dev/null +++ b/client/test/chart_selection_test.dart @@ -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); + }); +} diff --git a/client/test/latency_test.dart b/client/test/latency_test.dart new file mode 100644 index 0000000..21c3037 --- /dev/null +++ b/client/test/latency_test.dart @@ -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 lines, String label) { + for (final line in lines) { + if (line.label == label) { + return line.value; + } + } + return null; +} diff --git a/client/test/node_edit_test.dart b/client/test/node_edit_test.dart new file mode 100644 index 0000000..0bf355b --- /dev/null +++ b/client/test/node_edit_test.dart @@ -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', + ); + }, + ); +} diff --git a/client/test/selection_ledger_test.dart b/client/test/selection_ledger_test.dart new file mode 100644 index 0000000..055575a --- /dev/null +++ b/client/test/selection_ledger_test.dart @@ -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)); + }, + ); +} From 4c6472a5049c22397445f7e9f96e0ced483e9b42 Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 18:59:20 +0800 Subject: [PATCH 05/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E8=AF=B4=E6=98=8E=E3=80=81=E9=80=89=E5=9D=80=E6=BA=90?= =?UTF-8?q?=E7=A0=81=E5=B9=B6=E6=9B=B4=E6=96=B0=20README?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- README.md | 16 +- docs/release-notes/1.1.2.md | 39 ++++ server/selection.go | 368 ++++++++++++++++++++++++++++++++++++ server/selection_test.go | 266 ++++++++++++++++++++++++++ 4 files changed, 686 insertions(+), 3 deletions(-) create mode 100644 docs/release-notes/1.1.2.md create mode 100644 server/selection.go create mode 100644 server/selection_test.go diff --git a/README.md b/README.md index 876d4d8..f47b27e 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,15 @@ flutter run -d linux 3. 「目标」填要测的主机、端口和类型。合作反射的默认端口是 TCP `19090`、UDP `19091`。Minecraft Java 默认 `25565`,基岩版默认 `19132`。 4. 点「开始探测」。远程任务到设定的时长后节点会自己停,也可以提前点停止。停止或断开都会让节点结束这次任务。 -本机的 UDP 探测会记下这次解析出的每个地址。结果上的「发往」是当前实际在用的地址。还没有哪个地址应答时,一个超时就换下一个;已经有应答之后,要连续三次没有应答才换,中途开关 VPN 不会把还在应答的地址丢掉。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。 +本机的 UDP 探测会记下这次解析出的每个地址。结果上的「实际地址」是真正发包或连通的地址,并注明 IPv4 或 IPv6。域名解析出来的地址单独标成「解析到」,不会被说成已经在用。还没有哪个地址应答时,一次失败就换下一个,这次失败不计入正式丢包,界面会说明回退;已经有应答之后,超时算正式结果,要连续三次没有应答才换。全部地址都失败时显示失败,不会显示 0% 成功。地址落在 `198.18.0.0/15` 时,界面会标明这是 VPN 假地址。 + +远程节点从 1.1.2 起会在每条结果里带上实际地址。更早的节点没有这个字段时,界面写明「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。1.1.1 的节点仍会把选址失败算进统计。 + +端口框写着当前类型的默认端口。合作反射 TCP 是 19090,UDP 是 19091。只有端口仍是上一种类型的默认值,或端口是空的,切换类型才会自动更换。 + +已有远程节点可以改名称、控制地址和口令。节点编号和当前选择不变。口令留空表示不改,界面不显示已经保存的口令。 + +手动停止后曲线还在,并给出这次的开始、结束、用时和最终指标。停止时还没完成的请求不算丢包。点曲线可以钉住该时刻,松手后仍然保留。指标的算法在应用里的「指标说明」,版本记录在「更新历史」。 节点口令保存在本机应用目录里,权限尽量收成只有自己能读,不会写进网址或日志。 @@ -96,10 +104,12 @@ cd server && go test -race ./... cd client && flutter analyze && flutter test ``` -Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.1`。 +Android 安装包是按 CPU 分开的 release 包,使用调试证书,只适合测试安装,不是应用商店签名。当前版本名 `1.1.2`,构建号 `5`。 + +这一版的说明在 [docs/release-notes/1.1.2.md](docs/release-notes/1.1.2.md)。 ## 许可 -Copyright (C) 2026 灸 言 +Copyright (C) 2026 言灸 本项目以 GNU Affero General Public License v3.0 许可(SPDX 标识:AGPL-3.0-only)。你可以在遵守该许可的前提下使用、修改和分发。完整条款见仓库根目录的 [LICENSE](LICENSE)。 diff --git a/docs/release-notes/1.1.2.md b/docs/release-notes/1.1.2.md new file mode 100644 index 0000000..43cf076 --- /dev/null +++ b/docs/release-notes/1.1.2.md @@ -0,0 +1,39 @@ +# 网络质量探测 1.1.2 + +构建号 5。署名:言灸。许可:GNU Affero General Public License v3.0(AGPL-3.0-only)。 + +这一版还没有打 Git 标签,也还没有发布安装包。下面是准备发布的说明。 + +## 节点和端口 + +- 已有远程节点可以改名称、控制地址和口令。节点编号和当前选择保持不变。 +- 修改时口令留空表示继续使用已经保存在本机的口令。界面不会把原口令填出来。填写新口令才会替换。 +- 端口框标明当前探测类型的默认端口。合作反射 TCP 默认 19090,合作反射 UDP 默认 19091。 +- 只有端口仍是上一种类型的默认值,或者端口是空的,切换类型才会自动更换。自己填过的端口会留下。 + +## 实际地址 + +- 本机和 1.1.2 节点都会显示这次真正连通或真正发包的 IP,并注明 IPv4 或 IPv6。 +- 域名解析出的地址单独标成「解析到」,不会被说成已经使用的地址。 +- 1.1.2 之前的远程节点不会在结果里带地址。界面会写「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。 + +## 选址和丢包 + +- 还没有任何地址应答时,用来挑选地址的失败(例如 IPv6 没有应答,随后 IPv4 成功)不计入已发送、超时和正式丢包,并单独说明回退。 +- 某个地址已经应答之后,对它的超时和失败仍然计入,不会因为后来又换地址而被抹掉。 +- 只有一个地址时,失败从一开始就算正式结果。 +- 每一个候选都失败时,这些失败计入正式结果。不会显示 0% 成功。 +- 1.1.1 的节点仍可能把第一次选址失败算进统计。要分开看,节点也需要这一版。 + +## 指标和停止 + +- 结果给出已发送、已收到、超时、比率、当前/最小/平均/中位/P95/最大延迟、抖动和用时。 +- 探测无应答 = 超时 ÷(超时 + 成功)。分母只含已经写出的回显尝试。分母为 0 时显示 —,不是 0%。 +- 普通 TCP 和 Minecraft Java 显示失败率,不显示丢包百分比。 +- 普通 UDP、DNS、自定义 UDP 和基岩版把沉默记为无应答。UDP 没有应答不能当成已经证实的丢包。 +- 延迟分布只统计成功样本。P95 用最近秩,秩 = ceil(0.95 × 次数)。抖动沿用 RFC 3550。 +- 手动停止后保留曲线,并给出开始、结束、用时、目标、来源、实际地址和同一套最终指标。 +- 停止时还没完成的请求不计入丢包。 +- 点曲线可以钉住该时刻的延迟和比率,松手后仍然保留。再点另一点会更换。新的一次探测,或该点滚出窗口后,选择不会跳到别的点上。 + +应用里增加了「指标说明」和「更新历史」。更新历史只列出仓库里真实存在的标签 v1.1.1,以及这一版。 diff --git a/server/selection.go b/server/selection.go new file mode 100644 index 0000000..4ddbee8 --- /dev/null +++ b/server/selection.go @@ -0,0 +1,368 @@ +// Copyright (C) 2026 言灸 +// SPDX-License-Identifier: AGPL-3.0-only + +package main + +import ( + "context" + "errors" + "fmt" + "net" + "sort" + "strings" + "time" +) + +const appVersion = "1.1.2" + +// dialState is shared by the job runner and the prober. Both hold a copy of +// jobSpec, so the mutable address choice has to live behind a pointer. +type dialState struct { + picker *endpointPicker + used net.IP + fallback string + skipped int +} + +type endpointPicker struct { + ips []net.IP + index int + misses int + locked bool + sticky int +} + +func newEndpointPicker(ips []net.IP) *endpointPicker { + return &endpointPicker{ips: append([]net.IP(nil), ips...), sticky: 3} +} + +func (p *endpointPicker) current() net.IP { + if p == nil || len(p.ips) == 0 { + return nil + } + return p.ips[p.index] +} + +func (p *endpointPicker) lock(ip net.IP) { + for i, cand := range p.ips { + if cand.Equal(ip) { + p.index = i + p.locked = true + p.misses = 0 + return + } + } +} + +// record matches the client EndpointPicker: one miss rotates until some +// address has answered; after that, sticky misses are required. +func (p *endpointPicker) record(responded bool) bool { + if responded { + p.locked = true + p.misses = 0 + return false + } + p.misses++ + limit := 1 + if p.locked { + limit = p.sticky + } + if len(p.ips) < 2 || p.misses < limit { + return false + } + p.misses = 0 + p.locked = false + p.index = (p.index + 1) % len(p.ips) + return true +} + +func (s jobSpec) candidates() []net.IP { + if s.state != nil && s.state.picker != nil && len(s.state.picker.ips) > 0 { + return s.state.picker.ips + } + if s.IP != nil { + return []net.IP{s.IP} + } + return nil +} + +func (s jobSpec) dialIP() net.IP { + if s.state != nil && s.state.picker != nil { + if ip := s.state.picker.current(); ip != nil { + return ip + } + } + if s.IP != nil { + return s.IP + } + return nil +} + +func familyOf(ip net.IP) string { + if ip == nil { + return "" + } + if ip.To4() != nil { + return "IPv4" + } + return "IPv6" +} + +func copyDetail(in map[string]string) map[string]string { + out := make(map[string]string, len(in)+2) + for k, v := range in { + out[k] = v + } + return out +} + +func stampIP(o Outcome, ip net.IP) Outcome { + if ip == nil { + return o + } + o.Detail = copyDetail(o.Detail) + o.Detail["address"] = ip.String() + o.Detail["family"] = familyOf(ip) + return o +} + +// decorate attaches the address actually dialed. Candidate-connect failures +// that were skipped in favor of a working address are copied onto this one +// outcome and then cleared, so they are not repeated on later probes. +func (s jobSpec) decorate(o Outcome) Outcome { + if s.state == nil { + if s.IP != nil { + return stampIP(o, s.IP) + } + return o + } + if s.state.used != nil { + o = stampIP(o, s.state.used) + } + if s.state.fallback != "" { + o.Detail = copyDetail(o.Detail) + o.Detail["fallback"] = s.state.fallback + s.state.fallback = "" + } + if s.state.skipped > 0 { + o.SelectionSkipped += s.state.skipped + s.state.skipped = 0 + } + return o +} + +func selectionResponded(status string) bool { + switch status { + case statusOK, statusProtocol, statusRefused: + return true + default: + return false + } +} + +func datagramProfile(profile string) bool { + switch profile { + case "nq-udp", "udp-generic", "custom-udp", "dns", "minecraft-bedrock": + return true + default: + return false + } +} + +type selectionLedger struct { + candidates int + measuring bool + held []Outcome +} + +func (l *selectionLedger) take(o Outcome, responded bool) (commit []Outcome, skipped int) { + if l.candidates <= 1 { + if responded { + l.measuring = true + } + return []Outcome{o}, 0 + } + if l.measuring { + return []Outcome{o}, 0 + } + if responded { + skipped = len(l.held) + if skipped > 0 { + o.Detail = copyDetail(o.Detail) + o.Detail["fallback"] = fallbackFromHeld(l.held, o) + o.SelectionSkipped += skipped + } + l.held = nil + l.measuring = true + return []Outcome{o}, skipped + } + l.held = append(l.held, o) + if len(l.held) >= l.candidates { + commit = append([]Outcome(nil), l.held...) + l.held = nil + return commit, 0 + } + return nil, 0 +} + +func fallbackFromHeld(held []Outcome, success Outcome) string { + parts := make([]string, 0, len(held)) + for _, o := range held { + addr := "" + fam := "" + if o.Detail != nil { + addr = o.Detail["address"] + fam = o.Detail["family"] + } + where := "未知地址" + if addr != "" { + where = addr + if fam != "" { + where = addr + "(" + fam + ")" + } + } + why := o.Note + if why == "" { + why = "没有成功" + } + parts = append(parts, where+":"+why) + } + used := "" + usedFam := "" + if success.Detail != nil { + used = success.Detail["address"] + usedFam = success.Detail["family"] + } + usedText := "另一个地址" + if used != "" { + usedText = used + if usedFam != "" { + usedText = used + "(" + usedFam + ")" + } + } + return "候选未成功:" + strings.Join(parts, ";") + "。已改用 " + usedText + "。这些失败没有计入正式丢包或失败率。" +} + +type dialFunc func(context.Context, net.IP) (net.Conn, error) + +// dialFirst tries each address with its own timeout. A failure is described +// and not returned as a separate measured attempt. If a later address +// connects, the skipped notes are returned for the diagnostic. If every +// address fails, err is the last error. A cancelled parent context does not +// become a measured timeout. +func dialFirst(ctx context.Context, ips []net.IP, timeout time.Duration, dial dialFunc) (net.Conn, net.IP, []string, error) { + if len(ips) == 0 { + return nil, nil, nil, errors.New("no address") + } + if timeout <= 0 { + timeout = 1500 * time.Millisecond + } + var skipped []string + var last error + for _, ip := range ips { + if err := ctx.Err(); err != nil { + return nil, nil, skipped, err + } + dialCtx, cancel := context.WithTimeout(ctx, timeout) + conn, err := dial(dialCtx, ip) + cancel() + if err == nil { + return conn, ip, skipped, nil + } + if errors.Is(err, context.Canceled) && ctx.Err() != nil { + return nil, nil, skipped, ctx.Err() + } + skipped = append(skipped, fmt.Sprintf("%s %s %s", familyOf(ip), ip.String(), classifyDial(err).Note)) + last = err + } + if last == nil { + last = errors.New("连接失败") + } + return nil, nil, skipped, last +} + +func dialSpecTCP(ctx context.Context, spec *jobSpec) (net.Conn, error) { + ips := spec.candidates() + start := 0 + if spec.state != nil && spec.state.picker != nil { + start = spec.state.picker.index + } + rotated := make([]net.IP, 0, len(ips)) + for n := 0; n < len(ips); n++ { + rotated = append(rotated, ips[(start+n)%len(ips)]) + } + conn, ip, skipped, err := dialFirst(ctx, rotated, spec.Timeout, func(ctx context.Context, ip net.IP) (net.Conn, error) { + return dialTCP(ctx, ip, spec.Port) + }) + if spec.state != nil { + spec.state.used = nil + spec.state.fallback = "" + spec.state.skipped = 0 + } + if err != nil { + if spec.state != nil && len(skipped) > 0 && !errors.Is(err, context.Canceled) { + spec.state.fallback = "已尝试 " + strings.Join(skipped, ";") + "。没有地址连通,这次记为失败。" + } + return nil, err + } + if spec.state != nil { + if spec.state.picker != nil { + spec.state.picker.lock(ip) + } + spec.state.used = append(net.IP(nil), ip...) + if len(skipped) > 0 { + spec.state.skipped = len(skipped) + spec.state.fallback = "候选未连通:" + strings.Join(skipped, ";") + "。已改用 " + ip.String() + "(" + familyOf(ip) + ")。这些失败没有计入正式丢包或失败率。" + } + } + return conn, nil +} + +func ensureUDP(conn *net.UDPConn, spec jobSpec) (*net.UDPConn, error) { + want := spec.dialIP() + if want == nil { + return nil, errors.New("no address") + } + if conn != nil { + if ra, ok := conn.RemoteAddr().(*net.UDPAddr); ok && ra.IP.Equal(want) { + return conn, nil + } + _ = conn.Close() + } + return dialUDP(want, spec.Port) +} + +// nearestRank95 is ceil(0.95*n) in integer arithmetic. +func nearestRank95(n int) int { + if n <= 1 { + return 1 + } + rank := (95*n + 99) / 100 + if rank < 1 { + return 1 + } + if rank > n { + return n + } + return rank +} + +func latencyOf(samples []float64) (min, mean, median, p95, max float64, ok bool) { + if len(samples) == 0 { + return 0, 0, 0, 0, 0, false + } + sorted := append([]float64(nil), samples...) + sort.Float64s(sorted) + var sum float64 + for _, v := range sorted { + sum += v + } + n := len(sorted) + if n%2 == 1 { + median = sorted[n/2] + } else { + median = (sorted[n/2-1] + sorted[n/2]) / 2 + } + rank := nearestRank95(n) + return sorted[0], sum / float64(n), median, sorted[rank-1], sorted[n-1], true +} diff --git a/server/selection_test.go b/server/selection_test.go new file mode 100644 index 0000000..1b91965 --- /dev/null +++ b/server/selection_test.go @@ -0,0 +1,266 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestSelectionLedgerDoesNotCountFallback(t *testing.T) { + ledger := &selectionLedger{candidates: 2} + miss := Outcome{ + Status: statusTimeout, + Kind: kindProbe, + Note: "未收到回显", + Detail: map[string]string{"address": "2001:db8::1", "family": "IPv6"}, + } + commit, skipped := ledger.take(miss, false) + if commit != nil || skipped != 0 { + t.Fatalf("held failure was counted: %+v %d", commit, skipped) + } + ok := Outcome{ + Status: statusOK, + Kind: kindProbe, + HasRtt: true, + Rtt: 5 * time.Millisecond, + Note: "收到回显", + Detail: map[string]string{"address": "203.0.113.5", "family": "IPv4"}, + } + commit, skipped = ledger.take(ok, true) + if skipped != 1 || len(commit) != 1 || commit[0].SelectionSkipped != 1 { + t.Fatalf("success %+v skipped %d", commit, skipped) + } + if commit[0].Detail["fallback"] == "" || !containsAll(commit[0].Detail["fallback"], "2001:db8::1", "203.0.113.5", "没有计入") { + t.Fatalf("fallback %q", commit[0].Detail["fallback"]) + } + book := &sampleBook{profile: "nq-udp"} + book.add(commit[0]) + summary := book.summary() + if summary.Sent != 1 || summary.OK != 1 || summary.Timeout != 0 || summary.ProbeLossPct == nil || *summary.ProbeLossPct != 0 { + t.Fatalf("summary %+v", summary) + } + if summary.SelectionSkipped != 1 || summary.MinRttMs == nil || *summary.MinRttMs != 5 || summary.P95RttMs == nil || *summary.P95RttMs != 5 { + t.Fatalf("stats %+v", summary) + } +} + +func TestSelectionLedgerCommitsTotalFailure(t *testing.T) { + ledger := &selectionLedger{candidates: 2} + first := Outcome{Status: statusTimeout, Kind: kindProbe, Detail: map[string]string{"address": "2001:db8::1", "family": "IPv6"}} + second := Outcome{Status: statusTimeout, Kind: kindProbe, Detail: map[string]string{"address": "203.0.113.5", "family": "IPv4"}} + if commit, _ := ledger.take(first, false); commit != nil { + t.Fatal("first failure committed early") + } + commit, _ := ledger.take(second, false) + if len(commit) != 2 { + t.Fatalf("commit %+v", commit) + } + book := &sampleBook{profile: "nq-udp"} + for _, outcome := range commit { + book.add(outcome) + } + summary := book.summary() + if summary.OK != 0 || summary.Sent != 2 || summary.ProbeLossPct == nil || *summary.ProbeLossPct != 100 { + t.Fatalf("summary %+v", summary) + } +} + +func TestMeasuredTimeoutStillCounts(t *testing.T) { + ledger := &selectionLedger{candidates: 2} + ok := Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: 4 * time.Millisecond} + if commit, _ := ledger.take(ok, true); len(commit) != 1 { + t.Fatal(commit) + } + miss := Outcome{Status: statusTimeout, Kind: kindProbe} + commit, _ := ledger.take(miss, false) + if len(commit) != 1 || commit[0].Status != statusTimeout { + t.Fatalf("post-selection miss hidden: %+v", commit) + } + book := &sampleBook{profile: "nq-udp"} + book.add(ok) + book.add(commit[0]) + summary := book.summary() + if summary.ProbeLossPct == nil || *summary.ProbeLossPct != 50 || summary.Sent != 2 { + t.Fatalf("summary %+v", summary) + } +} + +func TestLatencyRanks(t *testing.T) { + if nearestRank95(1) != 1 || nearestRank95(2) != 2 || nearestRank95(4) != 4 || nearestRank95(5) != 5 || nearestRank95(20) != 19 { + t.Fatalf("ranks %d %d %d %d %d", nearestRank95(1), nearestRank95(2), nearestRank95(4), nearestRank95(5), nearestRank95(20)) + } + min, mean, median, p95, max, ok := latencyOf([]float64{1, 2, 3, 4}) + if !ok || min != 1 || mean != 2.5 || median != 2.5 || p95 != 4 || max != 4 { + t.Fatalf("four %v %v %v %v %v", min, mean, median, p95, max) + } + _, _, median, p95, _, ok = latencyOf([]float64{1, 2, 3, 4, 10}) + if !ok || median != 3 || p95 != 10 { + t.Fatalf("five median %v p95 %v", median, p95) + } + _, _, _, _, _, ok = latencyOf(nil) + if ok { + t.Fatal("empty latency") + } + book := &sampleBook{profile: "nq-udp"} + book.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: time.Millisecond}) + book.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: 4 * time.Millisecond}) + summary := book.summary() + if summary.MinRttMs == nil || *summary.MinRttMs != 1 || summary.MaxRttMs == nil || *summary.MaxRttMs != 4 || summary.MedianRttMs == nil || *summary.MedianRttMs != 2.5 { + t.Fatalf("aliased latency %+v", summary) + } +} + +func TestDialFirstSkipsFailedCandidate(t *testing.T) { + good, bad := net.Pipe() + defer good.Close() + defer bad.Close() + v6 := net.ParseIP("2001:db8::1") + v4 := net.ParseIP("203.0.113.5") + calls := 0 + conn, used, skipped, err := dialFirst(context.Background(), []net.IP{v6, v4}, time.Second, func(ctx context.Context, ip net.IP) (net.Conn, error) { + calls++ + if ip.Equal(v6) { + return nil, errors.New("network unreachable") + } + return good, nil + }) + if err != nil || !used.Equal(v4) || len(skipped) != 1 || calls != 2 { + t.Fatalf("used %v skipped %v err %v calls %d", used, skipped, err, calls) + } + _ = conn.Close() + + _, _, skipped, err = dialFirst(context.Background(), []net.IP{v6, v4}, time.Second, func(context.Context, net.IP) (net.Conn, error) { + return nil, context.DeadlineExceeded + }) + if err == nil || len(skipped) != 2 { + t.Fatalf("all-fail err %v skipped %v", err, skipped) + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, _, _, err = dialFirst(ctx, []net.IP{v6, v4}, time.Second, func(context.Context, net.IP) (net.Conn, error) { + t.Fatal("dialled after cancel") + return nil, nil + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("cancel err %v", err) + } +} + +func TestResolveTargetsKeepsOrder(t *testing.T) { + resolver := stubResolver{[]net.IP{net.ParseIP("2001:db8::1"), net.ParseIP("203.0.113.5")}} + ips, err := resolveTargets(context.Background(), resolver, "example.com", false, nil) + if err != nil || len(ips) != 2 || ips[0].String() != "2001:db8::1" || ips[1].String() != "203.0.113.5" { + t.Fatalf("ips %v err %v", ips, err) + } + first, err := targetOK(context.Background(), resolver, "example.com", false, nil) + if err != nil || first.String() != "2001:db8::1" { + t.Fatalf("first %v err %v", first, err) + } +} + +func TestStopDoesNotRecordInFlight(t *testing.T) { + blackhole, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + defer blackhole.Close() + node := newNode("", true, nil, testLimits()) + srv := httptest.NewServer(node.Handler()) + defer srv.Close() + id := createJob(t, srv.URL, "", map[string]any{ + "target": "127.0.0.1", "port": blackhole.LocalAddr().(*net.UDPAddr).Port, + "profile": "nq-udp", "intervalMs": 200, "timeoutMs": 4000, "durationSec": 5, "packetSize": 80, + }) + time.Sleep(50 * time.Millisecond) + req, err := http.NewRequest(http.MethodDelete, srv.URL+"/v1/jobs/"+id, nil) + if err != nil { + t.Fatal(err) + } + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + res.Body.Close() + time.Sleep(100 * time.Millisecond) + snapReq, err := http.NewRequest(http.MethodGet, srv.URL+"/v1/jobs/"+id, nil) + if err != nil { + t.Fatal(err) + } + snapRes, err := http.DefaultClient.Do(snapReq) + if err != nil { + t.Fatal(err) + } + defer snapRes.Body.Close() + if snapRes.StatusCode == http.StatusNotFound { + return + } + body, _ := io.ReadAll(snapRes.Body) + var msg sampleMsg + if err := json.Unmarshal(body, &msg); err != nil { + t.Fatal(err) + } + if msg.Summary.Sent > 0 || msg.Status == statusTimeout || msg.Status == statusUnknown { + t.Fatalf("cancelled probe counted %s", body) + } +} + +func TestNodeUDPFallbackIsNotLoss(t *testing.T) { + drop, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.2")}) + if err != nil { + t.Skipf("127.0.0.2 unavailable: %v", err) + } + defer drop.Close() + go func() { + buf := make([]byte, 2048) + for { + if _, _, err := drop.ReadFromUDP(buf); err != nil { + return + } + } + }() + port := drop.LocalAddr().(*net.UDPAddr).Port + echo, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port}) + if err != nil { + t.Skipf("paired echo: %v", err) + } + defer echo.Close() + reflector := &Server{} + go reflector.ServeUDP(echo) + defer reflector.Close() + + node := newNode("", true, nil, testLimits()) + node.Resolver = stubResolver{[]net.IP{net.ParseIP("127.0.0.2"), net.ParseIP("127.0.0.1")}} + srv := httptest.NewServer(node.Handler()) + defer srv.Close() + id := createJob(t, srv.URL, "", map[string]any{ + "target": "example.test", "port": port, "profile": "nq-udp", + "intervalMs": 200, "timeoutMs": 300, "durationSec": 5, "packetSize": 80, + }) + sample := readOneSample(t, srv.URL, "", id) + if sample.Status != statusOK || sample.Detail["address"] != "127.0.0.1" || sample.Detail["family"] != "IPv4" { + t.Fatalf("sample %+v", sample) + } + if sample.Summary.Sent != 1 || sample.Summary.Timeout != 0 || sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 || sample.Summary.SelectionSkipped != 1 { + t.Fatalf("loss polluted %+v", sample.Summary) + } + if !strings.Contains(sample.Detail["fallback"], "127.0.0.2") || !strings.Contains(sample.Detail["fallback"], "没有计入") { + t.Fatalf("fallback %q", sample.Detail["fallback"]) + } +} + +func containsAll(text string, parts ...string) bool { + for _, part := range parts { + if !strings.Contains(text, part) { + return false + } + } + return true +} From 3a6356f4d9f46164ac17ff449f49552055e1824b Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 18:59:35 +0800 Subject: [PATCH 06/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E5=AE=A2=E6=88=B7=E7=AB=AF=E6=8E=A2=E6=B5=8B=E4=B8=8E?= =?UTF-8?q?=E8=AF=B4=E6=98=8E=E6=96=87=E4=BB=B6=EF=BC=88=E4=B8=80=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- client/README.md | 2 +- client/lib/metrics/sample_book.dart | 49 ++- client/lib/probe/probe_controller.dart | 447 +++++++++++++++++++------ client/lib/probe/probe_loop.dart | 416 ++++++++++++++++++----- 4 files changed, 713 insertions(+), 201 deletions(-) diff --git a/client/README.md b/client/README.md index 7a35c11..f7c280a 100644 --- a/client/README.md +++ b/client/README.md @@ -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。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。 diff --git a/client/lib/metrics/sample_book.dart b/client/lib/metrics/sample_book.dart index 9f41492..83c5413 100644 --- a/client/lib/metrics/sample_book.dart +++ b/client/lib/metrics/sample_book.dart @@ -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 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 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 json) { final summary = json['summary'] is Map - ? ProbeSummary.fromJson(Map.from(json['summary'] as Map)) + ? ProbeSummary.fromJson( + Map.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 _rtts = []; + int selectionSkipped = 0; String lastNote = ''; Map 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, ); } diff --git a/client/lib/probe/probe_controller.dart b/client/lib/probe/probe_controller.dart index f970b16..7b79be6 100644 --- a/client/lib/probe/probe_controller.dart +++ b/client/lib/probe/probe_controller.dart @@ -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 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 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 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? 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? 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 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 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) { diff --git a/client/lib/probe/probe_loop.dart b/client/lib/probe/probe_loop.dart index 1a72e67..97d51e7 100644 --- a/client/lib/probe/probe_loop.dart +++ b/client/lib/probe/probe_loop.dart @@ -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> 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 addresses)? onResolved; + _TcpPipe? _tcp; _UdpPipe? _udp; EndpointPicker? _picker; + SelectionLedger? _ledger; InternetAddress? _announced; + InternetAddress? _tcpUsed; + List? _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!]; + 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 _once(ProbeRequest request, bool Function() cancelled) async { + Future _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 _nqTcp(ProbeRequest request, bool Function() cancelled) async { + Future _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 _nqUdp(ProbeRequest request, bool Function() cancelled) async { + Future _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 _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> _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 addresses; + try { + addresses = await _addresses(request.host); + } on SocketException catch (error) { + return _TcpOpen.fail(classifySocket(error)); + } + final skipped = []; + 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), + }, ); } From c1a60eef4363cb3de44e834fd8ebc5a834485863 Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 19:00:07 +0800 Subject: [PATCH 07/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E5=AE=A2=E6=88=B7=E7=AB=AF=E7=95=8C=E9=9D=A2=E4=B8=8E?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- client/lib/probe/remote_client.dart | 23 +- client/lib/ui/home_page.dart | 315 ++++++++++++++++++++++++---- client/lib/ui/quality_charts.dart | 142 +++++++++++-- client/packaging/README-linux.md | 2 +- 4 files changed, 415 insertions(+), 67 deletions(-) diff --git a/client/lib/probe/remote_client.dart b/client/lib/probe/remote_client.dart index 562fe17..0bb4a96 100644 --- a/client/lib/probe/remote_client.dart +++ b/client/lib/probe/remote_client.dart @@ -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 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 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 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 { diff --git a/client/lib/ui/home_page.dart b/client/lib/ui/home_page.dart index 6e3a537..f84623e 100644 --- a/client/lib/ui/home_page.dart +++ b/client/lib/ui/home_page.dart @@ -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 { 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 { 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 { appBar: AppBar( title: const Text('网络质量探测'), backgroundColor: const Color(0xFFF3F1EC), + actions: [ + PopupMenuButton( + tooltip: '说明', + onSelected: (value) { + final page = value == 'history' + ? const HistoryPage() + : const MetricGuidePage(); + Navigator.of(context) + .push(MaterialPageRoute(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 { 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 { _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( @@ -190,12 +226,18 @@ class _HomePageState extends State { 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 { 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 { _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( + builder: (_) => const MetricGuidePage(), + ), + ), + child: const Text('指标说明'), + ), + TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const HistoryPage(), + ), + ), + child: const Text('更新历史'), + ), + ], ), const Text( '延迟用发包一侧的单调时钟计算。远程探测时,这个时间在节点上量好再传回来,不包含手机到节点的控制通道耗时。TCP 超时不是物理丢包。没有协议应答的 UDP 记为无应答/未知,不会在探测完成前显示 100%。', @@ -271,17 +350,25 @@ class _HomePageState extends State { } Widget _source(ProbeView view, bool wide) { - final selected = _nodes.cast().followedBy(const [null]).firstWhere( - (node) => node?.id == _nodeId, - orElse: () => null, - ); + final selected = _nodes + .cast() + .followedBy(const [null]) + .firstWhere((node) => node?.id == _nodeId, orElse: () => null); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SegmentedButton( 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 { ), const SizedBox(height: 8), Text( - _remote - ? '由选中的节点向目标发包,这台设备只负责控制和显示。' - : '由这台设备直接向目标发包。可以探测本机上的反射器。', + _remote ? '由选中的节点向目标发包,这台设备只负责控制和显示。' : '由这台设备直接向目标发包。可以探测本机上的反射器。', style: const TextStyle(color: muted, fontSize: 13), ), if (_remote) ...[ @@ -338,13 +423,18 @@ class _HomePageState extends State { 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 { 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 { ), ], 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 _check(RemoteNode node) async { try { final info = await fetchNodeInfo(node.baseUrl); @@ -487,7 +665,10 @@ class _NodeDialogState extends State<_NodeDialog> { Future _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, + ), ); } diff --git a/client/lib/ui/quality_charts.dart b/client/lib/ui/quality_charts.dart index 7b255c3..62c5c3b 100644 --- a/client/lib/ui/quality_charts.dart +++ b/client/lib/ui/quality_charts.dart @@ -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 samples; final String rateLabel; final bool running; + final int sessionId; + + @override + State createState() => _QualityChartsState(); +} + +class _QualityChartsState extends State { + 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), + ), ), ], ), diff --git a/client/packaging/README-linux.md b/client/packaging/README-linux.md index 3ef4fb2..316d937 100644 --- a/client/packaging/README-linux.md +++ b/client/packaging/README-linux.md @@ -1,6 +1,6 @@ # 网络质量探测 · Linux 桌面客户端 -这是 1.1.1 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。 +这是 1.1.2 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。 ## 先安装系统库 From 3776ece7a419b57816e1a29a157883cf5347136a Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 19:00:36 +0800 Subject: [PATCH 08/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E6=B5=8B=E8=AF=95=E3=80=81=E7=89=88=E6=9C=AC=E5=8F=B7?= =?UTF-8?q?=E4=B8=8E=E5=8D=8F=E8=AE=AE=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- client/pubspec.yaml | 2 +- client/test/probe_loop_test.dart | 479 ++++++++++++++++--------------- client/test/widget_test.dart | 117 +++++++- docs/PROTOCOL.md | 4 +- 4 files changed, 373 insertions(+), 229 deletions(-) diff --git a/client/pubspec.yaml b/client/pubspec.yaml index 9906526..03408d7 100644 --- a/client/pubspec.yaml +++ b/client/pubspec.yaml @@ -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 diff --git a/client/test/probe_loop_test.dart b/client/test/probe_loop_test.dart index fb94d51..a78af36 100644 --- a/client/test/probe_loop_test.dart +++ b/client/test/probe_loop_test.dart @@ -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 = []; - final remote = RemoteProbe(); - final done = Completer(); - 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 = []; + final remote = RemoteProbe(); + final done = Completer(); + 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 = []; - 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 = []; + 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, [ diff --git a/client/test/widget_test.dart b/client/test/widget_test.dart index 0dfe315..abb6182 100644 --- a/client/test/widget_test.dart +++ b/client/test/widget_test.dart @@ -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(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; + final nodes = decoded['nodes'] as List; + expect(nodes, hasLength(1)); + final node = nodes.single as Map; + 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)); + 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)); + 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); + }); } diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 96f92e7..fd505e8 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -44,7 +44,9 @@ - **普通 TCP**:只记录连接耗时、成功或失败、连续失败。没有自定义帧。 - **普通 UDP、DNS、自定义 UDP、基岩版**:没有收到符合协议的包时记为无应答/未知,不叫丢包。内容不对记为协议错误。 - **Minecraft Java**:状态握手加上 ping/pong。往返时间只算 ping 到对上 nonce 的 pong。连不上或协议不对记为失败率。 -- **抖动**:RFC 3550。相邻两次成功的往返时间差 `D`,`J = J + (|D| - J) / 16`。 +- **抖动**:RFC 3550。相邻两次成功的往返时间差 `D`,`J = J + (|D| - J) / 16`。第一次成功时 J 为 0。 +- **延迟分布**:只统计成功样本。当前延迟是最近一次成功。最小、最大是极值。平均是算术平均。中位数在奇数个时取排序后的中间值,偶数个时取中间两个的平均。P95 用最近秩,秩 = ceil(0.95 × 次数),用整数 `(95 × 次数 + 99) / 100` 计算,从 1 起计。 +- **选址**:一个名字解析出多个地址时,还没有任何地址应答之前的失败只用于挑选地址。后面有地址成功时,这些失败不进入已发送、超时和丢包,并在 `detail.fallback` 里说明。选定之后的失败照常计入。每个候选都失败时,这些失败计入正式结果,不能显示成 0% 成功。每条样本的 `detail.address` 和 `detail.family` 是这次实际连通或发包的地址;没有这个字段就表示节点没有报告,不能用解析结果代替。`summary` 另有 `minRttMs`、`meanRttMs`、`medianRttMs`、`p95RttMs`、`maxRttMs` 和 `selectionSkipped`。旧客户端会忽略不认识的字段。 ## 控制接口 From 3e912d4d3c3e4d76dcb47dfe799c3cfbfdd1d8b8 Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 19:00:59 +0800 Subject: [PATCH 09/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E6=9C=8D=E5=8A=A1=E7=AB=AF=E4=B8=8E=20Linux=20?= =?UTF-8?q?=E8=AF=B4=E6=98=8E=EF=BC=88=E4=B8=80=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- docs/server-linux.md | 2 +- server/README.md | 2 +- server/main.go | 1 + server/metrics.go | 41 ++++++++++++++++++++++++++++++----------- 4 files changed, 33 insertions(+), 13 deletions(-) diff --git a/docs/server-linux.md b/docs/server-linux.md index c8157a0..f324260 100644 --- a/docs/server-linux.md +++ b/docs/server-linux.md @@ -63,7 +63,7 @@ ss -lunp | grep 19091 ```bash sudo mkdir -p /opt/netquality -sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.1-linux-amd64.tar.gz +sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.2-linux-amd64.tar.gz sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service sudo systemctl daemon-reload sudo systemctl enable --now netquality diff --git a/server/README.md b/server/README.md index a861f5d..c7231f0 100644 --- a/server/README.md +++ b/server/README.md @@ -110,7 +110,7 @@ sudo firewall-cmd --reload ```bash sudo mkdir -p /opt/netquality -sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.1-linux-amd64.tar.gz +sudo tar -C /opt/netquality --strip-components=1 -xzf netquality-server-1.1.2-linux-amd64.tar.gz sudo chmod 755 /opt/netquality/netquality-reflector sudo cp /opt/netquality/netquality.service /etc/systemd/system/netquality.service sudo systemctl daemon-reload diff --git a/server/main.go b/server/main.go index 037a2e2..01c0765 100644 --- a/server/main.go +++ b/server/main.go @@ -26,6 +26,7 @@ func main() { } log.Fatal(err) } + log.Printf("netquality %s", appVersion) log.Printf("%s", cfg.Summary()) tok, err := tokenBytes(cfg.Token) diff --git a/server/metrics.go b/server/metrics.go index 4d9e77b..78f25d5 100644 --- a/server/metrics.go +++ b/server/metrics.go @@ -19,13 +19,14 @@ const ( // Outcome is one finished attempt. Pending attempts are never turned into // a sample, so a chart cannot show a fake 100% before the probe completes. type Outcome struct { - Status string - Kind string - Rtt time.Duration - HasRtt bool - Note string - Detail map[string]string - Reconnect bool + Status string + Kind string + Rtt time.Duration + HasRtt bool + Note string + Detail map[string]string + Reconnect bool + SelectionSkipped int } type jitter struct { @@ -64,15 +65,18 @@ type sampleBook struct { reconnect int consecutive int - lastRttMs *float64 - jitter jitter - lastNote string - detail map[string]string + lastRttMs *float64 + jitter jitter + rtts []float64 + selectionSkipped int + lastNote string + detail map[string]string } func (b *sampleBook) add(o Outcome) { b.sent++ b.completed++ + b.selectionSkipped += o.SelectionSkipped if o.Reconnect { b.reconnect++ } @@ -94,6 +98,7 @@ func (b *sampleBook) add(o Outcome) { if o.HasRtt { ms := float64(o.Rtt) / float64(time.Millisecond) b.lastRttMs = &ms + b.rtts = append(b.rtts, ms) b.jitter.push(ms) } case statusTimeout: @@ -138,6 +143,14 @@ func (b *sampleBook) summary() summaryMsg { ConsecutiveFailures: b.consecutive, LastNote: b.lastNote, Detail: b.detail, + SelectionSkipped: b.selectionSkipped, + } + if min, mean, median, p95, max, ok := latencyOf(b.rtts); ok { + s.MinRttMs = &min + s.MeanRttMs = &mean + s.MedianRttMs = &median + s.P95RttMs = &p95 + s.MaxRttMs = &max } if b.lastRttMs != nil { v := *b.lastRttMs @@ -197,6 +210,12 @@ type summaryMsg struct { ProbeLossPct *float64 `json:"probeLossPct,omitempty"` FailurePct *float64 `json:"failurePct,omitempty"` UnknownPct *float64 `json:"unknownPct,omitempty"` + MinRttMs *float64 `json:"minRttMs,omitempty"` + MeanRttMs *float64 `json:"meanRttMs,omitempty"` + MedianRttMs *float64 `json:"medianRttMs,omitempty"` + P95RttMs *float64 `json:"p95RttMs,omitempty"` + MaxRttMs *float64 `json:"maxRttMs,omitempty"` + SelectionSkipped int `json:"selectionSkipped,omitempty"` LastNote string `json:"lastNote,omitempty"` Detail map[string]string `json:"detail,omitempty"` } From 1d35747b628ef2753b2432055575743356d77f99 Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 19:01:21 +0800 Subject: [PATCH 10/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E6=9C=8D=E5=8A=A1=E7=AB=AF=E6=8E=A2=E6=B5=8B=E4=B8=8E?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E6=BA=90=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- server/node.go | 52 +++++++++++++++++++++++++++++++++++++++++---- server/node_test.go | 6 ++++++ server/probes.go | 48 ++++++++++++++++++++--------------------- 3 files changed, 77 insertions(+), 29 deletions(-) diff --git a/server/node.go b/server/node.go index b6a40c8..2b4a6c2 100644 --- a/server/node.go +++ b/server/node.go @@ -21,6 +21,7 @@ type jobSpec struct { Port int Profile string IP net.IP + state *dialState Interval time.Duration Timeout time.Duration Duration time.Duration @@ -110,6 +111,7 @@ func (n *Node) info(w http.ResponseWriter, _ *http.Request) { vis = "public" } writeJSON(w, http.StatusOK, map[string]any{ + "version": appVersion, "visibility": vis, "authRequired": !n.Public(), "profiles": []string{ @@ -185,10 +187,19 @@ func (n *Node) create(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusInternalServerError, "error", "任务没有启动") return } + resolved := make([]map[string]string, 0, len(spec.candidates())) + for _, ip := range spec.candidates() { + resolved = append(resolved, map[string]string{ + "address": ip.String(), + "family": familyOf(ip), + }) + } writeJSON(w, http.StatusCreated, map[string]any{ "jobId": job.id, "expiresAt": job.expires.UTC().Format(time.RFC3339), "visibility": map[bool]string{true: "public", false: "private"}[n.Public()], + "version": appVersion, + "resolved": resolved, }) } @@ -246,7 +257,7 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) { } } } - ip, err := targetOK(ctx, n.Resolver, req.Target, n.AllowPrivate, n.ExtraNets) + ips, err := resolveTargets(ctx, n.Resolver, req.Target, n.AllowPrivate, n.ExtraNets) if err != nil { var dnsErr *net.DNSError if errors.As(err, &dnsErr) { @@ -258,7 +269,8 @@ func (n *Node) prepare(ctx context.Context, req createReq) (jobSpec, error) { return jobSpec{}, &apiError{http.StatusBadRequest, "bad_target", "目标地址无效"} } return jobSpec{ - Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ip, + Host: req.Target, Port: req.Port, Profile: req.Profile, IP: ips[0], + state: &dialState{picker: newEndpointPicker(ips)}, Interval: interval, Timeout: timeout, Duration: duration, PacketSize: size, Echo: echo, DNSName: req.DNSName, Payload: payload, Expect: expect, }, nil @@ -334,18 +346,50 @@ func (n *Node) run(ctx context.Context, job *probeJob, spec jobSpec, p prober) { case <-ctx.Done(): } } + ledger := &selectionLedger{candidates: len(spec.candidates())} + datagram := datagramProfile(spec.Profile) for { if err := n.pace.wait(ctx, spec.PacketSize); err != nil { return } started := time.Now() - pctx, cancel := context.WithTimeout(ctx, spec.Timeout) + budget := spec.Timeout + if budget <= 0 { + budget = 1500 * time.Millisecond + } + if !datagram && spec.state != nil && spec.state.picker != nil && !spec.state.picker.locked && len(spec.state.picker.ips) > 1 { + budget *= time.Duration(len(spec.state.picker.ips)) + } + if datagram && spec.state != nil { + if ip := spec.dialIP(); ip != nil { + spec.state.used = append(net.IP(nil), ip...) + } + } + pctx, cancel := context.WithTimeout(ctx, budget) out := p.Probe(pctx) cancel() if ctx.Err() != nil { return } - emit(out) + out = spec.decorate(out) + var commit []Outcome + if datagram && spec.state != nil && spec.state.picker != nil { + responded := selectionResponded(out.Status) + wasMeasuring := ledger.measuring + changed := spec.state.picker.record(responded) + commit, _ = ledger.take(out, responded) + if wasMeasuring && changed { + ledger.measuring = false + } + if len(commit) == 0 { + continue + } + } else { + commit = []Outcome{out} + } + for _, item := range commit { + emit(item) + } wait := spec.Interval - time.Since(started) if wait < 0 { wait = 0 diff --git a/server/node_test.go b/server/node_test.go index 434fe2c..7100bb5 100644 --- a/server/node_test.go +++ b/server/node_test.go @@ -163,6 +163,12 @@ func TestNodeNQAndTCPAndUDP(t *testing.T) { if sample.Status != statusOK || sample.RttMs == nil || *sample.RttMs <= 0 { t.Fatalf("nq tcp %+v", sample) } + if sample.Detail["address"] != "127.0.0.1" || sample.Detail["family"] != "IPv4" { + t.Fatalf("tcp did not report the connected address %+v", sample.Detail) + } + if sample.Summary.MinRttMs == nil || sample.Summary.P95RttMs == nil { + t.Fatalf("latency stats missing %+v", sample.Summary) + } if sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 { t.Fatalf("loss %+v", sample.Summary) } diff --git a/server/probes.go b/server/probes.go index 565d4de..5457896 100644 --- a/server/probes.go +++ b/server/probes.go @@ -127,7 +127,7 @@ func (p *nqTCP) Close() error { } func (p *nqTCP) dial(ctx context.Context) error { - conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port) + conn, err := dialSpecTCP(ctx, &p.spec) if err != nil { return err } @@ -208,11 +208,9 @@ func (p *nqUDP) Close() error { } func (p *nqUDP) ensure() error { - if p.conn != nil { - return nil - } - c, err := dialUDP(p.spec.IP, p.spec.Port) + c, err := ensureUDP(p.conn, p.spec) if err != nil { + p.conn = nil return err } p.conn = c @@ -273,7 +271,7 @@ func (p *tcpConnect) Close() error { return nil } func (p *tcpConnect) Probe(ctx context.Context) Outcome { start := time.Now() - conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port) + conn, err := dialSpecTCP(ctx, &p.spec) if err != nil { return classifyDial(err) } @@ -297,13 +295,12 @@ func (p *udpQuery) Close() error { } func (p *udpQuery) Probe(ctx context.Context) Outcome { - if p.conn == nil { - c, err := dialUDP(p.spec.IP, p.spec.Port) - if err != nil { - return classifyDial(err) - } - p.conn = c + c, err := ensureUDP(p.conn, p.spec) + if err != nil { + p.conn = nil + return classifyDial(err) } + p.conn = c payload := p.spec.Payload if p.generic { n := p.spec.PacketSize @@ -358,13 +355,12 @@ func (p *dnsQuery) Close() error { } func (p *dnsQuery) Probe(ctx context.Context) Outcome { - if p.conn == nil { - c, err := dialUDP(p.spec.IP, p.spec.Port) - if err != nil { - return classifyDial(err) - } - p.conn = c + c, err := ensureUDP(p.conn, p.spec) + if err != nil { + p.conn = nil + return classifyDial(err) } + p.conn = c p.id++ if p.id == 0 { p.id = 1 @@ -449,12 +445,14 @@ func (p *mcBedrock) Close() error { } func (p *mcBedrock) Probe(ctx context.Context) Outcome { - if p.conn == nil { - c, err := dialUDP(p.spec.IP, p.spec.Port) - if err != nil { - return classifyDial(err) - } - p.conn = c + fresh := p.conn == nil + c, err := ensureUDP(p.conn, p.spec) + if err != nil { + p.conn = nil + return classifyDial(err) + } + p.conn = c + if fresh || p.guid == 0 { p.guid = uint64(time.Now().UnixNano()) } ts := uint64(time.Now().UnixNano()) @@ -529,7 +527,7 @@ type mcJava struct{ spec jobSpec } func (p *mcJava) Close() error { return nil } func (p *mcJava) Probe(ctx context.Context) Outcome { - conn, err := dialTCP(ctx, p.spec.IP, p.spec.Port) + conn, err := dialSpecTCP(ctx, &p.spec) if err != nil { return classifyDial(err) } From 420eed64f7a9c1b04dca0726b086f1d8399cb461 Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 19:01:37 +0800 Subject: [PATCH 11/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E6=9C=8D=E5=8A=A1=E7=AB=AF=E5=AE=89=E5=85=A8=E6=A3=80?= =?UTF-8?q?=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言灸 --- server/safety.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/server/safety.go b/server/safety.go index ced841b..7819261 100644 --- a/server/safety.go +++ b/server/safety.go @@ -25,8 +25,17 @@ var metadataIP = net.ParseIP("169.254.169.254") // Loopback, private, link-local and cloud metadata are rejected unless // allowPrivate is set. Metadata addresses stay blocked either way. // Every resolved address is checked so a later DNS answer cannot rebind -// the dial onto a forbidden IP; the caller dials only the returned IP. +// the dial onto a forbidden IP. targetOK returns the first allowed address; +// resolveTargets returns every allowed address in resolver order. func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) (net.IP, error) { + ips, err := resolveTargets(ctx, resolver, host, allowPrivate, extra) + if err != nil { + return nil, err + } + return ips[0], nil +} + +func resolveTargets(ctx context.Context, resolver resolver, host string, allowPrivate bool, extra []*net.IPNet) ([]net.IP, error) { host = strings.TrimSpace(host) host = strings.Trim(host, "[]") if host == "" { @@ -39,7 +48,7 @@ func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate if !ipAllowed(ip, allowPrivate, extra) { return nil, fmt.Errorf("%w: %s", errForbiddenTarget, ip.String()) } - return ip, nil + return []net.IP{ip}, nil } if resolver == nil { resolver = net.DefaultResolver @@ -65,7 +74,7 @@ func targetOK(ctx context.Context, resolver resolver, host string, allowPrivate if len(allowed) != len(addrs) { return nil, fmt.Errorf("%w: %s resolved to a mix of public and blocked addresses", errForbiddenTarget, host) } - return allowed[0], nil + return allowed, nil } func ipAllowed(ip net.IP, allowPrivate bool, extra []*net.IPNet) bool { From fa38806250cf4bee0fba36cdf1e3dd45c186fc91 Mon Sep 17 00:00:00 2001 From: YanJiu <1+yanjiu@noreply.git.yanjiu.ltd> Date: Fri, 20 Nov 2026 19:02:26 +0800 Subject: [PATCH 12/12] =?UTF-8?q?=E5=8F=91=E5=B8=83=E7=BD=91=E7=BB=9C?= =?UTF-8?q?=E8=B4=A8=E9=87=8F=E6=8E=A2=E6=B5=8B=201.1.2=EF=BC=9A=E4=BF=9D?= =?UTF-8?q?=E7=95=99=20Windows=20=E5=90=AF=E5=8A=A8=E8=84=9A=E6=9C=AC?= =?UTF-8?q?=E7=9A=84=20CRLF=20=E6=8D=A2=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 署名:言炙 --- server/packaging/start.bat | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/server/packaging/start.bat b/server/packaging/start.bat index 9ca6a2e..e464cf8 100644 --- a/server/packaging/start.bat +++ b/server/packaging/start.bat @@ -1,8 +1,8 @@ -@echo off -chcp 65001 >nul -cd /d "%~dp0" -echo 正在启动网络质量探测节点。端口和口令请改同目录下的 .env -netquality-reflector.exe -echo. -echo 程序已退出。如果上面有报错,请检查 .env 后重新双击本文件。 -pause +@echo off +chcp 65001 >nul +cd /d "%~dp0" +echo 正在启动网络质量探测节点。端口和口令请改同目录下的 .env +netquality-reflector.exe +echo. +echo 程序已退出。如果上面有报错,请检查 .env 后重新双击本文件。 +pause