Windows 0.3.0 clean next-generation source delta; no private history or other platform changes
This commit is contained in:
@@ -105,30 +105,34 @@ internal sealed class MetricCard : CardPanel
|
||||
var s = DeviceDpi / 96f;
|
||||
int S(int n) => (int)Math.Round(n * s);
|
||||
var g = e.Graphics;
|
||||
DashboardDrawing.Icon(g, Glyph, new(S(10), S(18), S(22), S(22)), Glyph == DashboardIcon.Download ? Brand.Cyan : Brand.RoyalBlue);
|
||||
var x = S(49); var right = Width - S(12); var available = right - x;
|
||||
using var headingFont = Brand.Font(9);
|
||||
using var unitFont = Brand.Font(9);
|
||||
using var hintFont = Brand.Font(7.8f);
|
||||
var narrow = Width < S(180);
|
||||
var shortCard = Height < S(75);
|
||||
if (!narrow) DashboardDrawing.Icon(g, Glyph, new(S(10), S(18), S(22), S(22)), Glyph == DashboardIcon.Download ? Brand.Cyan : Brand.RoyalBlue);
|
||||
var x = S(narrow ? 8 : 49); var right = Width - S(8); var available = Math.Max(1, right - x);
|
||||
using var headingFont = Brand.Font(shortCard || narrow ? 8 : 9);
|
||||
using var unitFont = Brand.Font(shortCard || narrow ? 8 : 9);
|
||||
using var hintFont = Brand.Font(7.2f);
|
||||
var paintFlags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping;
|
||||
TextRenderer.DrawText(g, Heading, headingFont, new Rectangle(x, S(10), available, S(23)), Brand.Text, paintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
|
||||
var headingHeight = Math.Min(S(22), Math.Max(S(14), Height / 3));
|
||||
TextRenderer.DrawText(g, Heading, headingFont, new Rectangle(x, 0, available, headingHeight), Brand.Text, paintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
|
||||
var flags = TextFormatFlags.NoPadding | TextFormatFlags.SingleLine | paintFlags;
|
||||
var unitWidth = TextRenderer.MeasureText(g, UnitText, unitFont, Size.Empty, flags).Width;
|
||||
var size = 22f;
|
||||
var size = shortCard ? 17f : 22f;
|
||||
Font valueFont;
|
||||
while (true)
|
||||
{
|
||||
valueFont = Brand.Font(size, FontStyle.Bold);
|
||||
if (TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width + unitWidth + S(5) <= available || size <= 13) break;
|
||||
if (TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width + unitWidth + S(5) <= available || size <= 10) break;
|
||||
valueFont.Dispose(); size--;
|
||||
}
|
||||
using (valueFont)
|
||||
{
|
||||
var valueWidth = TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width;
|
||||
TextRenderer.DrawText(g, ValueText, valueFont, new Rectangle(x, S(31), available - unitWidth - S(4), S(32)), Brand.Navy, flags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
|
||||
TextRenderer.DrawText(g, UnitText, unitFont, new Rectangle(x + valueWidth + S(4), S(40), unitWidth, S(23)), Brand.Muted, flags | TextFormatFlags.VerticalCenter);
|
||||
var valueHeight = Math.Max(1, Height - headingHeight - (shortCard ? 0 : S(18)));
|
||||
TextRenderer.DrawText(g, ValueText, valueFont, new Rectangle(x, headingHeight, Math.Max(1, available - unitWidth - S(4)), valueHeight), Brand.Navy, flags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
|
||||
TextRenderer.DrawText(g, UnitText, unitFont, new Rectangle(x + Math.Min(valueWidth, available - unitWidth - S(4)) + S(4), headingHeight, unitWidth, valueHeight), Brand.Muted, flags | TextFormatFlags.VerticalCenter);
|
||||
}
|
||||
TextRenderer.DrawText(g, Hint, hintFont, new Rectangle(x, S(64), available, S(17)), Brand.Muted, paintFlags | TextFormatFlags.EndEllipsis);
|
||||
if (!shortCard) TextRenderer.DrawText(g, Hint, hintFont, new Rectangle(x, Height - S(17), available, S(17)), Brand.Muted, paintFlags | TextFormatFlags.EndEllipsis);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,39 +49,40 @@ internal sealed partial class MainForm
|
||||
var message = Message.Create(target.Handle, 0x20a, (IntPtr)packedDelta, (IntPtr)packedPoint);
|
||||
return Application.FilterMessage(ref message);
|
||||
}
|
||||
checks["compact_view_has_real_scroll_range"] = _dashboardScrollBar.Visible && Limit() > 0;
|
||||
checks["compact_view_is_single_fitted_page"] = !_dashboardScrollBar.Visible && Limit() == 0
|
||||
&& _dashboardBody.Location == Point.Empty && _dashboardBody.Size == _dashboardView.ClientSize;
|
||||
foreach (var (name, control) in new (string, Control)[]
|
||||
{
|
||||
("card", _trafficCard), ("nested_metric", _uploadMetric), ("chart", _trafficChart),
|
||||
("nested_label", _uploadLegend), ("closed_history_combo", _historyRangeCombo),
|
||||
("nested_label", _uploadLegend), ("closed_speed_combo", _historyRangeCombo),
|
||||
("closed_node_combo", _connectionModeCombo), ("closed_mode_combo", _routeCombo),
|
||||
("button", _connectButton)
|
||||
})
|
||||
{
|
||||
_dashboardScrollBar.Value = 0;
|
||||
var oldSelection = control is ComboBox combo ? combo.SelectedIndex : -1;
|
||||
checks["wheel_scrolls_over_" + name] = Wheel(control, -120) && _dashboardScrollBar.Value > 0
|
||||
checks["wheel_does_not_scroll_" + name] = !Wheel(control, -120) && _dashboardScrollBar.Value == 0
|
||||
&& (control is not ComboBox selector || selector.SelectedIndex == oldSelection);
|
||||
}
|
||||
_dashboardScrollBar.Value = 0;
|
||||
var halfHandled = Wheel(_trafficChart, -60);
|
||||
var firstHalf = _dashboardScrollBar.Value;
|
||||
checks["high_resolution_wheel_accumulates_half_notches"] = halfHandled && firstHalf == 0
|
||||
&& Wheel(_trafficChart, -60) && _dashboardScrollBar.Value > 0;
|
||||
checks["high_resolution_wheel_does_not_shift_fitted_page"] = !halfHandled && firstHalf == 0
|
||||
&& !Wheel(_trafficChart, -60) && _dashboardScrollBar.Value == 0;
|
||||
_dashboardScrollBar.Value = Limit();
|
||||
checks["wheel_bottom_clamped"] = Wheel(_dailyChart, -240) && _dashboardScrollBar.Value == Limit();
|
||||
checks["wheel_up_returns_from_bottom"] = Wheel(_dailyChart, 120) && _dashboardScrollBar.Value < Limit();
|
||||
checks["wheel_down_keeps_page_origin"] = !Wheel(_trafficChart, -240) && _dashboardScrollBar.Value == 0;
|
||||
checks["wheel_up_keeps_page_origin"] = !Wheel(_trafficChart, 120) && _dashboardScrollBar.Value == 0;
|
||||
_dashboardScrollBar.Value = Math.Min(137, Limit());
|
||||
var previous = _dashboardScrollBar.Value;
|
||||
UpdateProfile(profile, preserveSelections: true);
|
||||
DisplayTraffic(1234, 5678, "隔离刷新");
|
||||
LayoutDashboard();
|
||||
checks["profile_and_metric_refresh_preserve_scroll"] = _dashboardScrollBar.Value == previous && _dashboardBody.Top == -previous;
|
||||
checks["profile_and_metric_refresh_keep_page_origin"] = _dashboardScrollBar.Value == 0 && _dashboardBody.Top == 0;
|
||||
ClientSize = new Size(ClientSize.Width, ClientSize.Height + ScaleLogical(20));
|
||||
LayoutDashboard();
|
||||
checks["resize_preserves_valid_scroll"] = _dashboardScrollBar.Value == Math.Min(previous, Limit());
|
||||
checks["resize_remains_fitted_without_scroll"] = !_dashboardScrollBar.Visible && _dashboardScrollBar.Value == 0;
|
||||
_dashboardScrollBar.Value = Limit();
|
||||
checks["footer_reachable_without_horizontal_scroll"] = !_dashboardView.HorizontalScroll.Visible
|
||||
checks["footer_visible_without_any_scroll"] = !_dashboardView.HorizontalScroll.Visible && !_dashboardScrollBar.Visible
|
||||
&& _footer.RectangleToScreen(_footer.ClientRectangle).Bottom <= _dashboardView.RectangleToScreen(_dashboardView.ClientRectangle).Bottom;
|
||||
previous = _dashboardScrollBar.Value;
|
||||
checks["header_pointer_does_not_scroll_dashboard"] = !Wheel(_trafficChart, -120, _brandHeader.PointToScreen(new Point(20, 20)))
|
||||
|
||||
+36
-26
@@ -4,7 +4,7 @@ internal readonly record struct DashboardGeometry(
|
||||
Rectangle WelcomeLabel, Rectangle AccountLabel, Rectangle IdentityBadge,
|
||||
Rectangle LogoutButton, Rectangle StatusCard, Rectangle NodeCard, Rectangle ModeCard,
|
||||
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle DailyCard, Rectangle Footer,
|
||||
int ContentHeight, bool Compact);
|
||||
int ContentHeight, bool Compact, float VerticalScale);
|
||||
|
||||
// Logical pixels converted once, independent of WinForms autoscaling.
|
||||
internal static class DashboardLayout
|
||||
@@ -13,41 +13,49 @@ internal static class DashboardLayout
|
||||
{
|
||||
var scale = Math.Max(1f, dpi / 96f);
|
||||
int S(int n) => (int)Math.Round(n * scale);
|
||||
// Tailnet is a subdivision of the existing speed area, not another
|
||||
// dashboard row. Fit the complete canvas even on a small/high-DPI screen.
|
||||
var verticalScale = Math.Min(1f, Math.Max(1, viewport.Height) / (614f * scale));
|
||||
int Y(int n) => Math.Max(1, (int)Math.Floor(n * scale * verticalScale));
|
||||
var margin = S(20);
|
||||
var gap = S(10);
|
||||
var width = Math.Max(S(540), viewport.Width - margin * 2);
|
||||
var gap = Y(10);
|
||||
var columnGap = S(10);
|
||||
var width = Math.Max(1, viewport.Width - margin * 2);
|
||||
var compact = width < S(720);
|
||||
var half = (width - gap) / 2;
|
||||
var welcome = new Rectangle(margin, S(8), width - S(132), S(30));
|
||||
var account = new Rectangle(margin, S(38), Math.Min(S(275), width - S(230)), S(24));
|
||||
var identity = new Rectangle(account.Right + S(10), S(38), S(92), S(23));
|
||||
var logout = new Rectangle(margin + width - S(104), S(16), S(104), S(34));
|
||||
var status = new Rectangle(margin, S(72), width, S(76));
|
||||
var node = new Rectangle(margin, status.Bottom + gap, compact ? width : half, S(72));
|
||||
var mode = compact
|
||||
? new Rectangle(margin, node.Bottom + gap, width, node.Height)
|
||||
: new Rectangle(node.Right + gap, node.Top, width - half - gap, node.Height);
|
||||
var traffic = new Rectangle(margin, mode.Bottom + gap, compact ? width : half, S(276));
|
||||
var tailnet = showTailnet ? new Rectangle(traffic.Left, traffic.Bottom + gap, traffic.Width, traffic.Height) : Rectangle.Empty;
|
||||
var daily = compact
|
||||
? new Rectangle(margin, (showTailnet ? tailnet.Bottom : traffic.Bottom) + gap, width, traffic.Height)
|
||||
: new Rectangle(traffic.Right + gap, traffic.Top, width - half - gap,
|
||||
showTailnet ? tailnet.Bottom - traffic.Top : traffic.Height);
|
||||
Rectangle Metric(Rectangle parent, int column) => new(S(14) + column * ((parent.Width - S(28)) / 2), S(43), (parent.Width - S(28)) / 2 - S(2), S(82));
|
||||
var half = (width - columnGap) / 2;
|
||||
var welcome = new Rectangle(margin, Y(8), width - S(132), Y(30));
|
||||
var account = new Rectangle(margin, Y(38), Math.Min(S(275), width - S(230)), Y(24));
|
||||
var identity = new Rectangle(account.Right + S(10), Y(38), S(92), Y(23));
|
||||
var logout = new Rectangle(margin + width - S(104), Y(16), S(104), Y(34));
|
||||
var status = new Rectangle(margin, Y(72), width, Y(76));
|
||||
var node = new Rectangle(margin, status.Bottom + gap, half, Y(72));
|
||||
var mode = new Rectangle(node.Right + columnGap, node.Top, width - half - columnGap, node.Height);
|
||||
var analyticsTop = mode.Bottom + gap;
|
||||
var analyticsHeight = Y(276);
|
||||
var leftHeight = showTailnet ? (analyticsHeight - gap) / 2 : analyticsHeight;
|
||||
var traffic = new Rectangle(margin, analyticsTop, half, leftHeight);
|
||||
var tailnet = showTailnet ? new Rectangle(traffic.Left, traffic.Bottom + gap, half, analyticsHeight - leftHeight - gap) : Rectangle.Empty;
|
||||
var daily = new Rectangle(traffic.Right + columnGap, analyticsTop, width - half - columnGap, analyticsHeight);
|
||||
Rectangle Metric(Rectangle parent, int column, bool speed) => new(
|
||||
S(10) + column * ((parent.Width - S(20)) / 2),
|
||||
speed ? Math.Max(Y(38), (parent.Height - Y(82)) / 2) : Y(40),
|
||||
(parent.Width - S(20)) / 2 - S(1),
|
||||
speed ? Math.Min(Y(82), parent.Height - Y(44)) : Y(82));
|
||||
// Relative to their matching chart card: totals together; speeds together.
|
||||
Rectangle[] metrics = [Metric(daily, 0), Metric(traffic, 0), Metric(traffic, 1), Metric(daily, 1)];
|
||||
var footer = new Rectangle(margin, daily.Bottom + gap, width, S(76));
|
||||
Rectangle[] metrics = [Metric(daily, 0, false), Metric(traffic, 0, true), Metric(traffic, 1, true), Metric(daily, 1, false)];
|
||||
var footer = new Rectangle(margin, daily.Bottom + gap, width, Y(76));
|
||||
return new(welcome, account, identity, logout, status, node, mode, metrics, traffic,
|
||||
tailnet, daily, footer, footer.Bottom + S(12), compact);
|
||||
tailnet, daily, footer, Math.Min(viewport.Height, footer.Bottom + Y(12)), compact, verticalScale);
|
||||
}
|
||||
|
||||
internal static bool SelfTest()
|
||||
{
|
||||
foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288 })
|
||||
foreach (var width in new[] { 600, 620, 739, 760, 780, 900, 1100, 1600 })
|
||||
foreach (var height in new[] { 350, 418, 560, 720 })
|
||||
foreach (var showTailnet in new[] { false, true })
|
||||
{
|
||||
var viewport = new Size(width * dpi / 96, 560 * dpi / 96);
|
||||
var viewport = new Size(width * dpi / 96, height * dpi / 96);
|
||||
var p = Calculate(viewport, dpi, showTailnet);
|
||||
Rectangle[] cards = showTailnet
|
||||
? [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.TailnetTrafficCard, p.DailyCard, p.Footer]
|
||||
@@ -61,9 +69,11 @@ internal static class DashboardLayout
|
||||
for (var i = 0; i < p.Metrics.Length; i++)
|
||||
if (p.Metrics[i].Right > (i == 0 || i == 3 ? p.DailyCard.Width : p.TrafficCard.Width)) return false;
|
||||
if (!showTailnet && p.TailnetTrafficCard != Rectangle.Empty) return false;
|
||||
if (p.ContentHeight > viewport.Height || p.Footer.Bottom > viewport.Height) return false;
|
||||
var baseline = Calculate(viewport, dpi, false);
|
||||
if (p.DailyCard != baseline.DailyCard || p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight) return false;
|
||||
if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom
|
||||
|| p.Compact && p.DailyCard.Top <= p.TailnetTrafficCard.Bottom
|
||||
|| !p.Compact && (p.DailyCard.Top != p.TrafficCard.Top || p.DailyCard.Bottom != p.TailnetTrafficCard.Bottom))) return false;
|
||||
|| p.DailyCard.Top != p.TrafficCard.Top || p.DailyCard.Bottom != p.TailnetTrafficCard.Bottom)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -6,83 +6,71 @@ internal sealed partial class MainForm
|
||||
internal Dictionary<string, bool> CheckTailnetTrafficUi()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
int TailnetPoints()
|
||||
{
|
||||
var queue = typeof(TrafficChart).GetField("_points", System.Reflection.BindingFlags.Instance
|
||||
| System.Reflection.BindingFlags.NonPublic)!.GetValue(_tailnetTrafficChart)!;
|
||||
return (int)queue.GetType().GetProperty("Count")!.GetValue(queue)!;
|
||||
}
|
||||
var originalSize = ClientSize;
|
||||
SetTailnetTrafficVisibility(false);
|
||||
ClientSize = new Size(ScaleLogical(960), ScaleLogical(720));
|
||||
LayoutDashboard();
|
||||
var baseTraffic = _trafficCard.Bounds;
|
||||
var baseDaily = _dailyCard.Bounds;
|
||||
var baseFooter = _footer.Bounds;
|
||||
var baseHeight = _dashboardBody.Height;
|
||||
checks["tailnet_absent_has_original_two_card_layout"] = !_tailnetTrafficCard.Visible
|
||||
&& baseTraffic.Top == baseDaily.Top && baseTraffic.Bottom == baseDaily.Bottom;
|
||||
_dashboardScrollBar.Value = Math.Min(35, Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1));
|
||||
var previous = _dashboardScrollBar.Value;
|
||||
foreach (var size in new[] { new Size(960, 720), new Size(620, 550), new Size(900, 640) })
|
||||
{
|
||||
ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height));
|
||||
SetTailnetTrafficVisibility(false); LayoutDashboard();
|
||||
var baseline = (_trafficCard.Bounds, _dailyCard.Bounds, _footer.Bounds, _dashboardBody.Size);
|
||||
checks[$"no_tailnet_single_left_{size.Width}"] = !_tailnetTrafficCard.Visible
|
||||
&& _trafficCard.Top == _dailyCard.Top && _trafficCard.Bottom == _dailyCard.Bottom;
|
||||
SetTailnetTrafficVisibility(true);
|
||||
checks[$"tailnet_only_subdivides_left_{size.Width}"] = _tailnetTrafficCard.Left == _trafficCard.Left
|
||||
&& _tailnetTrafficCard.Width == _trafficCard.Width && _tailnetTrafficCard.Top > _trafficCard.Bottom
|
||||
&& _dailyCard.Top == _trafficCard.Top && _dailyCard.Bottom == _tailnetTrafficCard.Bottom;
|
||||
checks[$"tailnet_never_increases_page_{size.Width}"] = _dailyCard.Bounds == baseline.Item2
|
||||
&& _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4
|
||||
&& !_dashboardScrollBar.Visible && _dashboardBody.Location == Point.Empty;
|
||||
checks[$"all_card_controls_fit_{size.Width}"] = DashboardControlsFit();
|
||||
SetTailnetTrafficVisibility(false);
|
||||
checks[$"tailnet_hide_restores_geometry_{size.Width}"] = _trafficCard.Bounds == baseline.Item1
|
||||
&& _dailyCard.Bounds == baseline.Item2 && _footer.Bounds == baseline.Item3;
|
||||
}
|
||||
SetTailnetTrafficVisibility(true);
|
||||
checks["tailnet_wide_left_cards_stack"] = _tailnetTrafficCard.Left == _trafficCard.Left
|
||||
&& _tailnetTrafficCard.Width == _trafficCard.Width && _tailnetTrafficCard.Top > _trafficCard.Bottom;
|
||||
checks["tailnet_wide_right_history_spans_two_rows"] = _dailyCard.Top == _trafficCard.Top
|
||||
&& _dailyCard.Bottom == _tailnetTrafficCard.Bottom && _dailyCard.Left > _trafficCard.Right;
|
||||
checks["tailnet_show_preserves_scroll"] = _dashboardScrollBar.Value == previous;
|
||||
checks["tailnet_expanded_history_chart_fills_card"] = _dailyChart.Height > _trafficChart.Height
|
||||
&& _dailyChart.Bottom < _dailyUploadLegend.Top && _historyStatus.Bottom <= _dailyCard.Height;
|
||||
var originalProxyValue = _uploadMetric.ValueText;
|
||||
var originalProxyLegend = _uploadLegend.Text;
|
||||
var originalSessionUp = _sessionUp;
|
||||
var originalSessionDown = _sessionDown;
|
||||
var proxyValue = _uploadMetric.ValueText;
|
||||
var session = (_sessionUp, _sessionDown);
|
||||
var curveCount = _trafficChart.PointCount;
|
||||
DisplayTailnetTraffic(12345, 67890, "独立 UI 样本");
|
||||
checks["tailnet_view_never_adds_sample_to_session_totals_again"] = _sessionUp == originalSessionUp
|
||||
&& _sessionDown == originalSessionDown;
|
||||
checks["tailnet_never_double_counts_session_or_curve"] = session == (_sessionUp, _sessionDown)
|
||||
&& _trafficChart.PointCount == curveCount;
|
||||
checks["tailnet_values_are_independent_controls"] = _tailnetUploadMetric.ValueText == "12.06"
|
||||
&& _tailnetDownloadMetric.ValueText == "66.3" && _tailnetUploadMetric.Parent == _tailnetTrafficCard
|
||||
&& _tailnetDownloadMetric.Parent == _tailnetTrafficCard && _tailnetTrafficChart.Parent == _tailnetTrafficCard
|
||||
&& _uploadMetric.ValueText == originalProxyValue && _uploadLegend.Text == originalProxyLegend;
|
||||
checks["tailnet_valid_sample_appends_one_curve_point"] = TailnetPoints() == 1;
|
||||
&& _tailnetDownloadMetric.ValueText == "66.3" && _uploadMetric.ValueText == proxyValue;
|
||||
checks["tailnet_scope_and_already_accounted_are_explicit"] = _tailnetSampleLabel.Text.StartsWith("仅纵横家链路 · ")
|
||||
&& _tailnetUploadMetric.Hint == "已计入代理总流量" && _tailnetDownloadMetric.Hint == "已计入代理总流量";
|
||||
DisplayTailnetTraffic(null, double.NaN, "独立采样不可用");
|
||||
checks["tailnet_missing_samples_not_total_or_fake_zero"] = _tailnetUploadMetric.ValueText == "—"
|
||||
&& _tailnetDownloadMetric.ValueText == "—" && _tailnetUploadLegend.Text == "● 上传 —" && TailnetPoints() == 0;
|
||||
ResetTailnetTraffic();
|
||||
checks["tailnet_reset_clears_metric_and_sampling"] = _tailnetUploadMetric.ValueText == "—"
|
||||
&& _tailnetDownloadMetric.ValueText == "—" && _tailnetSampleLabel.Text == "仅纵横家链路 · 等待 Tailscale 流量采样" && TailnetPoints() == 0;
|
||||
SetTailnetTrafficVisibility(false);
|
||||
checks["tailnet_hide_restores_exact_original_geometry_without_gap"] = _trafficCard.Bounds == baseTraffic
|
||||
&& _dailyCard.Bounds == baseDaily && _footer.Bounds == baseFooter && _dashboardBody.Height == baseHeight;
|
||||
SetTailnetTrafficVisibility(true);
|
||||
checks["tailnet_resurface_has_no_previous_connection_numbers"] = _tailnetUploadMetric.ValueText == "—"
|
||||
&& _tailnetDownloadMetric.ValueText == "—" && TailnetPoints() == 0;
|
||||
Size = MinimumSize;
|
||||
PerformLayout();
|
||||
LayoutDashboard();
|
||||
Application.DoEvents();
|
||||
checks["tailnet_compact_orders_realtime_tailnet_history"] = _trafficCard.Left == _tailnetTrafficCard.Left
|
||||
&& _tailnetTrafficCard.Left == _dailyCard.Left && _tailnetTrafficCard.Top > _trafficCard.Bottom
|
||||
&& _dailyCard.Top > _tailnetTrafficCard.Bottom;
|
||||
checks["tailnet_all_controls_fit_transparent_cards"] = DashboardControlsFit() && CardPanel.SurfaceAlpha == 128;
|
||||
var limit = Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1);
|
||||
_dashboardScrollBar.Value = limit;
|
||||
LayoutDashboard();
|
||||
checks["tailnet_compact_footer_remains_reachable"] = !_dashboardView.HorizontalScroll.Visible
|
||||
&& _footer.RectangleToScreen(_footer.ClientRectangle).Bottom <= _dashboardView.RectangleToScreen(_dashboardView.ClientRectangle).Bottom;
|
||||
&& _tailnetUploadMetric.Hint == "已计入代理总流量";
|
||||
DisplayTailnetTraffic(null, double.NaN, "采样不可用");
|
||||
checks["tailnet_missing_samples_not_fake_zero"] = _tailnetUploadMetric.ValueText == "—"
|
||||
&& _tailnetDownloadMetric.ValueText == "—";
|
||||
DisplayTailnetTraffic(1, 2, "独立 UI 样本");
|
||||
SetTailnetTrafficVisibility(false);
|
||||
checks["tailnet_hide_clamps_scroll_and_clears_data"] = _dashboardScrollBar.Value <= Math.Max(0,
|
||||
_dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1)
|
||||
&& _tailnetUploadMetric.ValueText == "—" && _tailnetDownloadMetric.ValueText == "—";
|
||||
SetTailnetTrafficVisibility(false); SetTailnetTrafficVisibility(true);
|
||||
checks["tailnet_hide_clears_previous_numbers"] = _tailnetUploadMetric.ValueText == "—"
|
||||
&& _tailnetDownloadMetric.ValueText == "—";
|
||||
checks["only_one_speed_curve_on_right"] = !_trafficCard.Controls.OfType<TrafficChart>().Any()
|
||||
&& !_tailnetTrafficCard.Controls.OfType<TrafficChart>().Any()
|
||||
&& _dailyCard.Controls.OfType<TrafficChart>().Single() == _trafficChart
|
||||
&& _dailyChart.Parent is null && !_dailyChart.Visible;
|
||||
UpdateConnectedTransportPresentation(true);
|
||||
checks["actual_transport_presentation_enables_tailnet_card"] = _currentNodeUsesTailnet && _tailnetTrafficVisible;
|
||||
checks["actual_tailnet_transport_shows_section"] = _currentNodeUsesTailnet && _tailnetTrafficVisible;
|
||||
UpdateConnectedTransportPresentation(false);
|
||||
checks["public_transport_presentation_hides_tailnet_card"] = !_currentNodeUsesTailnet && !_tailnetTrafficVisible;
|
||||
ClientSize = originalSize;
|
||||
LayoutDashboard();
|
||||
checks["tailnet_geometry_112_viewport_dpi_cases"] = DashboardLayout.SelfTest();
|
||||
checks["public_transport_hides_section"] = !_currentNodeUsesTailnet && !_tailnetTrafficVisible;
|
||||
using var curve = new TrafficChart();
|
||||
var end = DateTimeOffset.Now;
|
||||
for (var i = 0; i <= 720; i++) curve.Add(i, i * 2, end.AddSeconds((i - 720) * 5));
|
||||
checks["speed_history_retains_actual_one_hour"] = curve.PointCount == 721;
|
||||
curve.SetPeriodMinutes(1);
|
||||
checks["one_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 13 && curve.PointCount == 721;
|
||||
curve.SetPeriodMinutes(5);
|
||||
checks["five_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 61;
|
||||
curve.SetPeriodMinutes(15);
|
||||
checks["fifteen_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 181;
|
||||
curve.SetPeriodMinutes(60);
|
||||
checks["hour_filter_preserves_available_samples"] = curve.VisiblePointCount == 721;
|
||||
curve.Add(1, 2, end.AddSeconds(5));
|
||||
checks["old_samples_expire_at_one_hour"] = curve.PointCount == 721;
|
||||
curve.Reset();
|
||||
checks["speed_history_reset_has_no_fabricated_samples"] = curve.PointCount == 0 && curve.VisiblePointCount == 0;
|
||||
ClientSize = originalSize; LayoutDashboard();
|
||||
checks["fitted_geometry_448_viewport_dpi_cases"] = DashboardLayout.SelfTest();
|
||||
checks["card_surface_remains_half_transparent"] = CardPanel.SurfaceAlpha == 128;
|
||||
return checks;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,35 +8,51 @@ namespace UCVL.VPNPlus;
|
||||
internal static class KnownTailnetEndpoints
|
||||
{
|
||||
internal static TailnetEndpoint? Resolve(ConfigResponse response, bool allowCompatibilityMapping)
|
||||
=> Resolve(response, allowCompatibilityMapping, out _);
|
||||
|
||||
internal static TailnetEndpoint? Resolve(ConfigResponse response, bool allowCompatibilityMapping, out string reason)
|
||||
{
|
||||
// This switch permits legacy endpoint mapping, not an employee or
|
||||
// tailnet-membership policy. The API still supplies node authorization.
|
||||
// An explicit field (including null/invalid metadata) ALWAYS wins. Never
|
||||
// turn server rejection or an unknown contract into a compiled fallback.
|
||||
if (!allowCompatibilityMapping || response.HasTailscaleEndpoint || response.ConfigContract != 2
|
||||
|| response.ConnectionScope is not ("" or "public")
|
||||
|| response.RouteMode is not ("smart" or "global")) return null;
|
||||
reason = "compatibility_disabled";
|
||||
if (!allowCompatibilityMapping) return null;
|
||||
reason = "explicit_endpoint_present";
|
||||
if (response.HasTailscaleEndpoint) return null;
|
||||
reason = "config_contract_unsupported";
|
||||
if (response.ConfigContract != 2) return null;
|
||||
reason = "scope_unsupported";
|
||||
if (response.ConnectionScope is not ("" or "public")) return null;
|
||||
reason = "route_mode_unsupported";
|
||||
if (response.RouteMode is not ("smart" or "global")) return null;
|
||||
var mapping = response.Node.Slug switch
|
||||
{
|
||||
"aliyun-tokyo-002" => (Host: "vpn002.example.invalid", PublicPort: 11082, Address: "100.64.0.2", Port: 10803),
|
||||
"aliyun-siliconvalley-003" => (Host: "vpn003.example.invalid", PublicPort: 11083, Address: "100.64.0.3", Port: 11083),
|
||||
_ => default
|
||||
};
|
||||
reason = "known_node_unmapped";
|
||||
if (mapping.Host is null) return null;
|
||||
try
|
||||
{
|
||||
// Check the API's original node endpoint BEFORE the public-gateway
|
||||
// rewrite. A reused slug/name must not send credentials to an old IP.
|
||||
var root = JsonNode.Parse(response.Config.GetRawText())!.AsObject();
|
||||
reason = "config_scope_or_marker_invalid";
|
||||
if (root.ContainsKey(TailnetTransport.Marker) || PrivateAuxiliaryRuntime.IsPrivate(root)) return null;
|
||||
var proxy = TailnetTransport.Proxy(root);
|
||||
reason = "proxy_identity_unsupported";
|
||||
if (proxy is null) return null;
|
||||
var server = proxy?["settings"]?["vnext"]?[0];
|
||||
reason = "known_original_ingress_mismatch";
|
||||
if (server?["address"]?.GetValue<string>() != mapping.Host
|
||||
|| server?["port"]?.GetValue<int>() != mapping.PublicPort) return null;
|
||||
reason = "known_endpoint";
|
||||
return new TailnetEndpoint { Contract = 1, NodeSlug = response.Node.Slug,
|
||||
Address = mapping.Address, Port = mapping.Port };
|
||||
}
|
||||
catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException)
|
||||
{ return null; }
|
||||
{ reason = "config_invalid"; return null; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Optional management APIs must neither interrupt a working data plane nor gate
|
||||
// one another. The owner supplies a bounded token and a session/core epoch check;
|
||||
// this class never stores credentials, changes routes, or starts/stops a core.
|
||||
internal sealed class LearningSyncCoordinator
|
||||
{
|
||||
private enum Endpoint { Upload, Rules, Ack }
|
||||
private sealed class Gate
|
||||
{
|
||||
internal int Failures;
|
||||
internal long NotBefore;
|
||||
}
|
||||
|
||||
private readonly Func<long> _clock;
|
||||
private readonly object _sync = new();
|
||||
private readonly Gate[] _gates = [new(), new(), new()];
|
||||
private long _generation;
|
||||
private long _lastNow;
|
||||
private bool _hasNow;
|
||||
private int _running;
|
||||
private string? _pendingAck;
|
||||
|
||||
internal LearningSyncCoordinator(Func<long>? monotonicClock = null)
|
||||
=> _clock = monotonicClock ?? (() => Environment.TickCount64);
|
||||
|
||||
// Call on login/logout/account change. In-flight old-session results cannot
|
||||
// reintroduce a pending acknowledgement or an old session's retry penalty.
|
||||
internal void Reset()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
_generation++;
|
||||
_pendingAck = null;
|
||||
foreach (var gate in _gates) { gate.Failures = 0; gate.NotBefore = 0; }
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task RunAsync(
|
||||
Func<bool> isCurrent,
|
||||
Func<CancellationToken, Task> upload,
|
||||
Func<CancellationToken, Task<RoutingManifest>> fetchRules,
|
||||
Func<RoutingManifest, CancellationToken, Task<bool>> applyRules,
|
||||
Func<string, CancellationToken, Task> acknowledge,
|
||||
CancellationToken cancellationToken,
|
||||
Action<string>? diagnostic = null)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
if (Interlocked.CompareExchange(ref _running, 1, 0) != 0) return;
|
||||
var generation = Volatile.Read(ref _generation);
|
||||
bool Current()
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
return generation == Volatile.Read(ref _generation) && isCurrent();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (!Current()) return;
|
||||
await AttemptAsync(Endpoint.Upload, upload);
|
||||
if (!Current()) return;
|
||||
|
||||
await AttemptAsync(Endpoint.Rules, async token =>
|
||||
{
|
||||
var manifest = await fetchRules(token);
|
||||
if (!Current()) return;
|
||||
// The callback must also guard its own asynchronous mutation.
|
||||
// A rejected/stale apply is never acknowledged as installed.
|
||||
if (!await applyRules(manifest, token) || !Current()) return;
|
||||
lock (_sync)
|
||||
if (generation == _generation && !string.IsNullOrWhiteSpace(manifest.Revision))
|
||||
_pendingAck = manifest.Revision;
|
||||
});
|
||||
if (!Current()) return;
|
||||
|
||||
string? revision;
|
||||
lock (_sync) revision = _pendingAck;
|
||||
if (revision is not null && await AttemptAsync(Endpoint.Ack, token => acknowledge(revision, token)))
|
||||
{
|
||||
lock (_sync)
|
||||
if (generation == _generation && _pendingAck == revision) _pendingAck = null;
|
||||
}
|
||||
}
|
||||
finally { Volatile.Write(ref _running, 0); }
|
||||
|
||||
async Task<bool> AttemptAsync(Endpoint endpoint, Func<CancellationToken, Task> operation)
|
||||
{
|
||||
if (!Current()) return false;
|
||||
lock (_sync)
|
||||
if (generation != _generation || Now() < _gates[(int)endpoint].NotBefore) return false;
|
||||
try
|
||||
{
|
||||
await operation(cancellationToken);
|
||||
if (!Current()) return false;
|
||||
var recovered = false;
|
||||
lock (_sync)
|
||||
{
|
||||
if (generation != _generation) return false;
|
||||
var gate = _gates[(int)endpoint];
|
||||
recovered = gate.Failures != 0;
|
||||
gate.Failures = 0; gate.NotBefore = 0;
|
||||
}
|
||||
if (recovered) Report(endpoint, "recovered");
|
||||
return true;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
|
||||
catch (ApiException error) when (error.StatusCode is 401 or 403)
|
||||
{
|
||||
// Never convert authentication loss to an optional-API fallback.
|
||||
// A delayed response from a previous account must not log out its successor.
|
||||
if (!Current()) return false;
|
||||
throw;
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
if (!Current()) return false;
|
||||
var unsupported = error is ApiException { StatusCode: 404 or 405 };
|
||||
lock (_sync)
|
||||
{
|
||||
if (generation != _generation) return false;
|
||||
var gate = _gates[(int)endpoint];
|
||||
gate.Failures = Math.Min(gate.Failures + 1, 16);
|
||||
// Unsupported: 2, 4, 8, 15 min. Transient: 1, 2, 4, 5 min.
|
||||
var first = unsupported ? 120_000L : 60_000L;
|
||||
var maximum = unsupported ? 900_000L : 300_000L;
|
||||
var delay = Math.Min(first * (1L << Math.Min(gate.Failures - 1, 4)), maximum);
|
||||
var now = Now();
|
||||
gate.NotBefore = now > long.MaxValue - delay ? long.MaxValue : now + delay;
|
||||
}
|
||||
Report(endpoint, unsupported ? "unsupported.backoff" : "transient.backoff");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void Report(Endpoint endpoint, string outcome)
|
||||
{
|
||||
// Only fixed endpoint/outcome identifiers; never exception text,
|
||||
// manifests, URLs, revisions, tokens, or user-provided content.
|
||||
var name = endpoint switch { Endpoint.Upload => "upload", Endpoint.Rules => "rules", _ => "ack" };
|
||||
try { diagnostic?.Invoke("learning." + name + "." + outcome); }
|
||||
catch { /* Diagnostics cannot break a working learning/data path. */ }
|
||||
}
|
||||
}
|
||||
|
||||
// All reads occur under _sync. A clock regression cannot retry early, and
|
||||
// wall-clock/time-zone changes never affect the default monotonic clock.
|
||||
private long Now()
|
||||
{
|
||||
var value = _clock();
|
||||
if (!_hasNow || value > _lastNow) _lastNow = value;
|
||||
_hasNow = true;
|
||||
return _lastNow;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class LearningSyncCoordinatorSelfTest
|
||||
{
|
||||
internal static async Task<int> RunAsync()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
await AddChecksAsync(checks);
|
||||
var passed = checks.Values.All(value => value);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "learning-sync-coordinator-self-test.json"),
|
||||
JsonSerializer.Serialize(new { kind = "optional_learning_api_resilience", network_modified = false,
|
||||
authenticated_vpn_tested = false, checks, passed }, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 87;
|
||||
}
|
||||
|
||||
internal static async Task AddChecksAsync(Dictionary<string, bool> checks)
|
||||
{
|
||||
var test = new Fixture { UploadError = new ApiException(404, "secret-token-not-for-log") };
|
||||
await test.Run();
|
||||
checks["learning_upload_404_does_not_block_rule_fetch_or_apply"] = test.Uploads == 1 && test.Fetches == 1 && test.Applies == 1;
|
||||
checks["learning_upload_404_does_not_block_ack"] = test.Acks == 1 && test.Acknowledged.SequenceEqual(["revision-1"]);
|
||||
checks["learning_diagnostic_has_only_fixed_endpoint_and_outcome"] = test.Diagnostics.SequenceEqual(["learning.upload.unsupported.backoff"]);
|
||||
await test.Run();
|
||||
checks["learning_one_callback_per_endpoint_per_run"] = test.Uploads == 1 && test.Fetches == 2 && test.Applies == 2 && test.Acks == 2;
|
||||
test.Now = 60_000; await test.Run();
|
||||
checks["learning_unsupported_not_retried_or_logged_each_minute"] = test.Uploads == 1 && test.Diagnostics.Count == 1;
|
||||
test.Now = 120_000; await test.Run();
|
||||
test.Now = 359_999; await test.Run();
|
||||
checks["learning_unsupported_second_backoff_is_four_minutes"] = test.Uploads == 2 && test.Diagnostics.Count == 2;
|
||||
test.Now = 360_000; await test.Run();
|
||||
test.Now = 839_999; await test.Run();
|
||||
checks["learning_unsupported_third_backoff_is_eight_minutes"] = test.Uploads == 3;
|
||||
test.Now = 840_000; await test.Run();
|
||||
test.Now = 1_739_999; await test.Run();
|
||||
checks["learning_unsupported_backoff_caps_at_fifteen_minutes"] = test.Uploads == 4;
|
||||
test.Now = 1_740_000; await test.Run();
|
||||
test.Now = 2_640_000; await test.Run();
|
||||
checks["learning_unsupported_cap_remains_fifteen_minutes"] = test.Uploads == 6;
|
||||
|
||||
test.UploadError = null; test.Now = 3_540_000; await test.Run();
|
||||
checks["learning_endpoint_recovery_is_reported_once"] = test.Diagnostics.Last() == "learning.upload.recovered";
|
||||
var logCount = test.Diagnostics.Count;
|
||||
test.Now++; await test.Run();
|
||||
checks["learning_success_does_not_spam_recovery_logs"] = test.Diagnostics.Count == logCount;
|
||||
test.UploadError = new ApiException(405, "sensitive request details");
|
||||
await test.Run();
|
||||
var attempts = test.Uploads;
|
||||
test.Now += 119_999; await test.Run();
|
||||
checks["learning_recovered_endpoint_restarts_405_at_two_minutes"] = test.Uploads == attempts;
|
||||
test.Now++; await test.Run();
|
||||
checks["learning_405_uses_unsupported_policy"] = test.Uploads == attempts + 1 && test.Diagnostics.Last() == "learning.upload.unsupported.backoff";
|
||||
|
||||
test = new Fixture { FetchError = new ApiException(404, "not available") };
|
||||
await test.Run(); test.Now = 60_000; await test.Run();
|
||||
checks["learning_rules_backoff_does_not_gate_upload"] = test.Uploads == 2 && test.Fetches == 1 && test.Applies == 0 && test.Acks == 0;
|
||||
|
||||
test = new Fixture { AckError = new ApiException(503, "unavailable") };
|
||||
await test.Run();
|
||||
checks["learning_failed_ack_keeps_applied_rules"] = test.Applies == 1 && test.LastApplied == "revision-1" && test.Acks == 1;
|
||||
test.FetchError = new ApiException(404, "not available");
|
||||
await test.Run();
|
||||
checks["learning_ack_gate_is_independent_of_rules_gate"] = test.Fetches == 2 && test.Acks == 1;
|
||||
test.AckError = null; test.Now = 60_000; await test.Run();
|
||||
checks["learning_pending_ack_retries_even_when_rules_are_backing_off"] = test.Fetches == 2 && test.Acks == 2 && test.Acknowledged.SequenceEqual(["revision-1"]);
|
||||
test.Now++; await test.Run();
|
||||
checks["learning_successful_pending_ack_is_not_repeated_without_new_apply"] = test.Acks == 2;
|
||||
|
||||
test = new Fixture { UploadError = new ApiException(500, "transient") };
|
||||
await test.Run(); test.Now = 59_999; await test.Run();
|
||||
checks["learning_transient_first_retry_waits_one_minute"] = test.Uploads == 1;
|
||||
test.Now = 60_000; await test.Run(); test.Now = 179_999; await test.Run();
|
||||
checks["learning_transient_second_retry_waits_two_minutes"] = test.Uploads == 2;
|
||||
test.Now = 180_000; await test.Run(); test.Now = 419_999; await test.Run();
|
||||
checks["learning_transient_third_retry_waits_four_minutes"] = test.Uploads == 3;
|
||||
test.Now = 420_000; await test.Run(); test.Now = 719_999; await test.Run();
|
||||
checks["learning_transient_backoff_caps_at_five_minutes"] = test.Uploads == 4;
|
||||
test.Now = 720_000; await test.Run();
|
||||
checks["learning_transient_cap_eventually_retries"] = test.Uploads == 5;
|
||||
|
||||
test = new Fixture { UploadError = new ApiException(404, "missing"), Now = 1_000_000 };
|
||||
await test.Run(); test.Now = 1; await test.Run();
|
||||
checks["learning_clock_regression_does_not_retry_early"] = test.Uploads == 1;
|
||||
test.Now = 1_119_999; await test.Run(); test.Now = 1_120_000; await test.Run();
|
||||
checks["learning_retry_uses_monotonic_deadline_not_wall_clock"] = test.Uploads == 2;
|
||||
test.Coordinator.Reset(); await test.Run();
|
||||
checks["learning_session_reset_clears_endpoint_backoff"] = test.Uploads == 3;
|
||||
|
||||
foreach (var status in new[] { 401, 403 })
|
||||
{
|
||||
test = new Fixture { UploadError = new ApiException(status, "authentication failed") };
|
||||
var original = test.UploadError;
|
||||
Exception? thrown = null;
|
||||
try { await test.Run(); } catch (Exception error) { thrown = error; }
|
||||
checks[$"learning_upload_{status}_propagates_without_optional_fallback"] = ReferenceEquals(original, thrown)
|
||||
&& test.Fetches == 0 && test.Applies == 0 && test.Acks == 0 && test.Diagnostics.Count == 0;
|
||||
test = new Fixture { FetchError = new ApiException(status, "authentication failed") };
|
||||
original = test.FetchError; thrown = null;
|
||||
try { await test.Run(); } catch (Exception error) { thrown = error; }
|
||||
checks[$"learning_rules_{status}_propagates_without_ack"] = ReferenceEquals(original, thrown) && test.Acks == 0;
|
||||
test = new Fixture { AckError = new ApiException(status, "authentication failed") };
|
||||
original = test.AckError; thrown = null;
|
||||
try { await test.Run(); } catch (Exception error) { thrown = error; }
|
||||
checks[$"learning_ack_{status}_propagates_without_removing_applied_rules"] = ReferenceEquals(original, thrown) && test.LastApplied == "revision-1";
|
||||
}
|
||||
|
||||
test = new Fixture { Current = false };
|
||||
await test.Run();
|
||||
checks["learning_wrong_session_does_not_send_requests"] = test.Uploads == 0 && test.Fetches == 0;
|
||||
test = new Fixture();
|
||||
var fetchResult = new TaskCompletionSource<RoutingManifest>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
test.FetchOverride = _ => fetchResult.Task;
|
||||
var inFlight = test.Run();
|
||||
test.Current = false; fetchResult.SetResult(new RoutingManifest { Revision = "old-session" });
|
||||
await inFlight;
|
||||
checks["learning_late_manifest_cannot_apply_to_new_session_or_core"] = test.Fetches == 1 && test.Applies == 0 && test.Acks == 0;
|
||||
|
||||
test = new Fixture();
|
||||
var uploadResult = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
test.UploadOverride = _ => uploadResult.Task;
|
||||
inFlight = test.Run();
|
||||
await test.Run();
|
||||
checks["learning_overlapping_run_does_not_duplicate_requests"] = test.Uploads == 1;
|
||||
test.Coordinator.Reset(); uploadResult.SetException(new ApiException(404, "old session"));
|
||||
await inFlight;
|
||||
checks["learning_reset_invalidates_old_error_without_new_session_penalty"] = test.Fetches == 0 && test.Diagnostics.Count == 0;
|
||||
test.UploadOverride = null; await test.Run();
|
||||
checks["learning_new_session_can_sync_immediately_after_reset"] = test.Uploads == 2 && test.Applies == 1 && test.Acks == 1;
|
||||
|
||||
test = new Fixture();
|
||||
fetchResult = new TaskCompletionSource<RoutingManifest>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
test.FetchOverride = _ => fetchResult.Task;
|
||||
inFlight = test.Run();
|
||||
test.Current = false; fetchResult.SetException(new ApiException(401, "expired previous account"));
|
||||
await inFlight;
|
||||
checks["learning_stale_auth_failure_does_not_expire_successor_account"] = test.Applies == 0 && test.Diagnostics.Count == 0;
|
||||
|
||||
test = new Fixture { ApplyAccepted = false };
|
||||
await test.Run();
|
||||
checks["learning_rejected_core_epoch_is_not_acknowledged"] = test.Applies == 1 && test.Acks == 0;
|
||||
test = new Fixture { AckError = new ApiException(404, "missing") };
|
||||
await test.Run(); test.Coordinator.Reset();
|
||||
test.FetchError = new ApiException(404, "missing"); test.AckError = null;
|
||||
await test.Run();
|
||||
checks["learning_session_reset_discards_pending_ack"] = test.Acks == 1;
|
||||
|
||||
test = new Fixture();
|
||||
using var cancelled = new CancellationTokenSource(); cancelled.Cancel();
|
||||
var sawCancellation = false;
|
||||
try { await test.Run(cancelled.Token); } catch (OperationCanceledException) { sawCancellation = true; }
|
||||
checks["learning_cancellation_prevents_requests"] = sawCancellation && test.Uploads == 0;
|
||||
using var deadline = new CancellationTokenSource();
|
||||
test.UploadOverride = token => { deadline.Cancel(); return Task.CompletedTask; };
|
||||
sawCancellation = false;
|
||||
try { await test.Run(deadline.Token); } catch (OperationCanceledException) { sawCancellation = true; }
|
||||
checks["learning_ignored_callback_cancellation_still_stops_following_requests"] = sawCancellation && test.Fetches == 0;
|
||||
|
||||
test = new Fixture { UploadError = new TimeoutException("credential in exception") };
|
||||
await test.Run();
|
||||
checks["learning_timeout_is_transient_and_does_not_block_rule_fetch"] = test.Diagnostics.SequenceEqual(["learning.upload.transient.backoff"]) && test.Applies == 1;
|
||||
}
|
||||
|
||||
private sealed class Fixture
|
||||
{
|
||||
internal long Now;
|
||||
internal bool Current = true;
|
||||
internal bool ApplyAccepted = true;
|
||||
internal Exception? UploadError, FetchError, AckError;
|
||||
internal Func<CancellationToken, Task>? UploadOverride;
|
||||
internal Func<CancellationToken, Task<RoutingManifest>>? FetchOverride;
|
||||
internal int Uploads, Fetches, Applies, Acks;
|
||||
internal string? LastApplied;
|
||||
internal List<string> Acknowledged = [];
|
||||
internal List<string> Diagnostics = [];
|
||||
internal LearningSyncCoordinator Coordinator { get; }
|
||||
internal Fixture() => Coordinator = new(() => Now);
|
||||
|
||||
internal Task Run(CancellationToken token = default) => Coordinator.RunAsync(() => Current,
|
||||
cancellation =>
|
||||
{
|
||||
Uploads++;
|
||||
return UploadOverride?.Invoke(cancellation) ?? (UploadError is { } error ? Task.FromException(error) : Task.CompletedTask);
|
||||
},
|
||||
cancellation =>
|
||||
{
|
||||
Fetches++;
|
||||
return FetchOverride?.Invoke(cancellation) ?? (FetchError is { } error
|
||||
? Task.FromException<RoutingManifest>(error) : Task.FromResult(new RoutingManifest { Revision = "revision-1" }));
|
||||
},
|
||||
(manifest, cancellation) =>
|
||||
{
|
||||
Applies++;
|
||||
if (ApplyAccepted) LastApplied = manifest.Revision;
|
||||
return Task.FromResult(ApplyAccepted);
|
||||
},
|
||||
(revision, cancellation) =>
|
||||
{
|
||||
Acks++;
|
||||
if (AckError is { } error) return Task.FromException(error);
|
||||
Acknowledged.Add(revision);
|
||||
return Task.CompletedTask;
|
||||
}, token, Diagnostics.Add);
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ internal sealed partial class MainForm
|
||||
private readonly Label _sampleLabel = new();
|
||||
private readonly Label _uploadLegend = new();
|
||||
private readonly Label _downloadLegend = new();
|
||||
private readonly Label _dailyUploadLegend = new(), _dailyDownloadLegend = new();
|
||||
private readonly Label _historyStatus = new();
|
||||
private readonly ReadOnlyModeLabel _routeReadOnly = new();
|
||||
private readonly ComboBox _historyRangeCombo = new();
|
||||
@@ -29,7 +28,11 @@ internal sealed partial class MainForm
|
||||
private readonly DashboardGlyph _trafficIcon = new(DashboardIcon.Chart), _dailyIcon = new(DashboardIcon.History);
|
||||
private readonly Label _trafficHeading = new(), _dailyHeading = new();
|
||||
private bool _layingOutDashboard;
|
||||
private DashboardWheelRouter? _dashboardWheelRouter;
|
||||
private sealed record SpeedHistoryPeriod(int Minutes, string Label)
|
||||
{
|
||||
public override string ToString() => Label;
|
||||
internal static readonly SpeedHistoryPeriod[] All = [new(1, "近 1 分钟"), new(5, "近 5 分钟"), new(15, "近 15 分钟"), new(60, "近 1 小时")];
|
||||
}
|
||||
|
||||
private void BuildDashboardView()
|
||||
{
|
||||
@@ -71,7 +74,7 @@ internal sealed partial class MainForm
|
||||
_statusDot.ForeColor = Brand.Muted;
|
||||
_statusCard.ScenicStatus = true;
|
||||
_nodeCard.AccentBar = _modeCard.AccentBar = true;
|
||||
_trafficCard.MetricBand = _dailyCard.MetricBand = true;
|
||||
_trafficCard.MetricBand = _dailyCard.MetricBand = false;
|
||||
ConfigurePrimaryButton(_connectButton, "连接", Point.Empty, new(130, 42));
|
||||
_connectButton.Click += async (_, _) =>
|
||||
{
|
||||
@@ -91,20 +94,21 @@ internal sealed partial class MainForm
|
||||
_routeReadOnly.Visible = false;
|
||||
_modeCard.Controls.AddRange([_modeIcon, _routeHeading, _routeCombo, _routeReadOnly]);
|
||||
|
||||
ConfigureLabel(_trafficHeading, "实时网速", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_dailyHeading, "代理流量", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_trafficHeading, "代理实时速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_dailyHeading, "速度与累计", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted);
|
||||
_sampleLabel.TextAlign = ContentAlignment.MiddleRight;
|
||||
ConfigureLabel(_uploadLegend, "● 上传 —", Brand.Font(8), Brand.RoyalBlue);
|
||||
ConfigureLabel(_downloadLegend, "● 下载 —", Brand.Font(8), Brand.Cyan);
|
||||
ConfigureLabel(_dailyUploadLegend, "● 上传", Brand.Font(8), Brand.RoyalBlue);
|
||||
ConfigureLabel(_dailyDownloadLegend, "● 下载", Brand.Font(8), Brand.Cyan);
|
||||
ConfigureLabel(_historyStatus, "套餐全部设备 · 按天统计", Brand.Font(7), Brand.Muted);
|
||||
ConfigureLabel(_historyStatus, "仅本次运行采样 · B/s", Brand.Font(7), Brand.Muted);
|
||||
_historyStatus.AutoEllipsis = true;
|
||||
_historyStatus.TextAlign = ContentAlignment.MiddleRight;
|
||||
_dailyChart.HistoryChanged += () => { _historyStatus.Text = _dailyChart.StatusText; _historyStatus.AccessibleDescription = _dailyChart.DetailText; };
|
||||
_trafficCard.Controls.AddRange([_trafficIcon, _trafficHeading, _sampleLabel, _trafficChart, _uploadLegend, _downloadLegend]);
|
||||
_dailyCard.Controls.AddRange([_dailyIcon, _dailyHeading, _dailyChart, _dailyUploadLegend, _dailyDownloadLegend]);
|
||||
_historyStatus.AccessibleDescription = "右侧曲线仅为当前客户端实际采集的代理速度。累计数值来自套餐和本次连接,不随速度时间范围改变。";
|
||||
_trafficCard.Controls.AddRange([_trafficIcon, _trafficHeading]);
|
||||
_dailyCard.Controls.AddRange([_dailyIcon, _dailyHeading, _trafficChart, _uploadLegend, _downloadLegend]);
|
||||
// Keep backend accounting data available to UpdateProfile, but daily
|
||||
// byte totals are no longer drawn as a misleading speed history.
|
||||
_dailyChart.Visible = false;
|
||||
ConfigureCombo(_historyRangeCombo, Point.Empty, new(120, 28));
|
||||
_historyRangeCombo.BackColor = Color.White;
|
||||
_historyRangeCombo.Font = Brand.Font(8.5f);
|
||||
@@ -119,12 +123,12 @@ internal sealed partial class MainForm
|
||||
e.Bounds, Brand.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.EndEllipsis);
|
||||
e.DrawFocusRectangle();
|
||||
};
|
||||
_historyRangeCombo.AccessibleName = "代理流量历史时间范围";
|
||||
_historyRangeCombo.Items.AddRange(UsageHistoryPeriod.All);
|
||||
_historyRangeCombo.SelectedItem = UsageHistoryPeriod.All[2];
|
||||
_historyRangeCombo.AccessibleName = "代理实时速度时间范围";
|
||||
_historyRangeCombo.Items.AddRange(SpeedHistoryPeriod.All);
|
||||
_historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1];
|
||||
_historyRangeCombo.SelectedIndexChanged += (_, _) =>
|
||||
{
|
||||
if (_historyRangeCombo.SelectedItem is UsageHistoryPeriod period) _dailyChart.SetPeriod(period);
|
||||
if (_historyRangeCombo.SelectedItem is SpeedHistoryPeriod period) _trafficChart.SetPeriodMinutes(period.Minutes);
|
||||
};
|
||||
_dailyCard.Controls.AddRange([_historyRangeCombo, _historyStatus]);
|
||||
ConfigureLabel(_planLabel, "", Brand.Font(8.5f), Brand.Muted);
|
||||
@@ -155,14 +159,15 @@ internal sealed partial class MainForm
|
||||
}
|
||||
_sessionMetric.SetBytes(0, hint: "本次连接累计");
|
||||
DisplayTraffic(null, null, "仅代理流量 · 近 5 分钟");
|
||||
_dashboardWheelRouter = new DashboardWheelRouter(_dashboardView, _dashboardScrollBar);
|
||||
// The dashboard is one fitted page; no hidden vertical or horizontal
|
||||
// canvas is introduced by Tailnet, and mouse-wheel cannot shift it.
|
||||
LayoutDashboard();
|
||||
}
|
||||
|
||||
private void DisplayTraffic(double? upload, double? download, string sampling)
|
||||
{
|
||||
_uploadMetric.SetBytes(upload, speed: true);
|
||||
_downloadMetric.SetBytes(download, speed: true);
|
||||
_uploadMetric.SetBytes(upload, speed: true, hint: "");
|
||||
_downloadMetric.SetBytes(download, speed: true, hint: "");
|
||||
_sampleLabel.Text = sampling;
|
||||
_uploadLegend.Text = upload.HasValue ? $"● 上传 {FormatBytes((long)upload.Value)}/s" : "● 上传 —";
|
||||
_downloadLegend.Text = download.HasValue ? $"● 下载 {FormatBytes((long)download.Value)}/s" : "● 下载 —";
|
||||
@@ -179,71 +184,66 @@ internal sealed partial class MainForm
|
||||
foreach (var container in layoutContainers) container.SuspendLayout();
|
||||
try
|
||||
{
|
||||
var previousScroll = _dashboardScrollBar.Value;
|
||||
// Explicit vertical canvas: card reflow must never retain a previous
|
||||
// horizontal extent or reset the user's scroll offset on repaint.
|
||||
var viewport = _dashboardView.ClientSize;
|
||||
var layout = DashboardLayout.Calculate(viewport, DeviceDpi, _tailnetTrafficVisible);
|
||||
_dashboardScrollBar.Visible = layout.ContentHeight > viewport.Height;
|
||||
_dashboardScrollBar.Bounds = new Rectangle(viewport.Width - ScaleLogical(17), 0, ScaleLogical(17), viewport.Height);
|
||||
if (_dashboardScrollBar.Visible)
|
||||
layout = DashboardLayout.Calculate(new Size(viewport.Width - ScaleLogical(17), viewport.Height), DeviceDpi, _tailnetTrafficVisible);
|
||||
var titleSize = 17f * Math.Max(.7f, layout.VerticalScale);
|
||||
if (Math.Abs(_statusTitle.Font.Size - titleSize) > .1f)
|
||||
{
|
||||
var previousTitleFont = _statusTitle.Font;
|
||||
_statusTitle.Font = Brand.Font(titleSize, FontStyle.Bold);
|
||||
previousTitleFont.Dispose();
|
||||
}
|
||||
_dashboardScrollBar.Visible = false;
|
||||
_dashboardScrollBar.Value = 0;
|
||||
_dashboardScrollBar.Maximum = 0;
|
||||
int Y(int value) => Math.Max(0, (int)Math.Floor(ScaleLogical(value) * layout.VerticalScale));
|
||||
void Place(Control c, Rectangle r) { c.Bounds = r; }
|
||||
Rectangle R(int x, int y, int w, int h) => new(ScaleLogical(x), ScaleLogical(y), ScaleLogical(w), ScaleLogical(h));
|
||||
Rectangle R(int x, int y, int w, int h) => new(ScaleLogical(x), Y(y), ScaleLogical(w), Y(h));
|
||||
Place(_welcomeLabel, layout.WelcomeLabel); Place(_accountLabel, layout.AccountLabel);
|
||||
Place(_identityBadge, layout.IdentityBadge); Place(_logoutButton, layout.LogoutButton);
|
||||
Place(_statusCard, layout.StatusCard); Place(_nodeCard, layout.NodeCard); Place(_modeCard, layout.ModeCard);
|
||||
var metrics = new[] { _usageMetric, _uploadMetric, _downloadMetric, _sessionMetric };
|
||||
for (var i = 0; i < 4; i++) Place(metrics[i], layout.Metrics[i]);
|
||||
Place(_trafficCard, layout.TrafficCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer);
|
||||
LayoutTailnetTrafficCard(layout.TailnetTrafficCard);
|
||||
LayoutTailnetTrafficCard(layout.TailnetTrafficCard, layout.VerticalScale);
|
||||
|
||||
_statusDot.Bounds = R(24, 15, 42, 46);
|
||||
_connectButton.Bounds = new(_statusCard.Width - ScaleLogical(148), ScaleLogical(17), ScaleLogical(130), ScaleLogical(42));
|
||||
_connectButton.Bounds = new(_statusCard.Width - ScaleLogical(148), Y(17), ScaleLogical(130), Y(42));
|
||||
var textWidth = _connectButton.Left - ScaleLogical(100);
|
||||
_statusTitle.Bounds = new(ScaleLogical(84), ScaleLogical(10), textWidth, ScaleLogical(33));
|
||||
_statusDetail.Bounds = new(ScaleLogical(85), ScaleLogical(43), textWidth, ScaleLogical(25));
|
||||
_statusTitle.Bounds = new(ScaleLogical(84), Y(10), textWidth, Y(33));
|
||||
_statusDetail.Bounds = new(ScaleLogical(85), Y(43), textWidth, Y(25));
|
||||
_nodeIcon.Bounds = R(26, 23, 24, 24); _modeIcon.Bounds = R(26, 23, 24, 24);
|
||||
_nodeHeading.Bounds = new(ScaleLogical(54), ScaleLogical(9), Math.Max(0, _nodeCard.Width - ScaleLogical(205)), ScaleLogical(23));
|
||||
_connectionModeCombo.Bounds = new(_nodeCard.Width - ScaleLogical(144), ScaleLogical(6), ScaleLogical(130), ScaleLogical(28));
|
||||
_manualNodeCombo.Bounds = new(ScaleLogical(54), ScaleLogical(34), _nodeCard.Width - ScaleLogical(68), ScaleLogical(28));
|
||||
_nodeHeading.Bounds = new(ScaleLogical(54), Y(9), Math.Max(0, _nodeCard.Width - ScaleLogical(205)), Y(23));
|
||||
_nodeHeading.Text = layout.Compact ? "工作节点" : "当前工作节点";
|
||||
_connectionModeCombo.Bounds = new(_nodeCard.Width - ScaleLogical(144), Y(6), ScaleLogical(130), Y(28));
|
||||
_manualNodeCombo.Bounds = new(ScaleLogical(54), Y(34), _nodeCard.Width - ScaleLogical(68), Y(28));
|
||||
var badgeWidth = ScaleLogical(88);
|
||||
var badgeX = _nodeCard.Width - badgeWidth - ScaleLogical(14);
|
||||
_currentNodeLabel.Bounds = new(ScaleLogical(54), ScaleLogical(34),
|
||||
_selectionUiConnected ? _nodeCard.Width - ScaleLogical(68) : badgeX - ScaleLogical(60), ScaleLogical(27));
|
||||
_scheduleBadge.Bounds = new(badgeX, ScaleLogical(35), badgeWidth, ScaleLogical(23));
|
||||
_routeHeading.Bounds = new(ScaleLogical(54), ScaleLogical(8), _modeCard.Width - ScaleLogical(70), ScaleLogical(22));
|
||||
_routeCombo.Bounds = new(ScaleLogical(54), ScaleLogical(33), _modeCard.Width - ScaleLogical(70), ScaleLogical(28));
|
||||
_routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, ScaleLogical(28));
|
||||
_currentNodeLabel.Bounds = new(ScaleLogical(54), Y(34),
|
||||
_selectionUiConnected ? _nodeCard.Width - ScaleLogical(68) : badgeX - ScaleLogical(60), Y(27));
|
||||
_scheduleBadge.Bounds = new(badgeX, Y(35), badgeWidth, Y(23));
|
||||
_routeHeading.Bounds = new(ScaleLogical(54), Y(8), _modeCard.Width - ScaleLogical(70), Y(22));
|
||||
_routeCombo.Bounds = new(ScaleLogical(54), Y(33), _modeCard.Width - ScaleLogical(70), Y(28));
|
||||
_routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, Y(28));
|
||||
_trafficIcon.Bounds = R(15, 10, 20, 20); _dailyIcon.Bounds = R(15, 10, 20, 20);
|
||||
_trafficHeading.Bounds = R(42, 8, 92, 26);
|
||||
_sampleLabel.Bounds = new(ScaleLogical(132), ScaleLogical(10), _trafficCard.Width - ScaleLogical(146), ScaleLogical(22));
|
||||
_dailyHeading.Bounds = new(ScaleLogical(42), ScaleLogical(8), _dailyCard.Width - ScaleLogical(180), ScaleLogical(26));
|
||||
_historyRangeCombo.Bounds = new(_dailyCard.Width - ScaleLogical(140), ScaleLogical(10), ScaleLogical(124), ScaleLogical(26));
|
||||
_trafficChart.Bounds = new(ScaleLogical(13), ScaleLogical(132), _trafficCard.Width - ScaleLogical(26), ScaleLogical(106));
|
||||
_dailyChart.Bounds = new(ScaleLogical(13), ScaleLogical(132), _dailyCard.Width - ScaleLogical(26), _dailyCard.Height - ScaleLogical(170));
|
||||
var legendWidth = (_trafficCard.Width - ScaleLogical(40)) / 2;
|
||||
_uploadLegend.Bounds = new(ScaleLogical(20), ScaleLogical(248), legendWidth, ScaleLogical(19));
|
||||
_downloadLegend.Bounds = new(ScaleLogical(20) + legendWidth, ScaleLogical(248), legendWidth, ScaleLogical(19));
|
||||
var dailyLegendTop = _dailyCard.Height - ScaleLogical(28);
|
||||
_dailyUploadLegend.Bounds = new(ScaleLogical(20), dailyLegendTop, ScaleLogical(52), ScaleLogical(19));
|
||||
_dailyDownloadLegend.Bounds = new(ScaleLogical(76), dailyLegendTop, ScaleLogical(52), ScaleLogical(19));
|
||||
_historyStatus.Bounds = new(ScaleLogical(134), dailyLegendTop, _dailyCard.Width - ScaleLogical(148), ScaleLogical(19));
|
||||
_dailyHeading.Bounds = new(ScaleLogical(42), Y(8), Math.Max(1, _dailyCard.Width - ScaleLogical(166)), Y(26));
|
||||
_historyRangeCombo.Bounds = new(_dailyCard.Width - ScaleLogical(120), Y(8), ScaleLogical(106), Y(26));
|
||||
_trafficChart.Bounds = new(ScaleLogical(10), Y(127), _dailyCard.Width - ScaleLogical(20), Y(105));
|
||||
var legendWidth = (_dailyCard.Width - ScaleLogical(28)) / 2;
|
||||
_uploadLegend.Bounds = new(ScaleLogical(14), Y(234), legendWidth, Y(19));
|
||||
_downloadLegend.Bounds = new(ScaleLogical(14) + legendWidth, Y(234), legendWidth, Y(19));
|
||||
_historyStatus.Bounds = new(ScaleLogical(14), Y(255), _dailyCard.Width - ScaleLogical(28), Y(17));
|
||||
_planLabel.Bounds = R(0, 4, 300, 26);
|
||||
_expiryLabel.Bounds = R(306, 4, 132, 26);
|
||||
_footerCompanyLogo.Bounds = R(0, 34, 32, 34);
|
||||
_footerCompanySite.Bounds = R(0, 41, 220, 22);
|
||||
_footerHint.Visible = true;
|
||||
_footerHint.Bounds = new(ScaleLogical(232), ScaleLogical(39), Math.Max(1, _footer.Width - ScaleLogical(232)), ScaleLogical(28));
|
||||
_footerHint.Bounds = new(ScaleLogical(232), Y(39), Math.Max(1, _footer.Width - ScaleLogical(232)), Y(28));
|
||||
_footerPoem.Visible = !layout.Compact && _footer.Width >= ScaleLogical(780);
|
||||
_footerPoem.Bounds = new(_footer.Width - ScaleLogical(322), ScaleLogical(5), ScaleLogical(322), ScaleLogical(29));
|
||||
_dashboardBody.Size = new Size(layout.StatusCard.Right + ScaleLogical(20), layout.ContentHeight);
|
||||
_dashboardScrollBar.Maximum = Math.Max(0, layout.ContentHeight - 1);
|
||||
_dashboardScrollBar.LargeChange = Math.Max(1, viewport.Height);
|
||||
_dashboardScrollBar.SmallChange = ScaleLogical(28);
|
||||
_dashboardScrollBar.Value = Math.Clamp(previousScroll, 0, Math.Max(0, layout.ContentHeight - viewport.Height));
|
||||
_dashboardBody.Location = new Point(0, -_dashboardScrollBar.Value);
|
||||
_dashboardScrollBar.BringToFront();
|
||||
_footerPoem.Bounds = new(_footer.Width - ScaleLogical(322), Y(5), ScaleLogical(322), Y(29));
|
||||
_dashboardBody.Size = viewport;
|
||||
_dashboardBody.Location = Point.Empty;
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -314,26 +314,29 @@ internal sealed partial class MainForm
|
||||
checks["content_uses_local_buffers_not_composited_subtree"] = !form._content.ComposeChildren;
|
||||
checks["dashboard_reuses_login_backdrop"] = form._dashboardView.LoginArtwork && form._dashboardBody.ParentArtwork;
|
||||
checks["header_only_has_minimize_button"] = form._brandHeader.Controls.OfType<CaptionButton>().Count() == 1;
|
||||
checks["scenic_asset_is_decoration_only"] = form._brandHeader.BackgroundImage is null && form._trafficChart.Parent == form._trafficCard;
|
||||
checks["scenic_asset_is_decoration_only"] = form._brandHeader.BackgroundImage is null && form._trafficChart.Parent == form._dailyCard;
|
||||
checks["scenic_artwork_packaged_in_exe"] = ScenicTheme.ArtworkAvailable;
|
||||
checks["footer_poem_does_not_overlap_plan"] = !form._footerPoem.Visible || form._footerPoem.Left > form._expiryLabel.Right;
|
||||
checks["internal_use_notice_visible"] = form._footerHint.Text == "仅限内部使用,不作商业使用。" && form._footerHint.Visible;
|
||||
checks["proxy_metrics_values"] = form._usageMetric.UnitText == "GB" && form._uploadMetric.UnitText == "KB/s" && form._sessionMetric.UnitText == "MB";
|
||||
checks["related_metrics_share_chart_parent"] = form._usageMetric.Parent == form._sessionMetric.Parent &&
|
||||
form._uploadMetric.Parent == form._trafficChart.Parent && form._downloadMetric.Parent == form._trafficChart.Parent;
|
||||
checks["speed_figures_left_curve_and_totals_right"] = form._usageMetric.Parent == form._sessionMetric.Parent
|
||||
&& form._usageMetric.Parent == form._trafficChart.Parent && form._uploadMetric.Parent == form._trafficCard
|
||||
&& form._downloadMetric.Parent == form._trafficCard;
|
||||
form._historyRangeCombo.SelectedIndex = 0;
|
||||
Capture("history-legacy-unavailable");
|
||||
checks["legacy_hourly_no_invented_curve"] = form._dailyChart.PointCount == 0;
|
||||
checks["daily_accounting_curve_no_longer_displayed"] = form._dailyChart.Parent is null && !form._dailyChart.Visible;
|
||||
form._dailyChart.SetHistory([], fixtureRanges);
|
||||
foreach (var period in UsageHistoryPeriod.All)
|
||||
var retainedSampleCount = form._trafficChart.PointCount;
|
||||
foreach (var period in SpeedHistoryPeriod.All)
|
||||
{
|
||||
form._historyRangeCombo.SelectedItem = period;
|
||||
Capture("history-" + period.Key);
|
||||
checks["filter_" + period.Key] = form._dailyChart.SelectedRange == period.Key && form._dailyChart.PointCount == period.Count;
|
||||
Capture("speed-" + period.Minutes + "m");
|
||||
checks["speed_filter_" + period.Minutes] = form._trafficChart.PeriodMinutes == period.Minutes
|
||||
&& form._trafficChart.PointCount == retainedSampleCount;
|
||||
}
|
||||
form._dailyChart.SetHistory([], fixtureRanges);
|
||||
checks["profile_refresh_preserves_filter"] = form._dailyChart.SelectedRange == "30d";
|
||||
form._historyRangeCombo.SelectedIndex = 2;
|
||||
checks["profile_refresh_preserves_speed_filter"] = form._trafficChart.PeriodMinutes == 60;
|
||||
form._historyRangeCombo.SelectedIndex = 1;
|
||||
form.Size = form.MinimumSize;
|
||||
Capture("compact");
|
||||
checks["zero3_compact_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width;
|
||||
@@ -341,7 +344,8 @@ internal sealed partial class MainForm
|
||||
form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1);
|
||||
Application.DoEvents();
|
||||
form.LayoutDashboard();
|
||||
checks["compact_footer_scrolls_into_view"] = form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom <= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom;
|
||||
checks["compact_footer_fits_without_scroll"] = !form._dashboardScrollBar.Visible
|
||||
&& form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom <= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom;
|
||||
checks["compact_no_horizontal_scrollbar"] = !form._dashboardView.HorizontalScroll.Visible;
|
||||
Capture("compact-scrolled");
|
||||
form._dashboardScrollBar.Value = 0;
|
||||
@@ -364,16 +368,15 @@ internal sealed partial class MainForm
|
||||
form.SetConnectionState(true, "已安全连接", "手动指定节点 · AI 智能代理");
|
||||
Capture("manual-connected");
|
||||
checks["manual_connected_selection_locked"] = !form._connectionModeCombo.Enabled && !form._manualNodeCombo.Visible;
|
||||
// Synthetic preview of the same already-accounted proxy sample on a
|
||||
// Tailnet connection. Use a taller fixture to show both left cards;
|
||||
// this does not change the production window size or claim live data.
|
||||
// Same window dimensions with or without Tailnet: only the left speed
|
||||
// region is subdivided. Synthetic samples do not claim live acceptance.
|
||||
form._connectionModeCombo.SelectedIndex = 0;
|
||||
form._currentNodeBaseName = "VPN003";
|
||||
form.UpdateConnectedTransportPresentation(true);
|
||||
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理");
|
||||
form._currentNodeLabel.Text = form._currentNodeName;
|
||||
form._dailyChart.SetHistory([], fixtureRanges);
|
||||
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(1020));
|
||||
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
|
||||
form._trafficChart.Reset();
|
||||
form.ResetTailnetTraffic();
|
||||
for (var i = 0; i < 60; i++)
|
||||
@@ -382,7 +385,6 @@ internal sealed partial class MainForm
|
||||
var down = (i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024;
|
||||
var sampledAt = DateTimeOffset.Now.AddSeconds((i - 59) * 5);
|
||||
form._trafficChart.Add(up, down, sampledAt);
|
||||
form._tailnetTrafficChart.Add(up, down, sampledAt);
|
||||
}
|
||||
form.DisplayTraffic(23842, 89312, "演示样本 · 近 5 分钟");
|
||||
form.DisplayTailnetTraffic(23842, 89312, "演示样本 · 近 5 分钟");
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
private readonly LearningSyncCoordinator _learningSync = new();
|
||||
private int? _learningSyncCore;
|
||||
private readonly TailnetReadinessPolicy _tailnetReadiness = new();
|
||||
private readonly ToolStripMenuItem _tailnetReconnectItem = new("优先内网重连(会重建连接)") { Enabled = false };
|
||||
|
||||
private void SetSessionToken(string? token)
|
||||
{
|
||||
_connectionAttemptCancellation?.Cancel();
|
||||
_accessToken = token;
|
||||
_sessionRevision++;
|
||||
_learningSync.Reset();
|
||||
_learningSyncCore = null;
|
||||
_tailnetReadiness.Reset();
|
||||
_tailnetReconnectItem.Enabled = false;
|
||||
while (_observationQueue.TryDequeue(out _)) { }
|
||||
}
|
||||
|
||||
private bool TryCancelPendingConnection()
|
||||
{
|
||||
if (_connectionAttemptCancellation is not { } pending) return false;
|
||||
_wantConnected = false;
|
||||
pending.Cancel();
|
||||
_connectButton.Enabled = false;
|
||||
_statusDetail.Text = "正在取消连接并恢复本机网络…";
|
||||
return true;
|
||||
}
|
||||
|
||||
private TailnetReadinessPolicy.Context ReadTailnetReadinessContext() => new(
|
||||
_sessionRevision, _xray.CoreId, _wantConnected,
|
||||
_busy || _handoverOperating || _xray.IsTransitioning || _exiting,
|
||||
_xray.IsRunning, _xray.UsesTailnet, _xray.PreferredTailnetEndpoint is not null);
|
||||
|
||||
// Read-only recovery observation. TCP availability is NOT authenticated
|
||||
// proxy proof and never authorizes terminating a healthy public connection.
|
||||
private async Task CheckTailnetReadinessAsync()
|
||||
{
|
||||
if (_uiOnly || _preview) return;
|
||||
if (!_tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out var ticket))
|
||||
{
|
||||
_tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy && !_exiting;
|
||||
return;
|
||||
}
|
||||
var reachable = false;
|
||||
try
|
||||
{
|
||||
if (_xray.PreferredTailnetEndpoint is { } endpoint)
|
||||
reachable = await TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, _lifetime.Token);
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception) { /* Advisory only; fixed diagnostics below contain no credentials. */ }
|
||||
var result = _tailnetReadiness.Observe(ticket, ReadTailnetReadinessContext(), Environment.TickCount64, reachable);
|
||||
if (_exiting || IsDisposed || Disposing) return;
|
||||
_tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady && !_busy;
|
||||
if (result == TailnetReadinessPolicy.Result.BecameReady)
|
||||
{
|
||||
AppPaths.WriteLog(new TransportDiagnostic("readiness", "tailnet_endpoint_recovered", _currentNodeSlug ?? "").SafeMessage);
|
||||
_notifyIcon.ShowBalloonTip(3500, "Tailscale 内网入口已恢复",
|
||||
"现有连接保持不变。右键托盘可优先内网重连;重连会重建连接。", ToolTipIcon.Info);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ReconnectThroughPreferredTailnetAsync()
|
||||
{
|
||||
if (_uiOnly || _preview || _exiting || _busy || !_wantConnected || !_xray.IsRunning
|
||||
|| _xray.UsesTailnet || !_tailnetReadiness.IsReady) return;
|
||||
_tailnetReadiness.Reset();
|
||||
_tailnetReconnectItem.Enabled = false;
|
||||
_tailnetPreference.ResetForUserConnect();
|
||||
// Explicit operator action, with fresh management authorization and the
|
||||
// normal same-node/manual constraints. No silent migration of streams.
|
||||
await ToggleConnectionAsync(reconnect: true);
|
||||
}
|
||||
}
|
||||
@@ -4,27 +4,23 @@ internal sealed partial class MainForm
|
||||
{
|
||||
// Presentation only. These controls never read adapter/counter state and
|
||||
// never change proxy, account, session totals or route decisions.
|
||||
private readonly CardPanel _tailnetTrafficCard = new() { MetricBand = true };
|
||||
private readonly CardPanel _tailnetTrafficCard = new();
|
||||
private readonly MetricCard _tailnetUploadMetric = new("上传速度", DashboardIcon.Upload) { Embedded = true };
|
||||
private readonly MetricCard _tailnetDownloadMetric = new("下载速度", DashboardIcon.Download) { Embedded = true };
|
||||
private readonly TrafficChart _tailnetTrafficChart = new();
|
||||
private readonly DashboardGlyph _tailnetTrafficIcon = new(DashboardIcon.Chart);
|
||||
private readonly Label _tailnetTrafficHeading = new(), _tailnetSampleLabel = new();
|
||||
private readonly Label _tailnetUploadLegend = new(), _tailnetDownloadLegend = new();
|
||||
private bool _tailnetTrafficVisible;
|
||||
|
||||
private void BuildTailnetTrafficCard()
|
||||
{
|
||||
ConfigureLabel(_tailnetTrafficHeading, "Tailscale 实时网速", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_tailnetTrafficHeading, "Tailscale 实时速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
|
||||
ConfigureLabel(_tailnetSampleLabel, "等待流量采样", Brand.Font(7.5f), Brand.Muted);
|
||||
_tailnetSampleLabel.TextAlign = ContentAlignment.MiddleRight;
|
||||
_tailnetSampleLabel.AutoEllipsis = true;
|
||||
ConfigureLabel(_tailnetUploadLegend, "● 上传 —", Brand.Font(8), Brand.RoyalBlue);
|
||||
ConfigureLabel(_tailnetDownloadLegend, "● 下载 —", Brand.Font(8), Brand.Cyan);
|
||||
_tailnetTrafficCard.AccessibleName = "Tailscale 实时网速";
|
||||
_tailnetTrafficCard.AccessibleDescription = "仅纵横家当前 Tailscale 代理链路;已计入代理总流量,不代表所有 Tailscale 网卡或整机流量。";
|
||||
_tailnetTrafficCard.Controls.AddRange([_tailnetTrafficIcon, _tailnetTrafficHeading, _tailnetSampleLabel,
|
||||
_tailnetUploadMetric, _tailnetDownloadMetric, _tailnetTrafficChart, _tailnetUploadLegend, _tailnetDownloadLegend]);
|
||||
_tailnetUploadMetric, _tailnetDownloadMetric]);
|
||||
_tailnetTrafficCard.Visible = false;
|
||||
_dashboardBody.Controls.Add(_tailnetTrafficCard);
|
||||
ResetTailnetTraffic();
|
||||
@@ -50,33 +46,29 @@ internal sealed partial class MainForm
|
||||
_tailnetUploadMetric.SetBytes(up, speed: true, hint: "已计入代理总流量");
|
||||
_tailnetDownloadMetric.SetBytes(down, speed: true, hint: "已计入代理总流量");
|
||||
_tailnetSampleLabel.Text = "仅纵横家链路 · " + sampling;
|
||||
_tailnetUploadLegend.Text = up.HasValue ? $"● 上传 {FormatBytes((long)up.Value)}/s" : "● 上传 —";
|
||||
_tailnetDownloadLegend.Text = down.HasValue ? $"● 下载 {FormatBytes((long)down.Value)}/s" : "● 下载 —";
|
||||
if (up.HasValue && down.HasValue) _tailnetTrafficChart.Add(up.Value, down.Value);
|
||||
else _tailnetTrafficChart.Reset();
|
||||
}
|
||||
|
||||
internal void ResetTailnetTraffic()
|
||||
{
|
||||
_tailnetTrafficChart.Reset();
|
||||
DisplayTailnetTraffic(null, null, "等待 Tailscale 流量采样");
|
||||
}
|
||||
|
||||
private void LayoutTailnetTrafficCard(Rectangle bounds)
|
||||
private void LayoutTailnetTrafficCard(Rectangle bounds, float verticalScale)
|
||||
{
|
||||
_tailnetTrafficCard.Visible = _tailnetTrafficVisible;
|
||||
if (!_tailnetTrafficVisible) { _tailnetTrafficCard.Bounds = Rectangle.Empty; return; }
|
||||
_tailnetTrafficCard.Bounds = bounds;
|
||||
int S(int value) => ScaleLogical(value);
|
||||
_tailnetTrafficIcon.Bounds = new Rectangle(S(15), S(10), S(20), S(20));
|
||||
_tailnetTrafficHeading.Bounds = new Rectangle(S(42), S(8), S(132), S(26));
|
||||
_tailnetSampleLabel.Bounds = new Rectangle(S(178), S(10), Math.Max(1, bounds.Width - S(192)), S(22));
|
||||
var metricWidth = (bounds.Width - S(28)) / 2;
|
||||
_tailnetUploadMetric.Bounds = new Rectangle(S(14), S(43), metricWidth - S(2), S(82));
|
||||
_tailnetDownloadMetric.Bounds = new Rectangle(S(14) + metricWidth, S(43), metricWidth - S(2), S(82));
|
||||
_tailnetTrafficChart.Bounds = new Rectangle(S(13), S(132), bounds.Width - S(26), S(106));
|
||||
var legendWidth = (bounds.Width - S(40)) / 2;
|
||||
_tailnetUploadLegend.Bounds = new Rectangle(S(20), S(248), legendWidth, S(19));
|
||||
_tailnetDownloadLegend.Bounds = new Rectangle(S(20) + legendWidth, S(248), legendWidth, S(19));
|
||||
int Y(int value) => Math.Max(0, (int)Math.Floor(S(value) * verticalScale));
|
||||
_tailnetTrafficIcon.Bounds = new Rectangle(S(15), Y(8), S(20), Y(20));
|
||||
_tailnetTrafficHeading.Bounds = new Rectangle(S(42), Y(6), Math.Max(1, bounds.Width - S(52)), Y(26));
|
||||
// Scope remains accessible, without repeating long disclaimers inside
|
||||
// a small speed section. These are the same already-accounted bytes.
|
||||
_tailnetSampleLabel.Visible = false;
|
||||
var metricWidth = (bounds.Width - S(20)) / 2;
|
||||
var metricTop = Math.Max(Y(38), (bounds.Height - Y(82)) / 2);
|
||||
var metricHeight = Math.Min(Y(82), bounds.Height - Y(44));
|
||||
_tailnetUploadMetric.Bounds = new Rectangle(S(10), metricTop, metricWidth - S(1), metricHeight);
|
||||
_tailnetDownloadMetric.Bounds = new Rectangle(S(10) + metricWidth, metricTop, metricWidth - S(1), metricHeight);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
private sealed record PlannedTransport(ConnectionAttempt Attempt, ConfigResponse? Cached = null,
|
||||
bool TailnetOnly = false);
|
||||
|
||||
private async Task<IReadOnlyList<PlannedTransport>> PlanTransportsAsync(ConnectionSelection selection,
|
||||
IReadOnlyList<PrivateAuxiliaryNode> rankedPrivate, string routeMode, CancellationToken token)
|
||||
{
|
||||
var legacy = ConnectionAttemptPlanner.CreateRanked(selection, rankedPrivate, _publicNodeCount);
|
||||
if (selection.Manual || routeMode == "direct")
|
||||
return legacy.Select(a => new PlannedTransport(a)).ToArray();
|
||||
|
||||
_statusDetail.Text = "先并行检测授权内网入口,按响应时间选择;全部不可用后再使用公网。";
|
||||
var publicTailnet = await PublicTailnetSelection.RankAsync(
|
||||
_manualNodeCombo.Items.Cast<NodeInfo>().Where(n => n is not PrivateAuxiliaryNode), routeMode,
|
||||
slug => _failedNodes.ContainsKey(slug) || !_tailnetPreference.MayTry(slug, Environment.TickCount64),
|
||||
(slug, probeToken) => _api.GetConfigAsync(_accessToken!, slug, routeMode, probeToken),
|
||||
TailnetTransport.ProbeEndpointAsync, token, allowKnownEndpoints: _knownTailnetAllowed,
|
||||
diagnostic: (slug, reason) => AppPaths.WriteLog(new TransportDiagnostic("selection_probe", reason, slug).SafeMessage));
|
||||
|
||||
// All reachable authenticated-grant overlay candidates precede domain
|
||||
// fallback. Failure of the fastest candidate does not consume the other
|
||||
// candidates or incorrectly mark its still-usable public ingress down.
|
||||
return rankedPrivate.Where(n => n.ProbeIpv4 != PrivateAuxiliaryRouting.PublicPhoneAddress)
|
||||
.Select(n => new PlannedTransport(new(n.Slug, n)))
|
||||
.Concat(publicTailnet.Select(c => new PlannedTransport(new(c.Response.Node.Slug, null), c.Response, true)))
|
||||
.Concat(rankedPrivate.Where(n => n.ProbeIpv4 == PrivateAuxiliaryRouting.PublicPhoneAddress)
|
||||
.Select(n => new PlannedTransport(new(n.Slug, n))))
|
||||
.Concat(legacy.Where(a => !a.IsPrivate).Select(a => new PlannedTransport(a)))
|
||||
.ToArray();
|
||||
}
|
||||
}
|
||||
+129
-48
@@ -63,6 +63,8 @@ internal sealed partial class MainForm : Form
|
||||
private readonly Label _planLabel = new();
|
||||
|
||||
private string? _accessToken;
|
||||
private long _sessionRevision;
|
||||
private CancellationTokenSource? _connectionAttemptCancellation;
|
||||
private bool _busy;
|
||||
private bool _exiting;
|
||||
private bool _exitRequested;
|
||||
@@ -387,9 +389,9 @@ internal sealed partial class MainForm : Form
|
||||
|
||||
private async Task RestoreSessionAsync()
|
||||
{
|
||||
_accessToken = _runWindowExitSelfTest
|
||||
SetSessionToken(_runWindowExitSelfTest
|
||||
? Environment.GetEnvironmentVariable("UCVL_VPN_TEST_TOKEN") ?? TokenStore.Load()
|
||||
: TokenStore.Load();
|
||||
: TokenStore.Load());
|
||||
if (string.IsNullOrWhiteSpace(_accessToken))
|
||||
{
|
||||
ShowLogin();
|
||||
@@ -405,7 +407,7 @@ internal sealed partial class MainForm : Form
|
||||
{
|
||||
AppPaths.WriteError(exception);
|
||||
if (!_runWindowExitSelfTest) TokenStore.Clear();
|
||||
_accessToken = null;
|
||||
SetSessionToken(null);
|
||||
ShowLogin("登录已失效,请重新登录。");
|
||||
}
|
||||
catch (Exception exception)
|
||||
@@ -435,7 +437,7 @@ internal sealed partial class MainForm : Form
|
||||
try
|
||||
{
|
||||
var response = await _api.LoginAsync(login, password, _lifetime.Token);
|
||||
_accessToken = response.AccessToken;
|
||||
SetSessionToken(response.AccessToken);
|
||||
TokenStore.Save(_accessToken);
|
||||
_passwordText.Clear();
|
||||
ShowDashboard(response.Profile);
|
||||
@@ -467,6 +469,7 @@ internal sealed partial class MainForm : Form
|
||||
private async Task ToggleConnectionAsync(bool suppressDialogs = false, bool reconnect = false)
|
||||
{
|
||||
if (_uiOnly || _preview) return;
|
||||
if (!reconnect && TryCancelPendingConnection()) return;
|
||||
if (_handoverOperating && !reconnect) { await DisconnectAsync(); return; }
|
||||
if (_busy) return;
|
||||
if (_wantConnected && !reconnect)
|
||||
@@ -497,7 +500,10 @@ internal sealed partial class MainForm : Form
|
||||
if (!suppressDialogs) MessageBox.Show(exception.Message, "选择工作节点", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
return;
|
||||
}
|
||||
SetBusy(true, "正在建立安全连接…");
|
||||
using var attemptCancellation = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
|
||||
_connectionAttemptCancellation = attemptCancellation;
|
||||
var connectionToken = attemptCancellation.Token;
|
||||
SetBusy(true, "正在建立安全连接,可点击取消…");
|
||||
_connectionHealth.Invalidate();
|
||||
_nextReconnect = DateTimeOffset.MinValue;
|
||||
_wantConnected = true;
|
||||
@@ -517,28 +523,37 @@ internal sealed partial class MainForm : Form
|
||||
throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。");
|
||||
var rankedPrivate = route.Id == "direct" ? Array.Empty<PrivateAuxiliaryNode>() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants,
|
||||
_failedNodes.Keys.ToHashSet(StringComparer.Ordinal), _xray.IsRunning,
|
||||
PrivateAuxiliaryRouting.MeasureEndpointAsync, _lifetime.Token);
|
||||
var attempts = ConnectionAttemptPlanner.CreateRanked(selection, rankedPrivate, _publicNodeCount);
|
||||
PrivateAuxiliaryRouting.MeasureEndpointAsync, connectionToken);
|
||||
var attempts = await PlanTransportsAsync(selection, rankedPrivate, route.Id, connectionToken);
|
||||
if (reconnect && _transportRetryNodeSlug is { } sameNode
|
||||
&& !attempts.Any(a => a.Slug == sameNode))
|
||||
attempts = new[] { new ConnectionAttempt(sameNode, null) }.Concat(attempts).ToArray();
|
||||
&& !attempts.Any(a => a.Attempt.Slug == sameNode))
|
||||
// A same-node public retry must not jump ahead of another usable
|
||||
// overlay candidate. Keep it before only the public AI pass.
|
||||
attempts = attempts.Where(a => a.Attempt.IsPrivate || a.TailnetOnly)
|
||||
.Concat(new[] { new PlannedTransport(new(sameNode, null)) })
|
||||
.Concat(attempts.Where(a => !a.Attempt.IsPrivate && !a.TailnetOnly)).ToArray();
|
||||
var connectedPrivate = false;
|
||||
var connectedTailnet = false;
|
||||
PrivateAuxiliaryNode? connectedEndpoint = null;
|
||||
foreach (var attempt in attempts)
|
||||
foreach (var planned in attempts)
|
||||
{
|
||||
var attempt = planned.Attempt;
|
||||
NodeInfo? candidate = attempt.Auxiliary;
|
||||
try
|
||||
{
|
||||
var candidateResponse = attempt.Auxiliary is { } auxiliary
|
||||
? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, _lifetime.Token)
|
||||
var candidateResponse = planned.Cached ?? (attempt.Auxiliary is { } auxiliary
|
||||
? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, connectionToken)
|
||||
: await _api.GetConfigAsync(
|
||||
_accessToken,
|
||||
attempt.Slug,
|
||||
route.Id,
|
||||
_lifetime.Token,
|
||||
selection.Manual ? null : _failedNodes.Keys);
|
||||
connectionToken,
|
||||
selection.Manual ? null : _failedNodes.Keys));
|
||||
connectionToken.ThrowIfCancellationRequested();
|
||||
selection.ValidateResponse(candidateResponse.Node.Slug);
|
||||
if ((attempt.Slug != "auto" && candidateResponse.Node.Slug != attempt.Slug)
|
||||
|| candidateResponse.RouteMode != route.Id)
|
||||
throw new InvalidOperationException("服务器返回的节点或代理模式与请求不一致,已拒绝连接。");
|
||||
if (!attempt.IsPrivate && _privateAuxiliaryNodes.Any(n => n.Slug == candidateResponse.Node.Slug))
|
||||
throw new InvalidOperationException("公共调度返回了私有辅助节点,已拒绝混用配置。");
|
||||
candidate = candidateResponse.Node;
|
||||
@@ -549,15 +564,19 @@ internal sealed partial class MainForm : Form
|
||||
async (config, connectionToken) => {
|
||||
replacementStarted = true;
|
||||
await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken,
|
||||
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson());
|
||||
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(),
|
||||
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate));
|
||||
}, _xray.StopAsync, _xray.CheckProxyHealthAsync,
|
||||
address => { TailnetTransport.RequireExistingRoute(address); },
|
||||
message => { _statusDetail.Text = $"{candidateName} · {message}"; },
|
||||
() => Environment.TickCount64, _lifetime.Token,
|
||||
() => Environment.TickCount64, connectionToken,
|
||||
allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate,
|
||||
endpointProbe: TailnetTransport.ProbeEndpointAsync);
|
||||
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(_lifetime.Token))
|
||||
endpointProbe: TailnetTransport.ProbeEndpointAsync,
|
||||
tailnetOnly: planned.TailnetOnly,
|
||||
diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage));
|
||||
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken))
|
||||
throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。");
|
||||
connectionToken.ThrowIfCancellationRequested();
|
||||
if (attempt.IsPrivate && candidateResponse.ConfigExpiresAt <= DateTimeOffset.UtcNow)
|
||||
throw new InvalidOperationException("私有节点授权在连接期间已过期。");
|
||||
connectedPrivate = attempt.IsPrivate;
|
||||
@@ -568,6 +587,12 @@ internal sealed partial class MainForm : Form
|
||||
break;
|
||||
}
|
||||
catch (LocalNetworkException) { throw; }
|
||||
catch (TailnetUnavailableException)
|
||||
{
|
||||
// Connector cleans up only a core it actually attempted.
|
||||
// Retain node eligibility for the later public pass.
|
||||
failures.Add($"{candidate?.Name ?? "内网节点"}: Tailscale 入口未通过,继续其他内网节点。");
|
||||
}
|
||||
catch (ApiException exception) when (exception.StatusCode is not (401 or 403))
|
||||
{
|
||||
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception)) throw;
|
||||
@@ -592,6 +617,7 @@ internal sealed partial class MainForm : Form
|
||||
throw new InvalidOperationException(
|
||||
(selection.Manual ? "指定节点连接失败,未切换其他节点,已执行网络恢复。\n\n" : "所有可用线路均未能建立连接,已执行网络恢复。\n\n") + string.Join("\n", failures));
|
||||
}
|
||||
connectionToken.ThrowIfCancellationRequested();
|
||||
_currentNodeSlug = response.Node.Slug;
|
||||
_currentNodeIsPrivateAuxiliary = connectedPrivate;
|
||||
_currentPrivateEndpoint = connectedEndpoint;
|
||||
@@ -608,6 +634,10 @@ internal sealed partial class MainForm : Form
|
||||
_notifyIcon.Text = "纵横家 · 已连接";
|
||||
_notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"当前线路:{_currentNodeName}", ToolTipIcon.Info);
|
||||
}
|
||||
catch (Exception) when (connectionToken.IsCancellationRequested)
|
||||
{
|
||||
if (!_exiting) await DisconnectAsync();
|
||||
}
|
||||
catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception))
|
||||
{
|
||||
AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name);
|
||||
@@ -619,7 +649,7 @@ internal sealed partial class MainForm : Form
|
||||
}
|
||||
catch (ApiException exception)
|
||||
{
|
||||
await DisconnectAsync();
|
||||
await DisconnectAsync(cancelPending: exception.StatusCode is 401 or 403);
|
||||
if (!suppressDialogs)
|
||||
{
|
||||
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
@@ -632,7 +662,7 @@ internal sealed partial class MainForm : Form
|
||||
catch (Exception exception)
|
||||
{
|
||||
AppPaths.WriteError(exception);
|
||||
await DisconnectAsync();
|
||||
await DisconnectAsync(cancelPending: false);
|
||||
if (!suppressDialogs)
|
||||
{
|
||||
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
@@ -640,14 +670,20 @@ internal sealed partial class MainForm : Form
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (!_xray.IsRunning && reconnect && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); }
|
||||
if (!_xray.IsRunning && reconnect && !connectionToken.IsCancellationRequested && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); }
|
||||
if (ReferenceEquals(_connectionAttemptCancellation, attemptCancellation)) _connectionAttemptCancellation = null;
|
||||
SetBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DisconnectAsync()
|
||||
private async Task DisconnectAsync(bool cancelPending = true)
|
||||
{
|
||||
_wantConnected = false;
|
||||
if (cancelPending) _connectionAttemptCancellation?.Cancel();
|
||||
_tailnetReadiness.Reset();
|
||||
_tailnetReconnectItem.Enabled = false;
|
||||
_learningSync.Reset();
|
||||
_learningSyncCore = null;
|
||||
_handoverCancellation?.Cancel();
|
||||
_handover.Reset();
|
||||
_connectionHealth.Invalidate();
|
||||
@@ -740,6 +776,7 @@ internal sealed partial class MainForm : Form
|
||||
AppPaths.WriteLog("普通智能路径已恢复,沿用原内核与工作节点。");
|
||||
}
|
||||
ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId);
|
||||
await CheckTailnetReadinessAsync();
|
||||
return;
|
||||
}
|
||||
if (decision == ConnectionHealthPolicy.Decision.Repair) {
|
||||
@@ -749,6 +786,7 @@ internal sealed partial class MainForm : Form
|
||||
_statusDot.ForeColor = _statusTitle.ForeColor;
|
||||
_notifyIcon.Text = "纵横家 · 分流修复中";
|
||||
AppPaths.WriteLog($"健康诊断:普通路径失败、代理路径正常;保留内核 {_xray.CoreId},未判为节点故障。");
|
||||
await CheckTailnetReadinessAsync();
|
||||
return;
|
||||
}
|
||||
ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures);
|
||||
@@ -798,30 +836,54 @@ internal sealed partial class MainForm : Form
|
||||
if (_learningSyncing || _busy || _uiOnly || _preview || string.IsNullOrWhiteSpace(_accessToken)) return;
|
||||
_learningSyncing = true;
|
||||
var token = _accessToken;
|
||||
var revision = _sessionRevision;
|
||||
var core = _xray.CoreId;
|
||||
bool IsCurrent() => SessionOperationFence.IsCurrent(revision, _sessionRevision, token, _accessToken, _exiting)
|
||||
&& core is not null && core == _xray.CoreId && !_busy;
|
||||
try
|
||||
{
|
||||
// Memory-only FIFO with stable UUIDs: retries are idempotent, proof follows failure.
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token);
|
||||
deadline.CancelAfter(TimeSpan.FromSeconds(15));
|
||||
// Rule lifetime does not depend on management-server availability.
|
||||
await _xray.ExpireLearningAsync(deadline.Token);
|
||||
for (var count = 0; count < 10 && _observationQueue.TryPeek(out var pending); count++)
|
||||
{
|
||||
if (pending.Token != token || Environment.TickCount64 - pending.Created > 5 * 60_000)
|
||||
{ _observationQueue.TryDequeue(out _); continue; }
|
||||
try { await _api.ReportObservationAsync(token, pending.Observation, deadline.Token); }
|
||||
catch (ApiException error) when (error.StatusCode == 400)
|
||||
{ _observationQueue.TryDequeue(out _); continue; }
|
||||
_observationQueue.TryDequeue(out _);
|
||||
}
|
||||
if (_accessToken != token || _xray.CoreId is not { } core) return;
|
||||
var manifest = await _api.GetRoutingRulesAsync(token, deadline.Token);
|
||||
if (_accessToken != token || _xray.CoreId != core) return;
|
||||
await _xray.CacheLearningCandidatesAsync(manifest, core, deadline.Token);
|
||||
await _api.AcknowledgeRoutingAsync(token, manifest.Revision, true, deadline.Token);
|
||||
if (!IsCurrent()) return;
|
||||
if (_learningSyncCore != core) { _learningSync.Reset(); _learningSyncCore = core; }
|
||||
await _learningSync.RunAsync(IsCurrent,
|
||||
async uploadToken =>
|
||||
{
|
||||
// A slow optional upload must leave budget for rule fetch.
|
||||
using var uploadDeadline = CancellationTokenSource.CreateLinkedTokenSource(uploadToken);
|
||||
uploadDeadline.CancelAfter(TimeSpan.FromSeconds(4));
|
||||
for (var count = 0; count < 10 && _observationQueue.TryPeek(out var pending); count++)
|
||||
{
|
||||
if (!IsCurrent()) return;
|
||||
if (pending.Token != token || Environment.TickCount64 - pending.Created > 5 * 60_000)
|
||||
{ _observationQueue.TryDequeue(out _); continue; }
|
||||
try { await _api.ReportObservationAsync(token, pending.Observation, uploadDeadline.Token); }
|
||||
catch (ApiException error) when (error.StatusCode == 400)
|
||||
{ if (IsCurrent()) _observationQueue.TryDequeue(out _); continue; }
|
||||
if (!IsCurrent()) return;
|
||||
_observationQueue.TryDequeue(out _);
|
||||
}
|
||||
},
|
||||
fetchToken => _api.GetRoutingRulesAsync(token, fetchToken),
|
||||
async (manifest, applyToken) =>
|
||||
{
|
||||
if (!IsCurrent()) return false;
|
||||
await _xray.CacheLearningCandidatesAsync(manifest, core!.Value, applyToken);
|
||||
return IsCurrent();
|
||||
},
|
||||
(acceptedRevision, ackToken) => _api.AcknowledgeRoutingAsync(token, acceptedRevision, true, ackToken),
|
||||
deadline.Token, message => AppPaths.WriteLog(message));
|
||||
}
|
||||
catch (Exception error) { AppPaths.WriteLog("学习同步暂未完成(本机路径验证独立运行,保留原连接):" + error.GetType().Name
|
||||
+ (error is ApiException apiError ? " status=" + apiError.StatusCode : "")); }
|
||||
catch (ApiException error) when (error.StatusCode is 401 or 403)
|
||||
{
|
||||
if (!IsCurrent()) return;
|
||||
await DisconnectAsync();
|
||||
if (SessionOperationFence.IsCurrent(revision, _sessionRevision, token, _accessToken, _exiting))
|
||||
await HandleSessionInvalidAsync();
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
catch (Exception error) { if (IsCurrent()) AppPaths.WriteLog("learning.sync.local_failure type=" + error.GetType().Name); }
|
||||
finally { _learningSyncing = false; }
|
||||
}
|
||||
|
||||
@@ -839,13 +901,18 @@ internal sealed partial class MainForm : Form
|
||||
private async Task RefreshProfileAsync(bool silent)
|
||||
{
|
||||
if (_busy || string.IsNullOrWhiteSpace(_accessToken)) return;
|
||||
var sessionToken = _accessToken;
|
||||
var sessionRevision = _sessionRevision;
|
||||
bool IsCurrent() => SessionOperationFence.IsCurrent(sessionRevision, _sessionRevision, sessionToken, _accessToken, _exiting);
|
||||
try
|
||||
{
|
||||
var profile = await _api.GetProfileAsync(_accessToken, _lifetime.Token);
|
||||
var profile = await _api.GetProfileAsync(sessionToken, _lifetime.Token);
|
||||
if (!IsCurrent() || _busy) return;
|
||||
UpdateProfile(profile, preserveSelections: true);
|
||||
if (_currentNodeIsPrivateAuxiliary && !_privateAuxiliaryNodes.Any(n => n.Slug == _currentNodeSlug))
|
||||
{
|
||||
await DisconnectAsync();
|
||||
if (!IsCurrent()) return;
|
||||
_statusDetail.Text = "私有节点授权已撤回,连接已断开。";
|
||||
}
|
||||
else if (_currentNodeIsPrivateAuxiliary && _xray.CoreId is { } privateCore && !_busy && !_handoverOperating
|
||||
@@ -854,14 +921,18 @@ internal sealed partial class MainForm : Form
|
||||
var grant = PrivateAuxiliaryRouting.ForRenewal(
|
||||
_privateAuxiliaryNodes.Single(n => n.Slug == _currentNodeSlug),
|
||||
_currentPrivateEndpoint ?? throw new InvalidOperationException("当前私有节点入口记录缺失。"));
|
||||
var renewed = await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, grant, privateRoute.Id, _lifetime.Token);
|
||||
var renewed = await _api.GetPrivateAuxiliaryConfigAsync(sessionToken, grant, privateRoute.Id, _lifetime.Token);
|
||||
if (!IsCurrent()) return;
|
||||
if (_currentNodeIsPrivateAuxiliary && _xray.CoreId == privateCore)
|
||||
{
|
||||
if (await _xray.RenewPrivateAuthorizationAsync(renewed.GetRuntimeConfigJson(), privateCore, _lifetime.Token))
|
||||
var accepted = await _xray.RenewPrivateAuthorizationAsync(renewed.GetRuntimeConfigJson(), privateCore, _lifetime.Token);
|
||||
if (!IsCurrent() || _xray.CoreId != privateCore) return;
|
||||
if (accepted)
|
||||
_privateLeaseDeadlineTicks = Environment.TickCount64 + Math.Max(0, (long)(renewed.ConfigExpiresAt!.Value - DateTimeOffset.UtcNow).TotalMilliseconds);
|
||||
else
|
||||
{
|
||||
await DisconnectAsync();
|
||||
if (!IsCurrent()) return;
|
||||
_statusDetail.Text = "私有节点凭据或配置已变更,请重新连接。";
|
||||
}
|
||||
}
|
||||
@@ -869,11 +940,14 @@ internal sealed partial class MainForm : Form
|
||||
}
|
||||
catch (ApiException exception) when (exception.StatusCode is 401 or 403)
|
||||
{
|
||||
if (!IsCurrent()) return;
|
||||
await DisconnectAsync();
|
||||
if (!IsCurrent()) return;
|
||||
await HandleSessionInvalidAsync();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
if (!IsCurrent()) return;
|
||||
AppPaths.WriteError(exception);
|
||||
if (!silent)
|
||||
{
|
||||
@@ -902,7 +976,7 @@ internal sealed partial class MainForm : Form
|
||||
finally
|
||||
{
|
||||
TokenStore.Clear();
|
||||
_accessToken = null;
|
||||
SetSessionToken(null);
|
||||
SetBusy(false);
|
||||
ShowLogin();
|
||||
}
|
||||
@@ -911,7 +985,7 @@ internal sealed partial class MainForm : Form
|
||||
private Task HandleSessionInvalidAsync()
|
||||
{
|
||||
TokenStore.Clear();
|
||||
_accessToken = null;
|
||||
SetSessionToken(null);
|
||||
ShowLogin("账号授权或订阅已失效,请重新登录或联系管理员。 ");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
@@ -1000,7 +1074,7 @@ internal sealed partial class MainForm : Form
|
||||
_statusTitle.Text = title;
|
||||
_statusTitle.ForeColor = connected ? Brand.Success : Brand.Text;
|
||||
_statusDetail.Text = detail;
|
||||
_connectButton.Text = connected ? "断开连接" : "连接";
|
||||
_connectButton.Text = _connectionAttemptCancellation is { IsCancellationRequested: false } ? "取消连接" : connected ? "断开连接" : "连接";
|
||||
_connectButton.BackColor = Brand.RoyalBlue;
|
||||
if (!connected) DisplayTraffic(null, null, "未连接 · 仅代理流量");
|
||||
_routeCombo.Enabled = !connected && !_busy;
|
||||
@@ -1021,7 +1095,10 @@ internal sealed partial class MainForm : Form
|
||||
_passwordText.ReadOnly = busy;
|
||||
_loginButton.Text = busy && _loginView.Visible ? status ?? "请稍候…" : "安全登录";
|
||||
_logoutButton.Enabled = !busy;
|
||||
_connectButton.Enabled = !busy && (_availableNodeCount > 0 || _wantConnected);
|
||||
_connectButton.Enabled = _connectionAttemptCancellation is { IsCancellationRequested: false }
|
||||
|| !busy && (_availableNodeCount > 0 || _wantConnected);
|
||||
if (_connectionAttemptCancellation is { IsCancellationRequested: false }) _connectButton.Text = "取消连接";
|
||||
else if (!busy) _connectButton.Text = _selectionUiConnected ? "断开连接" : "连接";
|
||||
RefreshSelectionControls();
|
||||
if (busy && _dashboardView.Visible && !string.IsNullOrWhiteSpace(status))
|
||||
{
|
||||
@@ -1062,7 +1139,7 @@ internal sealed partial class MainForm : Form
|
||||
}
|
||||
if (_uiOnly || _preview)
|
||||
{
|
||||
BeginExitCleanup();
|
||||
_ = BeginExitCleanup();
|
||||
CompleteExitResources();
|
||||
_exitCleanupCompleted = true;
|
||||
return;
|
||||
@@ -1176,9 +1253,13 @@ internal sealed partial class MainForm : Form
|
||||
var showItem = new ToolStripMenuItem("显示纵横家");
|
||||
var menu = new ContextMenuStrip();
|
||||
menu.Items.Add(showItem);
|
||||
menu.Items.Add(_tailnetReconnectItem);
|
||||
menu.Items.Add(new ToolStripSeparator());
|
||||
menu.Items.Add(exitItem);
|
||||
showItem.Click += (_, _) => ShowFromTray();
|
||||
_tailnetReconnectItem.Click += async (_, _) => await ReconnectThroughPreferredTailnetAsync();
|
||||
menu.Opening += (_, _) => _tailnetReconnectItem.Enabled = _tailnetReadiness.IsReady
|
||||
&& !_busy && !_exiting && _wantConnected && _xray.IsRunning && !_xray.UsesTailnet;
|
||||
exitItem.Click += (_, _) => RequestExit();
|
||||
var notify = new NotifyIcon
|
||||
{
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class NextGenerationSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
checks["same_live_session_accepts_result"] = SessionOperationFence.IsCurrent(3, 3, "fixture-a", "fixture-a", false);
|
||||
checks["older_login_rejects_success_even_with_reused_token"] = !SessionOperationFence.IsCurrent(2, 3, "fixture-a", "fixture-a", false);
|
||||
checks["old_account_cannot_apply_profile_or_clear_new_account"] = !SessionOperationFence.IsCurrent(3, 4, "fixture-a", "fixture-b", false);
|
||||
checks["changed_token_rejected_without_epoch_change"] = !SessionOperationFence.IsCurrent(3, 3, "fixture-a", "fixture-b", false);
|
||||
checks["logout_rejects_pending_profile"] = !SessionOperationFence.IsCurrent(3, 4, "fixture-a", null, false);
|
||||
checks["shutdown_rejects_pending_profile"] = !SessionOperationFence.IsCurrent(3, 3, "fixture-a", "fixture-a", true);
|
||||
checks["empty_session_never_valid"] = !SessionOperationFence.IsCurrent(3, 3, "", "", false);
|
||||
using (var form = new MainForm(preview: true, uiOnly: true))
|
||||
foreach (var check in form.CheckNextGenerationLifecycle()) checks.Add(check.Key, check.Value);
|
||||
var passed = checks.Values.All(v => v);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "nextgen-lifecycle-self-test.json"), JsonSerializer.Serialize(
|
||||
new { passed, checks, network_modified = false, credentials_loaded = false,
|
||||
scope = "synthetic lifecycle and owned WinForms controls; not installed-client acceptance" },
|
||||
new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 88;
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed partial class MainForm
|
||||
{
|
||||
internal Dictionary<string, bool> CheckNextGenerationLifecycle()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
SetSessionToken("fixture-a");
|
||||
var oldRevision = _sessionRevision;
|
||||
_observationQueue.Enqueue(("fixture-a", new LearningObservation(), Environment.TickCount64));
|
||||
SetSessionToken("fixture-b");
|
||||
checks["session_replacement_advances_epoch"] = _sessionRevision > oldRevision;
|
||||
checks["session_replacement_removes_old_credential_queue"] = _observationQueue.IsEmpty;
|
||||
checks["session_replacement_disables_overlay_reconnect_action"] = !_tailnetReconnectItem.Enabled;
|
||||
checks["old_refresh_fence_rejects_new_session"] = !SessionOperationFence.IsCurrent(oldRevision, _sessionRevision, "fixture-a", _accessToken, false);
|
||||
var currentRevision = _sessionRevision;
|
||||
SetSessionToken("fixture-b");
|
||||
checks["relogin_same_token_still_invalidates_old_operations"] = _sessionRevision > currentRevision;
|
||||
using var pending = new CancellationTokenSource();
|
||||
_connectionAttemptCancellation = pending;
|
||||
_availableNodeCount = 1;
|
||||
_wantConnected = true;
|
||||
SetBusy(true);
|
||||
checks["connecting_button_remains_cancellable"] = _connectButton.Enabled && _connectButton.Text == "取消连接";
|
||||
checks["explicit_cancel_is_accepted"] = TryCancelPendingConnection();
|
||||
checks["explicit_cancel_invalidates_attempt_token"] = pending.IsCancellationRequested;
|
||||
checks["explicit_cancel_does_not_leave_reconnect_intent"] = !_wantConnected;
|
||||
checks["cancel_waits_for_cleanup_before_reenable"] = !_connectButton.Enabled;
|
||||
_connectionAttemptCancellation = null;
|
||||
SetBusy(false);
|
||||
checks["button_returns_to_connect_after_cleanup"] = _connectButton.Enabled && _connectButton.Text == "连接";
|
||||
checks["no_attempt_cancel_is_noop"] = !TryCancelPendingConnection();
|
||||
using var oldAccountWork = new CancellationTokenSource();
|
||||
_connectionAttemptCancellation = oldAccountWork;
|
||||
SetSessionToken("fixture-c");
|
||||
checks["account_replacement_cancels_old_connection_work"] = oldAccountWork.IsCancellationRequested;
|
||||
_connectionAttemptCancellation = null;
|
||||
checks["readiness_does_not_fake_authenticated_transport"] = !_currentNodeUsesTailnet && !_tailnetReadiness.IsReady;
|
||||
checks["tray_action_explicitly_warns_connection_rebuild"] = _tailnetReconnectItem.Text.Contains("会重建连接");
|
||||
SetSessionToken(null);
|
||||
return checks;
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,83 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Contains only bounded identifiers and fixed reason codes, never config JSON,
|
||||
// credentials, exception messages, URLs, or a management access token.
|
||||
internal sealed record TransportDiagnostic(string Event, string Reason, string Node)
|
||||
{
|
||||
private static string Identifier(string value) => new(value.Take(100)
|
||||
.Select(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_' or '.' ? c : '_').ToArray());
|
||||
internal string SafeMessage => $"transport event={Identifier(Event)} reason={Identifier(Reason)} node={Identifier(Node)}";
|
||||
}
|
||||
|
||||
internal sealed class TailnetUnavailableException(string reason) : IOException("当前授权节点的 Tailscale 入口未通过验证。")
|
||||
{
|
||||
internal string Reason { get; } = reason;
|
||||
}
|
||||
|
||||
internal static class NodeTransportConnector
|
||||
{
|
||||
internal static async Task<string> RebindAsync(string current, string? original,
|
||||
Func<string, CancellationToken, Task> start, Func<Task> stop,
|
||||
Func<CancellationToken, Task<bool>> proxyHealth, CancellationToken token)
|
||||
Func<CancellationToken, Task<bool>> proxyHealth, CancellationToken token,
|
||||
string? preferredTailnetConfig = null, Action<string>? requireRoute = null,
|
||||
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null,
|
||||
Action<TransportDiagnostic>? diagnostic = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var tailnet = TailnetTransport.Address(current) is not null;
|
||||
if (tailnet && !TailnetTransport.SameAuthorizedFallback(current, original))
|
||||
throw new InvalidOperationException("缺少可验证的同节点原入口,未尝试切换。");
|
||||
var selected = current;
|
||||
var fallback = original;
|
||||
if (!tailnet && preferredTailnetConfig is not null)
|
||||
{
|
||||
// Only a confirmed physical-network recovery calls this method.
|
||||
// Re-check the cached alternate of this SAME authorized config; a
|
||||
// previous-network cooldown must not make public ingress sticky.
|
||||
if (!TailnetTransport.SameAuthorizedFallback(preferredTailnetConfig, current))
|
||||
throw new InvalidOperationException("Tailscale 恢复入口与当前授权线路不匹配。");
|
||||
if (requireRoute is null || endpointProbe is null)
|
||||
throw new InvalidOperationException("Tailscale 恢复入口缺少独立路由或端口验证。");
|
||||
var recheckReason = "route_unavailable";
|
||||
try
|
||||
{
|
||||
var address = TailnetTransport.Address(preferredTailnetConfig)!;
|
||||
requireRoute(address);
|
||||
token.ThrowIfCancellationRequested();
|
||||
recheckReason = "endpoint_unreachable";
|
||||
if (!await endpointProbe(address, TailnetTransport.Port(preferredTailnetConfig), token))
|
||||
diagnostic?.Invoke(new("rebind_skipped", "endpoint_unreachable", ""));
|
||||
else
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
selected = preferredTailnetConfig;
|
||||
fallback = current;
|
||||
tailnet = true;
|
||||
diagnostic?.Invoke(new("rebind_attempt", "tailnet_recovered", ""));
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is not OperationCanceledException && e is not LocalNetworkException)
|
||||
{ diagnostic?.Invoke(new("rebind_skipped", recheckReason, "")); }
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
if (tailnet) deadline.CancelAfter(TimeSpan.FromSeconds(45));
|
||||
try
|
||||
{
|
||||
await start(current, deadline.Token);
|
||||
await start(selected, deadline.Token);
|
||||
if (tailnet && !await proxyHealth(deadline.Token)) throw new IOException("Tailscale 切网后出口未通过。");
|
||||
deadline.Token.ThrowIfCancellationRequested();
|
||||
return current;
|
||||
diagnostic?.Invoke(new("rebind_selected", tailnet ? "tailnet_verified" : "public_ingress", ""));
|
||||
return selected;
|
||||
}
|
||||
catch (Exception e) when (tailnet && e is not LocalNetworkException && !token.IsCancellationRequested)
|
||||
{
|
||||
await stop(); // Full cleanup before same-node fallback; failure aborts.
|
||||
token.ThrowIfCancellationRequested();
|
||||
await start(original!, token);
|
||||
return original!;
|
||||
diagnostic?.Invoke(new("rebind_fallback", "proxy_health_or_start_failed", ""));
|
||||
await start(fallback!, token);
|
||||
token.ThrowIfCancellationRequested();
|
||||
return fallback!;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,10 +87,16 @@ internal static class NodeTransportConnector
|
||||
Func<string, CancellationToken, Task> start, Func<Task> stop, Func<CancellationToken, Task<bool>> proxyHealth,
|
||||
Action<string> requireRoute, Action<string> status, Func<long> ticks,
|
||||
CancellationToken token, bool allowKnownEndpoints = false,
|
||||
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null)
|
||||
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null,
|
||||
bool tailnetOnly = false, Action<TransportDiagnostic>? diagnostic = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var tailnet = preference.MayTry(response.Node.Slug, ticks()) ? TailnetTransport.TryPrepare(response, allowKnownEndpoints) : null;
|
||||
var reason = "cooldown_active";
|
||||
var tailnet = preference.MayTry(response.Node.Slug, ticks())
|
||||
? TailnetTransport.TryPrepare(response, out reason, allowKnownEndpoints) : null;
|
||||
void Report(string action, string code) => diagnostic?.Invoke(new(action, code, response.Node.Slug));
|
||||
if (tailnet is null) Report("tailnet_skipped", reason);
|
||||
else Report("tailnet_candidate", reason);
|
||||
if (tailnet is not null)
|
||||
{
|
||||
try
|
||||
@@ -48,7 +108,9 @@ internal static class NodeTransportConnector
|
||||
{
|
||||
preference.Failed(response.Node.Slug, ticks());
|
||||
tailnet = null;
|
||||
status("Tailscale 无独立内网路由,使用同一节点公网入口");
|
||||
reason = "route_unavailable";
|
||||
Report("tailnet_skipped", reason);
|
||||
status(tailnetOnly ? "Tailscale 无独立内网路由,继续检测其他授权内网节点" : "Tailscale 无独立内网路由,使用同一节点公网入口");
|
||||
}
|
||||
}
|
||||
if (tailnet is not null && endpointProbe is not null)
|
||||
@@ -64,7 +126,9 @@ internal static class NodeTransportConnector
|
||||
{
|
||||
preference.Failed(response.Node.Slug, ticks());
|
||||
tailnet = null;
|
||||
status("Tailscale 端口不可达,使用同一节点公网入口");
|
||||
reason = "endpoint_unreachable";
|
||||
Report("tailnet_skipped", reason);
|
||||
status(tailnetOnly ? "Tailscale 端口不可达,继续检测其他授权内网节点" : "Tailscale 端口不可达,使用同一节点公网入口");
|
||||
}
|
||||
}
|
||||
if (tailnet is not null)
|
||||
@@ -80,6 +144,7 @@ internal static class NodeTransportConnector
|
||||
// Plain TCP/ping, or a successful DIRECT smart request, is not proof.
|
||||
if (!await proxyHealth(deadline.Token)) throw new InvalidOperationException("Tailscale 代理出口验证失败。");
|
||||
deadline.Token.ThrowIfCancellationRequested();
|
||||
Report("selected", "tailnet_verified");
|
||||
return true;
|
||||
}
|
||||
catch (LocalNetworkException) { throw; }
|
||||
@@ -89,11 +154,18 @@ internal static class NodeTransportConnector
|
||||
preference.Failed(response.Node.Slug, ticks());
|
||||
// A failed restore must propagate: never stack a second connection.
|
||||
await stop();
|
||||
status("Tailscale 协议或代理出口验证失败,回退同一节点公网入口");
|
||||
reason = "proxy_health_or_start_failed";
|
||||
Report("tailnet_failed", reason);
|
||||
status(tailnetOnly ? "Tailscale 代理出口验证失败,继续检测其他授权内网节点" : "Tailscale 协议或代理出口验证失败,回退同一节点公网入口");
|
||||
}
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
// Automatic selection can test ALL authorized Tailnet nodes first. A
|
||||
// failed alternate must not launch public ingress before that pass ends.
|
||||
if (tailnetOnly) throw new TailnetUnavailableException(reason);
|
||||
Report("selected", "public_ingress");
|
||||
await start(response.GetRuntimeConfigJson(), token);
|
||||
token.ThrowIfCancellationRequested();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,17 @@ internal static class Program
|
||||
return PlatformBootstrapTransportSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--tailnet-transport-self-test")
|
||||
return TailnetTransportSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--public-tailnet-selection-self-test")
|
||||
return PublicTailnetSelectionSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--learning-sync-coordinator-self-test")
|
||||
return LearningSyncCoordinatorSelfTest.RunAsync().GetAwaiter().GetResult();
|
||||
if (args.Length == 1 && args[0] == "--tailnet-readiness-self-test")
|
||||
return TailnetReadinessSelfTest.Run();
|
||||
if (args.Length == 1 && args[0] == "--nextgen-lifecycle-self-test")
|
||||
{
|
||||
ApplicationConfiguration.Initialize();
|
||||
return NextGenerationSelfTest.Run();
|
||||
}
|
||||
if (args.Length == 2 && args[0] == "--tailnet-transport-probe")
|
||||
return TailnetTransportProbe.RunAsync(args[1]).GetAwaiter().GetResult();
|
||||
if (args.Any(a => a.StartsWith("--tailnet-transport-probe", StringComparison.OrdinalIgnoreCase))) return 82;
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Ranks only explicit public nodes from the current authenticated profile. This
|
||||
// is connection planning, not proof of proxy identity or permission to replace a
|
||||
// healthy core. The caller must still validate the selected proxy after start.
|
||||
internal static class PublicTailnetSelection
|
||||
{
|
||||
internal sealed record Candidate(ConfigResponse Response, long LatencyMilliseconds);
|
||||
private static readonly Regex ValidSlug = new("^[a-z0-9][a-z0-9-]{0,79}$", RegexOptions.CultureInvariant);
|
||||
|
||||
internal static async Task<IReadOnlyList<Candidate>> RankAsync(
|
||||
IEnumerable<NodeInfo> authorizedNodes, string routeMode,
|
||||
Func<string, bool> coolingDown,
|
||||
Func<string, CancellationToken, Task<ConfigResponse>> loadConfig,
|
||||
Func<string, int, CancellationToken, Task<bool>> endpointProbe,
|
||||
CancellationToken token, bool allowKnownEndpoints = false,
|
||||
Action<string, string>? diagnostic = null, TimeSpan? budget = null)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (routeMode is not ("smart" or "global")) return [];
|
||||
// Snapshot before asynchronous work: profile/cooldown state belongs to
|
||||
// the caller, and private grants must never become public dispatch.
|
||||
var nodes = authorizedNodes.Where(n => n is not null && n is not PrivateAuxiliaryNode
|
||||
&& n.Slug is not null && n.Slug != "auto" && ValidSlug.IsMatch(n.Slug))
|
||||
.DistinctBy(n => n.Slug, StringComparer.Ordinal)
|
||||
.Where(n => !coolingDown(n.Slug)).Take(8).ToArray();
|
||||
if (nodes.Length == 0) return [];
|
||||
|
||||
var milliseconds = Math.Clamp((budget ?? TimeSpan.FromSeconds(15)).TotalMilliseconds, 1, 15_000);
|
||||
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
deadline.CancelAfter(TimeSpan.FromMilliseconds(milliseconds));
|
||||
using var slots = new SemaphoreSlim(3, 3);
|
||||
ApiException? authorizationFailure = null;
|
||||
|
||||
void Report(string slug, string reason)
|
||||
{
|
||||
// Fixed reason codes only, never exception messages or config JSON.
|
||||
if (!Regex.IsMatch(reason, "^[a-z0-9_]{1,80}$", RegexOptions.CultureInvariant)) reason = "metadata_rejected";
|
||||
try { diagnostic?.Invoke(slug, reason); } catch { /* Telemetry cannot alter connection planning. */ }
|
||||
}
|
||||
|
||||
async Task<(Candidate Candidate, int Index)?> Read(NodeInfo node, int index)
|
||||
{
|
||||
var entered = false;
|
||||
try
|
||||
{
|
||||
await slots.WaitAsync(deadline.Token).ConfigureAwait(false);
|
||||
entered = true;
|
||||
// WaitAsync also bounds a buggy callback that ignores its token.
|
||||
var response = await loadConfig(node.Slug, deadline.Token).WaitAsync(deadline.Token).ConfigureAwait(false);
|
||||
deadline.Token.ThrowIfCancellationRequested();
|
||||
if (response?.Node is null || !string.Equals(response.Node.Slug, node.Slug, StringComparison.Ordinal))
|
||||
{ Report(node.Slug, "response_node_mismatch"); return null; }
|
||||
if (!string.Equals(response.RouteMode, routeMode, StringComparison.Ordinal))
|
||||
{ Report(node.Slug, "response_route_mismatch"); return null; }
|
||||
var prepared = TailnetTransport.TryPrepare(response, out var reason, allowKnownEndpoints);
|
||||
if (prepared is null) { Report(node.Slug, reason); return null; }
|
||||
var address = TailnetTransport.Address(prepared);
|
||||
var port = TailnetTransport.Port(prepared);
|
||||
if (address is null || port is < 1 or > 65535)
|
||||
{ Report(node.Slug, "prepared_endpoint_invalid"); return null; }
|
||||
|
||||
using var probeDeadline = CancellationTokenSource.CreateLinkedTokenSource(deadline.Token);
|
||||
probeDeadline.CancelAfter(TimeSpan.FromSeconds(3));
|
||||
var elapsed = Stopwatch.StartNew();
|
||||
var available = await endpointProbe(address, port, probeDeadline.Token)
|
||||
.WaitAsync(probeDeadline.Token).ConfigureAwait(false);
|
||||
probeDeadline.Token.ThrowIfCancellationRequested();
|
||||
if (!available) { Report(node.Slug, "endpoint_unreachable"); return null; }
|
||||
Report(node.Slug, "endpoint_reachable");
|
||||
return (new Candidate(response, Math.Max(0, elapsed.ElapsedMilliseconds)), index);
|
||||
}
|
||||
catch (ApiException error) when (error.StatusCode is 401 or 403)
|
||||
{
|
||||
// Never turn expired/revoked authorization into another node or
|
||||
// public fallback. Cancel sibling work, then propagate unchanged.
|
||||
Interlocked.CompareExchange(ref authorizationFailure, error, null);
|
||||
deadline.Cancel();
|
||||
Report(node.Slug, "authorization_rejected");
|
||||
return null;
|
||||
}
|
||||
catch (OperationCanceledException) when (!token.IsCancellationRequested)
|
||||
{ Report(node.Slug, "selection_or_probe_deadline"); return null; }
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception)
|
||||
{ Report(node.Slug, "config_or_probe_unavailable"); return null; }
|
||||
finally { if (entered) slots.Release(); }
|
||||
}
|
||||
|
||||
var readings = await Task.WhenAll(nodes.Select(Read)).ConfigureAwait(false);
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (authorizationFailure is not null) ExceptionDispatchInfo.Capture(authorizationFailure).Throw();
|
||||
return readings.Where(r => r is not null).Select(r => r!.Value)
|
||||
.OrderBy(r => r.Candidate.LatencyMilliseconds).ThenBy(r => r.Index)
|
||||
.Select(r => r.Candidate).ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class PublicTailnetSelectionSelfTest
|
||||
{
|
||||
internal static async Task<int> RunAsync()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
ConfigResponse Config(string slug, string route = "smart", string scope = "public")
|
||||
{
|
||||
var fixture = JsonNode.Parse("""
|
||||
{"config_contract":2,"connection_scope":"public","node":{"slug":"fixture"},"route_mode":"smart",
|
||||
"tailscale_endpoint":{"contract":1,"node_slug":"fixture","address":"100.64.0.2","port":10803},
|
||||
"config":{"inbounds":[],"outbounds":[{"tag":"proxy","protocol":"vless",
|
||||
"settings":{"vnext":[{"address":"fixture.example.com","port":11082,"users":[{"id":"fixture-id"}]}]},
|
||||
"streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"fixture.example.com","publicKey":"fixture-key"}}}],
|
||||
"routing":{"rules":[]}}}
|
||||
""")!;
|
||||
fixture["connection_scope"] = scope;
|
||||
fixture["node"]!["slug"] = slug;
|
||||
fixture["route_mode"] = route;
|
||||
fixture["tailscale_endpoint"]!["node_slug"] = slug;
|
||||
return JsonSerializer.Deserialize<ConfigResponse>(fixture.ToJsonString())!;
|
||||
}
|
||||
NodeInfo Node(string slug) => new() { Slug = slug };
|
||||
var requested = new ConcurrentQueue<string>();
|
||||
var loaded = new ConcurrentDictionary<string, ConfigResponse>();
|
||||
Task<ConfigResponse> Load(string slug, CancellationToken _)
|
||||
{ requested.Enqueue(slug); var response = Config(slug); loaded[slug] = response; return Task.FromResult(response); }
|
||||
Task<bool> Reachable(string _, int __, CancellationToken ___) => Task.FromResult(true);
|
||||
var candidates = await PublicTailnetSelection.RankAsync(
|
||||
new[] { Node("node-a"), Node("node-a"), new PrivateAuxiliaryNode { Slug = "private-a" }, Node("auto"), Node("bad slug"), Node("cooling") }
|
||||
.Concat(Enumerable.Range(0, 12).Select(i => Node("node-" + i))),
|
||||
"smart", slug => slug == "cooling", Load, Reachable, CancellationToken.None);
|
||||
checks["at_most_eight_distinct_authorized_public_nodes"] = requested.Count == 8 && requested.Distinct().Count() == 8 && candidates.Count == 8;
|
||||
checks["private_auto_invalid_and_cooldown_not_fetched"] = !requested.Intersect(new[] { "private-a", "auto", "bad slug", "cooling" }).Any();
|
||||
checks["cached_response_not_refetched"] = candidates.All(c => ReferenceEquals(c.Response, loaded[c.Response.Node.Slug]));
|
||||
|
||||
requested.Clear();
|
||||
var pending = new Dictionary<string, TaskCompletionSource<bool>>();
|
||||
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
// Unique endpoint ports allow deterministic completion ordering without
|
||||
// actual sockets, route inspection or millisecond timing assumptions.
|
||||
var rankedNodes = new[] { Node("slow"), Node("fast"), Node("medium") };
|
||||
var portSlugs = new Dictionary<int, string> { [10803] = "slow", [10804] = "fast", [10805] = "medium" };
|
||||
foreach (var node in rankedNodes) pending[node.Slug] = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var ranking = PublicTailnetSelection.RankAsync(rankedNodes, "smart", _ => false,
|
||||
(slug, _) => Task.FromResult(JsonSerializer.Deserialize<ConfigResponse>(JsonSerializer.Serialize(Config(slug))
|
||||
.Replace("10803", (10803 + Array.FindIndex(rankedNodes, n => n.Slug == slug)).ToString()))!),
|
||||
(_, port, _) => Probe(port), CancellationToken.None);
|
||||
async Task<bool> Probe(int port)
|
||||
{
|
||||
var task = pending[portSlugs[port]].Task;
|
||||
if (port == 10805) entered.TrySetResult();
|
||||
return await task;
|
||||
}
|
||||
await entered.Task.WaitAsync(TimeSpan.FromSeconds(1));
|
||||
await Task.Delay(20);
|
||||
pending["fast"].SetResult(true);
|
||||
await Task.Delay(35);
|
||||
pending["medium"].SetResult(true);
|
||||
await Task.Delay(35);
|
||||
pending["slow"].SetResult(true);
|
||||
candidates = await ranking;
|
||||
checks["reachable_endpoints_rank_by_probe_latency"] = candidates.Select(c => c.Response.Node.Slug).SequenceEqual(new[] { "fast", "medium", "slow" });
|
||||
|
||||
var diagnostics = new ConcurrentQueue<string>(); var probes = 0;
|
||||
candidates = await PublicTailnetSelection.RankAsync(new[] { Node("wrong-node"), Node("wrong-route"), Node("private-scope"), Node("unreachable"), Node("broken") },
|
||||
"smart", _ => false, (slug, _) => slug switch {
|
||||
"wrong-node" => Task.FromResult(Config("some-other-node")),
|
||||
"wrong-route" => Task.FromResult(Config(slug, "global")),
|
||||
"private-scope" => Task.FromResult(Config(slug, scope: "private_auxiliary")),
|
||||
"broken" => Task.FromException<ConfigResponse>(new IOException("secret-config-body")),
|
||||
_ => Task.FromResult(Config(slug)) },
|
||||
(_, _, _) => { Interlocked.Increment(ref probes); return Task.FromResult(false); }, CancellationToken.None,
|
||||
diagnostic: (_, reason) => diagnostics.Enqueue(reason));
|
||||
checks["wrong_slug_route_and_private_scope_rejected_before_probe"] = candidates.Count == 0 && probes == 1
|
||||
&& diagnostics.Contains("response_node_mismatch") && diagnostics.Contains("response_route_mismatch");
|
||||
checks["diagnostics_never_include_exception_body"] = !diagnostics.Any(d => d.Contains("secret", StringComparison.Ordinal));
|
||||
|
||||
probes = 0;
|
||||
candidates = await PublicTailnetSelection.RankAsync([Node("disabled")], "smart", _ => false,
|
||||
(slug, _) => {
|
||||
var fixture = JsonNode.Parse(JsonSerializer.Serialize(Config(slug)))!;
|
||||
fixture["tailscale_endpoint"] = null;
|
||||
return Task.FromResult(JsonSerializer.Deserialize<ConfigResponse>(fixture.ToJsonString())!);
|
||||
}, (_, _, _) => { probes++; return Task.FromResult(true); }, CancellationToken.None,
|
||||
allowKnownEndpoints: true);
|
||||
checks["explicit_null_metadata_never_probed"] = candidates.Count == 0 && probes == 0;
|
||||
candidates = await PublicTailnetSelection.RankAsync([Node("missing"), Node("good")], "smart", _ => false,
|
||||
(slug, _) => slug == "missing" ? Task.FromException<ConfigResponse>(new ApiException(404, "fixture missing")) : Task.FromResult(Config(slug)),
|
||||
Reachable, CancellationToken.None);
|
||||
checks["per_node_404_keeps_other_authorized_candidate"] = candidates.Count == 1 && candidates[0].Response.Node.Slug == "good";
|
||||
|
||||
foreach (var status in new[] { 401, 403 })
|
||||
{
|
||||
ApiException? observed = null;
|
||||
var expected = new ApiException(status, "fixture rejected");
|
||||
try { await PublicTailnetSelection.RankAsync(new[] { Node("denied"), Node("other") }, "smart", _ => false,
|
||||
(slug, _) => slug == "denied" ? Task.FromException<ConfigResponse>(expected) : Task.FromResult(Config(slug)),
|
||||
Reachable, CancellationToken.None); }
|
||||
catch (ApiException error) { observed = error; }
|
||||
checks["authorization_" + status + "_propagates_same_exception"] = ReferenceEquals(observed, expected);
|
||||
}
|
||||
|
||||
using (var cancelled = new CancellationTokenSource())
|
||||
{
|
||||
cancelled.Cancel(); var called = false; var cancellationObserved = false;
|
||||
try { await PublicTailnetSelection.RankAsync([Node("node")], "smart", _ => false,
|
||||
(_, _) => { called = true; return Task.FromResult(Config("node")); }, Reachable, cancelled.Token); }
|
||||
catch (OperationCanceledException) { cancellationObserved = true; }
|
||||
checks["pre_cancelled_caller_does_not_fetch"] = cancellationObserved && !called;
|
||||
}
|
||||
using (var cancelled = new CancellationTokenSource())
|
||||
{
|
||||
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var operation = PublicTailnetSelection.RankAsync([Node("node")], "smart", _ => false,
|
||||
async (_, token) => { started.SetResult(); await Task.Delay(Timeout.Infinite, token); return Config("node"); },
|
||||
Reachable, cancelled.Token);
|
||||
await started.Task.WaitAsync(TimeSpan.FromSeconds(1)); cancelled.Cancel();
|
||||
var cancellationObserved = false;
|
||||
try { await operation; } catch (OperationCanceledException) { cancellationObserved = true; }
|
||||
checks["inflight_caller_cancellation_propagates"] = cancellationObserved;
|
||||
}
|
||||
|
||||
var never = new TaskCompletionSource<ConfigResponse>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
candidates = await PublicTailnetSelection.RankAsync([Node("node")], "smart", _ => false,
|
||||
(_, _) => never.Task, Reachable, CancellationToken.None, budget: TimeSpan.FromMilliseconds(30));
|
||||
checks["deadline_bounds_callback_ignoring_token"] = candidates.Count == 0;
|
||||
requested.Clear();
|
||||
candidates = await PublicTailnetSelection.RankAsync([Node("node")], "direct", _ => false, Load, Reachable, CancellationToken.None);
|
||||
checks["direct_mode_never_probes_or_fetches"] = candidates.Count == 0 && requested.Count == 0;
|
||||
|
||||
var active = 0; var maximum = 0;
|
||||
candidates = await PublicTailnetSelection.RankAsync(Enumerable.Range(0, 8).Select(i => Node("parallel-" + i)), "smart", _ => false,
|
||||
async (slug, token) => {
|
||||
var current = Interlocked.Increment(ref active);
|
||||
lock (checks) maximum = Math.Max(maximum, current);
|
||||
try { await Task.Delay(15, token); return Config(slug); }
|
||||
finally { Interlocked.Decrement(ref active); }
|
||||
}, Reachable, CancellationToken.None);
|
||||
checks["at_most_three_parallel_fetches"] = candidates.Count == 8 && maximum is > 1 and <= 3;
|
||||
var report = new { passed = checks.Values.All(v => v), checks, simulated_transport = true, network_modified = false,
|
||||
note = "Fake config/probe callbacks only. TCP availability is selection evidence, not authenticated proxy acceptance." };
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "public-tailnet-selection-self-test.json"), JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
|
||||
return report.passed ? 0 : 83;
|
||||
}
|
||||
}
|
||||
+3
-5
@@ -1,6 +1,6 @@
|
||||
# 纵横家 Windows 0.2.23 开源源码
|
||||
# 纵横家 Windows 0.3.0 开源源码
|
||||
|
||||
基于已冻结的 0.2.23 r2 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
基于已冻结的 0.3.0 r1 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
|
||||
|
||||
## 构建
|
||||
|
||||
@@ -17,6 +17,4 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
|
||||
|
||||
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
|
||||
|
||||
本次只同步Windows界面维护代码:滚动/刷新、托盘与透明卡片。清洁导出继续省略可选登录人物插图,使用已有原创山水fallback;未重新导出或修改其它平台。安装包发布证据不能转移为此脱敏源码的构建/真实网络验收。
|
||||
|
||||
新增条件 Tailscale 实时卡,内网左二右一,公网隐藏;仅已有代理总量分项,不重复累计。源码仍省略许可不明可选人物插图。
|
||||
本次 0.3.0 同步连接排序与内网恢复提示、可取消连接、会话代际及学习同步退避、固定高度单页与实时速度显示。内网恢复不静默中断长连接;需要明确重连。此清洁源码以原创山水替代许可不明的可选人物插图,真实内部端点替换为示例。原安装包测试结论不自动转移为此导出的网络或安装验收。
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// A reused account/token must not accept a response from an earlier login.
|
||||
// No credentials or session identifiers are persisted by this predicate.
|
||||
internal static class SessionOperationFence
|
||||
{
|
||||
internal static bool IsCurrent(long expectedRevision, long currentRevision,
|
||||
string? expectedToken, string? currentToken, bool exiting) => !exiting
|
||||
&& expectedRevision == currentRevision && !string.IsNullOrWhiteSpace(expectedToken)
|
||||
&& string.Equals(expectedToken, currentToken, StringComparison.Ordinal);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
// Advisory only: detects an available authorized alternate, never starts/stops a
|
||||
// core, changes routes, fetches grants, or turns a TCP result into proxy proof.
|
||||
// The caller owns the snapshot and performs one read-only probe per ticket.
|
||||
internal sealed class TailnetReadinessPolicy
|
||||
{
|
||||
internal readonly record struct Context(long Epoch, int? CoreId, bool Wanted,
|
||||
bool Busy, bool Running, bool UsesTailnet, bool HasAuthorizedCandidate);
|
||||
internal readonly record struct ProbeTicket(long Generation, long Sequence, long Epoch, int CoreId);
|
||||
internal enum Result { Ignore, NotReady, Confirming, BecameReady, Ready }
|
||||
|
||||
internal const long IntervalMilliseconds = 30_000;
|
||||
internal const long MaximumBackoffMilliseconds = 120_000;
|
||||
private bool _bound, _inFlight;
|
||||
private long _generation, _sequence, _epoch, _nextDue;
|
||||
private int? _core;
|
||||
private int _successes, _failures;
|
||||
internal bool IsReady { get; private set; }
|
||||
internal long NextDue => _nextDue;
|
||||
|
||||
internal void Reset()
|
||||
{
|
||||
_generation++;
|
||||
_bound = _inFlight = IsReady = false;
|
||||
_core = null;
|
||||
_nextDue = 0;
|
||||
_successes = _failures = 0;
|
||||
}
|
||||
|
||||
private static bool Eligible(Context context) => context.Wanted && context.Running
|
||||
&& context.CoreId is not null && !context.UsesTailnet && context.HasAuthorizedCandidate;
|
||||
|
||||
private void Synchronize(Context context)
|
||||
{
|
||||
if (!_bound || _epoch != context.Epoch || _core != context.CoreId)
|
||||
{
|
||||
Reset();
|
||||
_bound = true;
|
||||
_epoch = context.Epoch;
|
||||
_core = context.CoreId;
|
||||
}
|
||||
if (!Eligible(context) && (_inFlight || IsReady || _successes != 0 || _failures != 0))
|
||||
{
|
||||
// A grant withdrawal/disconnect must invalidate the outstanding
|
||||
// ticket even when the process ID has not changed yet.
|
||||
_generation++;
|
||||
_inFlight = IsReady = false;
|
||||
_nextDue = 0;
|
||||
_successes = _failures = 0;
|
||||
}
|
||||
}
|
||||
|
||||
internal bool TryBegin(Context context, long now, out ProbeTicket ticket)
|
||||
{
|
||||
ticket = default;
|
||||
Synchronize(context);
|
||||
if (!Eligible(context) || context.Busy || _inFlight || now < _nextDue) return false;
|
||||
_inFlight = true;
|
||||
ticket = new(_generation, ++_sequence, context.Epoch, context.CoreId!.Value);
|
||||
return true;
|
||||
}
|
||||
|
||||
internal Result Observe(ProbeTicket ticket, Context context, long now, bool reachable)
|
||||
{
|
||||
Synchronize(context);
|
||||
if (!_inFlight || ticket.Generation != _generation || ticket.Sequence != _sequence
|
||||
|| ticket.Epoch != context.Epoch || ticket.CoreId != context.CoreId || !Eligible(context))
|
||||
return Result.Ignore;
|
||||
_inFlight = false;
|
||||
_nextDue = now + IntervalMilliseconds;
|
||||
// Do not publish a result obtained while connection/authorization state
|
||||
// is being changed. A new ticket can retry after the normal cadence.
|
||||
if (context.Busy) return Result.Ignore;
|
||||
if (!reachable)
|
||||
{
|
||||
IsReady = false;
|
||||
_successes = 0;
|
||||
_failures = Math.Min(_failures + 1, 3);
|
||||
_nextDue = now + Math.Min(MaximumBackoffMilliseconds,
|
||||
IntervalMilliseconds * (1L << (_failures - 1)));
|
||||
return Result.NotReady;
|
||||
}
|
||||
_failures = 0;
|
||||
_successes = Math.Min(_successes + 1, 2);
|
||||
if (_successes < 2) return Result.Confirming;
|
||||
if (IsReady) return Result.Ready;
|
||||
IsReady = true;
|
||||
return Result.BecameReady;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace UCVL.VPNPlus;
|
||||
|
||||
internal static class TailnetReadinessSelfTest
|
||||
{
|
||||
internal static int Run()
|
||||
{
|
||||
var checks = new Dictionary<string, bool>();
|
||||
var policy = new TailnetReadinessPolicy();
|
||||
var current = new TailnetReadinessPolicy.Context(1, 10, true, false, true, false, true);
|
||||
bool Begin(long now, out TailnetReadinessPolicy.ProbeTicket ticket) => policy.TryBegin(current, now, out ticket);
|
||||
TailnetReadinessPolicy.Result Complete(TailnetReadinessPolicy.ProbeTicket ticket, long now, bool reachable)
|
||||
=> policy.Observe(ticket, current, now, reachable);
|
||||
checks["public_authorized_session_can_probe_without_physical_network_change"] = Begin(0, out var first);
|
||||
checks["no_concurrent_readiness_probe"] = !Begin(0, out _);
|
||||
checks["one_tcp_success_is_not_stable_readiness"] = Complete(first, 100, true) == TailnetReadinessPolicy.Result.Confirming && !policy.IsReady;
|
||||
var second = default(TailnetReadinessPolicy.ProbeTicket);
|
||||
checks["monotonic_thirty_second_cadence"] = !Begin(30_099, out _) && Begin(30_100, out second);
|
||||
checks["second_success_announces_readiness_once"] = Complete(second, 30_200, true) == TailnetReadinessPolicy.Result.BecameReady && policy.IsReady;
|
||||
checks["already_ready_probe_is_not_new_notification"] = Begin(60_200, out var third)
|
||||
&& Complete(third, 60_300, true) == TailnetReadinessPolicy.Result.Ready;
|
||||
checks["failed_probe_clears_ready_state"] = Begin(90_300, out var failed)
|
||||
&& Complete(failed, 90_400, false) == TailnetReadinessPolicy.Result.NotReady && !policy.IsReady;
|
||||
checks["first_failure_backoff_thirty_seconds"] = policy.NextDue == 120_400 && !Begin(120_399, out _);
|
||||
checks["second_failure_backoff_sixty_seconds"] = Begin(120_400, out failed)
|
||||
&& Complete(failed, 120_500, false) == TailnetReadinessPolicy.Result.NotReady && policy.NextDue == 180_500;
|
||||
checks["third_failure_backoff_bounded_two_minutes"] = Begin(180_500, out failed)
|
||||
&& Complete(failed, 180_600, false) == TailnetReadinessPolicy.Result.NotReady && policy.NextDue == 300_600;
|
||||
checks["failure_backoff_does_not_grow_unbounded"] = Begin(300_600, out failed)
|
||||
&& Complete(failed, 300_700, false) == TailnetReadinessPolicy.Result.NotReady && policy.NextDue == 420_700;
|
||||
checks["recovery_restarts_two_success_hysteresis"] = Begin(420_700, out first)
|
||||
&& Complete(first, 420_800, true) == TailnetReadinessPolicy.Result.Confirming
|
||||
&& Begin(450_800, out second) && Complete(second, 450_900, true) == TailnetReadinessPolicy.Result.BecameReady;
|
||||
|
||||
policy.Reset();
|
||||
checks["reset_invalidates_ticket"] = Complete(second, 500_000, true) == TailnetReadinessPolicy.Result.Ignore && !policy.IsReady;
|
||||
checks["fresh_session_can_probe_immediately"] = Begin(500_000, out first);
|
||||
current = current with { Epoch = 2 };
|
||||
checks["session_epoch_fences_late_success"] = Complete(first, 500_100, true) == TailnetReadinessPolicy.Result.Ignore && !policy.IsReady;
|
||||
checks["old_ticket_does_not_consume_new_ticket"] = Begin(500_200, out second)
|
||||
&& Complete(first, 500_300, true) == TailnetReadinessPolicy.Result.Ignore
|
||||
&& Complete(second, 500_400, true) == TailnetReadinessPolicy.Result.Confirming;
|
||||
checks["core_change_fences_old_ticket"] = Begin(530_400, out first)
|
||||
&& policy.Observe(first, current with { CoreId = 11 }, 530_500, true) == TailnetReadinessPolicy.Result.Ignore;
|
||||
current = current with { CoreId = 11 };
|
||||
checks["disconnect_fences_late_success"] = Begin(530_600, out first)
|
||||
&& policy.Observe(first, current with { Wanted = false }, 530_700, true) == TailnetReadinessPolicy.Result.Ignore;
|
||||
checks["grant_withdrawal_fences_late_success"] = Begin(530_800, out first)
|
||||
&& policy.Observe(first, current with { HasAuthorizedCandidate = false }, 530_900, true) == TailnetReadinessPolicy.Result.Ignore;
|
||||
checks["tailnet_connection_fences_old_public_probe"] = Begin(531_000, out first)
|
||||
&& policy.Observe(first, current with { UsesTailnet = true }, 531_100, true) == TailnetReadinessPolicy.Result.Ignore;
|
||||
checks["dead_core_fences_old_probe"] = Begin(531_200, out first)
|
||||
&& policy.Observe(first, current with { Running = false }, 531_300, true) == TailnetReadinessPolicy.Result.Ignore;
|
||||
checks["busy_session_does_not_start_probe"] = !policy.TryBegin(current with { Busy = true }, 531_400, out _);
|
||||
checks["busy_completion_is_ignored_not_announced"] = Begin(531_500, out first)
|
||||
&& policy.Observe(first, current with { Busy = true }, 531_600, true) == TailnetReadinessPolicy.Result.Ignore && !policy.IsReady;
|
||||
foreach (var state in new[] {
|
||||
current with { Wanted = false }, current with { CoreId = null }, current with { Running = false },
|
||||
current with { UsesTailnet = true }, current with { HasAuthorizedCandidate = false } })
|
||||
checks["ineligible_state_" + checks.Count] = !policy.TryBegin(state, 600_000, out _);
|
||||
|
||||
var passed = checks.Values.All(v => v);
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "tailnet-readiness-self-test.json"),
|
||||
JsonSerializer.Serialize(new { kind = "advisory_tailnet_readiness", network_modified = false,
|
||||
transport_switched = false, proxy_authenticated = false, checks, passed },
|
||||
new JsonSerializerOptions { WriteIndented = true }));
|
||||
return passed ? 0 : 84;
|
||||
}
|
||||
}
|
||||
@@ -17,18 +17,40 @@ internal static class TailnetTransport
|
||||
&& value is not ("100.100.100.100" or "100.64.0.0" or "100.127.255.255");
|
||||
|
||||
internal static string? TryPrepare(ConfigResponse response, bool allowKnownEndpoints = false)
|
||||
=> TryPrepare(response, out _, allowKnownEndpoints);
|
||||
|
||||
internal static string? TryPrepare(ConfigResponse response, out string reason, bool allowKnownEndpoints = false)
|
||||
{
|
||||
var endpoint = response.TailscaleEndpoint ?? KnownTailnetEndpoints.Resolve(response, allowKnownEndpoints);
|
||||
if (endpoint is null || endpoint.Contract != 1 || endpoint.NodeSlug != response.Node.Slug
|
||||
|| string.IsNullOrWhiteSpace(endpoint.NodeSlug) || !IsTailnetAddress(endpoint.Address)
|
||||
|| endpoint.Port is < 1 or > 65535 || response.ConfigContract != 2
|
||||
|| response.ConnectionScope is not ("" or "public") || response.RouteMode is not ("smart" or "global"))
|
||||
return null;
|
||||
reason = "explicit_endpoint";
|
||||
var endpoint = response.TailscaleEndpoint;
|
||||
if (endpoint is null)
|
||||
{
|
||||
if (response.HasTailscaleEndpoint) { reason = "explicit_endpoint_disabled"; return null; }
|
||||
endpoint = KnownTailnetEndpoints.Resolve(response, allowKnownEndpoints, out reason);
|
||||
if (endpoint is null) return null;
|
||||
}
|
||||
var source = reason;
|
||||
reason = "endpoint_contract_unsupported";
|
||||
if (endpoint.Contract != 1) return null;
|
||||
reason = "endpoint_node_mismatch";
|
||||
if (endpoint.NodeSlug != response.Node.Slug || string.IsNullOrWhiteSpace(endpoint.NodeSlug)) return null;
|
||||
reason = "endpoint_address_invalid";
|
||||
if (!IsTailnetAddress(endpoint.Address)) return null;
|
||||
reason = "endpoint_port_invalid";
|
||||
if (endpoint.Port is < 1 or > 65535) return null;
|
||||
reason = "config_contract_unsupported";
|
||||
if (response.ConfigContract != 2) return null;
|
||||
reason = "scope_unsupported";
|
||||
if (response.ConnectionScope is not ("" or "public")) return null;
|
||||
reason = "route_mode_unsupported";
|
||||
if (response.RouteMode is not ("smart" or "global")) return null;
|
||||
try
|
||||
{
|
||||
var root = JsonNode.Parse(response.GetRuntimeConfigJson())!.AsObject();
|
||||
reason = "config_scope_or_marker_invalid";
|
||||
if (PrivateAuxiliaryRuntime.IsPrivate(root) || root.ContainsKey(Marker)) return null;
|
||||
var proxy = Proxy(root);
|
||||
reason = "proxy_identity_unsupported";
|
||||
if (proxy is null) return null;
|
||||
var server = proxy["settings"]!["vnext"]![0]!.AsObject();
|
||||
// Preserve users/flow/encryption/Reality key/SNI/shortId and all rules.
|
||||
@@ -36,10 +58,11 @@ internal static class TailnetTransport
|
||||
server["address"] = endpoint.Address;
|
||||
server["port"] = endpoint.Port;
|
||||
root[Marker] = new JsonObject { ["address"] = endpoint.Address, ["port"] = endpoint.Port };
|
||||
reason = source;
|
||||
return root.ToJsonString();
|
||||
}
|
||||
catch (Exception e) when (e is System.Text.Json.JsonException or InvalidOperationException or FormatException)
|
||||
{ return null; } // Invalid optional metadata never breaks the original ingress.
|
||||
{ reason = "config_invalid"; return null; } // Invalid optional metadata never breaks the original ingress.
|
||||
}
|
||||
|
||||
internal static JsonObject? Proxy(JsonObject root)
|
||||
|
||||
@@ -246,6 +246,118 @@ internal static class TailnetTransportSelfTest
|
||||
selected = await NodeTransportConnector.ConnectAsync(Known(r=>r["tailscale_endpoint"]=null),new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None,
|
||||
allowKnownEndpoints:true, endpointProbe:(_,_,_)=>throw new InvalidOperationException("explicit null must not probe"));
|
||||
checks["explicit_disabled_transport_never_probed"] = !selected && starts.SequenceEqual(new[]{"vpn002.example.invalid"}) && probes == 0;
|
||||
|
||||
TailnetTransport.TryPrepare(Known(r=>r["tailscale_endpoint"]=null), out var skipReason, true);
|
||||
checks["diagnostic_explicit_null_is_not_missing_metadata"] = skipReason == "explicit_endpoint_disabled";
|
||||
TailnetTransport.TryPrepare(Known(r=>r["config_contract"]=1), out skipReason, true);
|
||||
checks["diagnostic_unknown_contract_preserves_rejection"] = skipReason == "config_contract_unsupported";
|
||||
TailnetTransport.TryPrepare(Known(r=>r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"]="other.example.com"), out skipReason, true);
|
||||
checks["diagnostic_known_ingress_mismatch_is_distinct"] = skipReason == "known_original_ingress_mismatch";
|
||||
TailnetTransport.TryPrepare(known, out skipReason, true);
|
||||
checks["diagnostic_compatibility_source_identified"] = skipReason == "known_endpoint";
|
||||
var diagnostics = new List<TransportDiagnostic>();
|
||||
starts.Clear(); beforeStops=stops;
|
||||
var tailnetFailure = "";
|
||||
try
|
||||
{
|
||||
await NodeTransportConnector.ConnectAsync(known,new(),Start,Stop,Healthy,Route,_=>{},()=>tick,CancellationToken.None,
|
||||
allowKnownEndpoints:true, endpointProbe:(_,_,_)=>Task.FromResult(false), tailnetOnly:true, diagnostic:diagnostics.Add);
|
||||
}
|
||||
catch (TailnetUnavailableException failure) { tailnetFailure = failure.Reason; }
|
||||
checks["internal_first_closed_port_never_starts_public"] = tailnetFailure == "endpoint_unreachable" && starts.Count==0 && stops==beforeStops;
|
||||
checks["diagnostics_persist_specific_probe_failure"] = diagnostics.Any(d=>d.Event=="tailnet_skipped" && d.Reason=="endpoint_unreachable" && d.Node==known.Node.Slug);
|
||||
starts.Clear(); diagnostics.Clear(); beforeStops=stops;
|
||||
checks["internal_first_failed_auth_cleans_up_before_other_node"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(known,new(),Start,Stop,
|
||||
_=>Task.FromResult(false),Route,_=>{},()=>tick,CancellationToken.None,allowKnownEndpoints:true,
|
||||
endpointProbe:(_,_,_)=>Task.FromResult(true),tailnetOnly:true,diagnostic:diagnostics.Add))
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2"}) && stops==beforeStops+1
|
||||
&& !diagnostics.Any(d=>d.Reason=="public_ingress");
|
||||
starts.Clear(); diagnostics.Clear();
|
||||
var heldPreference = new TailnetPreference(); heldPreference.Failed(known.Node.Slug,tick);
|
||||
checks["internal_first_cooldown_never_starts_public"] = await ThrowsAsync(()=>NodeTransportConnector.ConnectAsync(known,heldPreference,Start,Stop,Healthy,
|
||||
Route,_=>{},()=>tick+1,CancellationToken.None,allowKnownEndpoints:true,tailnetOnly:true,diagnostic:diagnostics.Add))
|
||||
&& starts.Count==0 && diagnostics.Single().Reason=="cooldown_active";
|
||||
var safeDiagnostic = new TransportDiagnostic("selected\nconfig", "SYNTHETIC_SECRET?\r\n", new string('n',120)).SafeMessage;
|
||||
checks["diagnostics_line_and_identifier_bounded"] = !safeDiagnostic.Contains('\n') && !safeDiagnostic.Contains('\r') && !safeDiagnostic.Contains('?') && safeDiagnostic.Length<260;
|
||||
|
||||
starts.Clear(); beforeStops=stops; probes=0; preflights=0; routeReads=0; diagnostics.Clear();
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>{preflights++;return Task.FromResult(true);},diagnostic:diagnostics.Add);
|
||||
checks["handover_public_rechecks_authorized_tailnet"] = rebound==prepared && starts.SequenceEqual(new[]{"100.64.0.2"})
|
||||
&& stops==beforeStops && preflights==1 && routeReads==1 && probes==1;
|
||||
checks["handover_promotion_requires_verified_exit"] = diagnostics.Any(d=>d.Event=="rebind_selected" && d.Reason=="tailnet_verified");
|
||||
starts.Clear(); beforeStops=stops; probes=0;
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(false));
|
||||
checks["handover_unreachable_alternate_keeps_public_without_replacement_attempt"] = rebound==original
|
||||
&& starts.SequenceEqual(new[]{"vpn002.example.invalid"}) && stops==beforeStops && probes==0;
|
||||
starts.Clear(); beforeStops=stops;
|
||||
rebound = await NodeTransportConnector.RebindAsync(original,null,Start,Stop,_=>Task.FromResult(false),CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true));
|
||||
checks["handover_promotion_failure_same_node_cleanup_fallback"] = rebound==original
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2","vpn002.example.invalid"}) && stops==beforeStops+1;
|
||||
starts.Clear();
|
||||
checks["handover_forged_preferred_credentials_rejected_before_start"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared.Replace("fixture-key","different-key"),requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))) && starts.Count==0;
|
||||
checks["handover_promotion_without_probe_rejected"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,CancellationToken.None,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route)) && starts.Count==0;
|
||||
checks["handover_preferred_cancellation_does_not_start_any_path"] = await ThrowsAsync(()=>NodeTransportConnector.RebindAsync(original,null,Start,Stop,Healthy,cancel.Token,
|
||||
preferredTailnetConfig:prepared,requireRoute:Route,endpointProbe:(_,_,_)=>Task.FromResult(true))) && starts.Count==0;
|
||||
|
||||
// Exercise the actual public ranker + connector as one offline sequence:
|
||||
// socket availability is ordering evidence, never proxy-health proof.
|
||||
var rankedResponses = new Dictionary<string,ConfigResponse> {
|
||||
["tokyo"] = response,
|
||||
["silicon"] = Sample(r=> {
|
||||
r["node"]!["slug"]="silicon";
|
||||
r["tailscale_endpoint"]!["node_slug"]="silicon";
|
||||
r["tailscale_endpoint"]!["address"]="100.64.0.3";
|
||||
r["tailscale_endpoint"]!["port"]=11083;
|
||||
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["address"]="vpn003.example.invalid";
|
||||
r["config"]!["outbounds"]![0]!["settings"]!["vnext"]![0]!["port"]=11083;
|
||||
})
|
||||
};
|
||||
var rankedCandidates = await PublicTailnetSelection.RankAsync(rankedResponses.Values.Select(r=>r.Node),"smart",_=>false,
|
||||
(slug,_)=>Task.FromResult(rankedResponses[slug]),async (address,_,ct)=> {
|
||||
if(address=="100.64.0.3") await Task.Delay(20,ct);
|
||||
return true;
|
||||
},CancellationToken.None);
|
||||
checks["integration_ranker_keeps_both_authorized_endpoints"] = rankedCandidates.Count==2
|
||||
&& rankedCandidates[0].Response.Node.Slug=="tokyo" && rankedCandidates[1].Response.Node.Slug=="silicon";
|
||||
starts.Clear(); beforeStops=stops;
|
||||
var rankedPreference = new TailnetPreference();
|
||||
var connectedSecond = false;
|
||||
foreach(var rankedCandidate in rankedCandidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
connectedSecond = await NodeTransportConnector.ConnectAsync(rankedCandidate.Response,rankedPreference,Start,Stop,
|
||||
_=>Task.FromResult(starts.LastOrDefault()=="100.64.0.3"),Route,_=>{},()=>tick,CancellationToken.None,
|
||||
endpointProbe:(_,_,_)=>Task.FromResult(true),tailnetOnly:true);
|
||||
if(connectedSecond) break;
|
||||
}
|
||||
catch(TailnetUnavailableException) { /* MainForm continues the inner pass, not a node penalty. */ }
|
||||
}
|
||||
checks["integration_protocol_failure_tries_next_internal_before_public"] = connectedSecond
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2","100.64.0.3"}) && stops==beforeStops+1;
|
||||
checks["integration_transport_failure_does_not_cool_other_node"] = !rankedPreference.MayTry("tokyo",tick+1)
|
||||
&& rankedPreference.MayTry("silicon",tick+1);
|
||||
starts.Clear(); beforeStops=stops; rankedPreference=new();
|
||||
var unavailableCandidates=0;
|
||||
foreach(var rankedCandidate in rankedCandidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
await NodeTransportConnector.ConnectAsync(rankedCandidate.Response,rankedPreference,Start,Stop,_=>Task.FromResult(false),
|
||||
Route,_=>{},()=>tick,CancellationToken.None,endpointProbe:(_,_,_)=>Task.FromResult(true),tailnetOnly:true);
|
||||
}
|
||||
catch(TailnetUnavailableException) { unavailableCandidates++; }
|
||||
}
|
||||
checks["integration_all_internal_fail_without_early_public_start"] = unavailableCandidates==2
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2","100.64.0.3"}) && stops==beforeStops+2;
|
||||
selected=await NodeTransportConnector.ConnectAsync(response,rankedPreference,Start,Stop,Healthy,Route,_=>{},()=>tick+1,CancellationToken.None);
|
||||
checks["integration_public_pass_only_after_all_internal_fail"] = !selected
|
||||
&& starts.SequenceEqual(new[]{"100.64.0.2","100.64.0.3","vpn002.example.invalid"});
|
||||
var report = new { passed=checks.Values.All(x=>x), checks, simulated_transport=true,
|
||||
production_network_actions=Array.Empty<string>(), note="Pure config/route models and fake start/stop/probe delegates; not a live Tailscale or release acceptance." };
|
||||
File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"tailnet-transport-self-test.json"),JsonSerializer.Serialize(report,new JsonSerializerOptions{WriteIndented=true}));
|
||||
|
||||
+21
-4
@@ -6,6 +6,21 @@ namespace UCVL.VPNPlus;
|
||||
internal sealed class TrafficChart : Control
|
||||
{
|
||||
private readonly Queue<(DateTimeOffset Time, double Up, double Down)> _points = new();
|
||||
private TimeSpan _period = TimeSpan.FromMinutes(5);
|
||||
internal int PeriodMinutes => (int)_period.TotalMinutes;
|
||||
internal int PointCount => _points.Count;
|
||||
internal int VisiblePointCount => VisiblePoints().Length;
|
||||
internal void SetPeriodMinutes(int minutes)
|
||||
{
|
||||
if (minutes is not (1 or 5 or 15 or 60)) throw new ArgumentOutOfRangeException(nameof(minutes));
|
||||
_period = TimeSpan.FromMinutes(minutes);
|
||||
Invalidate();
|
||||
}
|
||||
private (DateTimeOffset Time, double Up, double Down)[] VisiblePoints()
|
||||
{
|
||||
var end = _points.Count == 0 ? DateTimeOffset.Now : _points.Last().Time;
|
||||
return _points.Where(point => end - point.Time <= _period).ToArray();
|
||||
}
|
||||
internal TrafficChart()
|
||||
{
|
||||
DoubleBuffered = true;
|
||||
@@ -19,19 +34,21 @@ internal sealed class TrafficChart : Control
|
||||
var at = time ?? DateTimeOffset.Now;
|
||||
double Clean(double n) => double.IsFinite(n) ? Math.Max(0, n) : 0;
|
||||
_points.Enqueue((at, Clean(up), Clean(down)));
|
||||
while (_points.Count > 60 || (_points.Count > 0 && at - _points.Peek().Time > TimeSpan.FromMinutes(5))) _points.Dequeue();
|
||||
// Bounded current-session samples only: never turn daily accounting
|
||||
// totals into a fictitious speed curve. Changing range preserves samples.
|
||||
while (_points.Count > 3600 || (_points.Count > 0 && at - _points.Peek().Time > TimeSpan.FromMinutes(60))) _points.Dequeue();
|
||||
Invalidate();
|
||||
}
|
||||
internal void Reset() { _points.Clear(); Invalidate(); }
|
||||
protected override void OnPaint(PaintEventArgs e)
|
||||
{
|
||||
base.OnPaint(e);
|
||||
var points = _points.ToArray();
|
||||
var points = VisiblePoints();
|
||||
var peak = points.Length == 0 ? 1024 : Math.Max(1024, points.Max(p => Math.Max(p.Up, p.Down)));
|
||||
var chart = ChartAxis.Draw(e.Graphics, ClientRectangle, Font, DeviceDpi, peak, speed: true);
|
||||
if (chart.Plot.Width < 1 || chart.Plot.Height < 1) return;
|
||||
var end = points.Length == 0 ? DateTimeOffset.Now : points[^1].Time;
|
||||
ChartAxis.TimeLabels(e.Graphics, chart.Plot, Font, [end.AddMinutes(-5).ToString("HH:mm"), end.AddMinutes(-2.5).ToString("HH:mm"), end.ToString("HH:mm")]);
|
||||
ChartAxis.TimeLabels(e.Graphics, chart.Plot, Font, [end.Subtract(_period).ToString("HH:mm"), end.Subtract(_period / 2).ToString("HH:mm"), end.ToString("HH:mm")]);
|
||||
if (points.Length == 0)
|
||||
{
|
||||
TextRenderer.DrawText(e.Graphics, "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted,
|
||||
@@ -39,7 +56,7 @@ internal sealed class TrafficChart : Control
|
||||
return;
|
||||
}
|
||||
PointF[] Line(bool up) => points.Select(p => new PointF(
|
||||
chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / 300, 0, 1) * chart.Plot.Width,
|
||||
chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / _period.TotalSeconds, 0, 1) * chart.Plot.Width,
|
||||
chart.Plot.Bottom - (float)((up ? p.Up : p.Down) / chart.Maximum) * chart.Plot.Height)).ToArray();
|
||||
ChartAxis.Curve(e.Graphics, Line(true), Brand.RoyalBlue, DeviceDpi, dots: points.Length == 1);
|
||||
ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: points.Length == 1);
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
|
||||
<Version>0.2.23</Version>
|
||||
<AssemblyVersion>0.2.23.0</AssemblyVersion>
|
||||
<FileVersion>0.2.23.0</FileVersion>
|
||||
<InformationalVersion>0.2.23</InformationalVersion>
|
||||
<Version>0.3.0</Version>
|
||||
<AssemblyVersion>0.3.0.0</AssemblyVersion>
|
||||
<FileVersion>0.3.0.0</FileVersion>
|
||||
<InformationalVersion>0.3.0</InformationalVersion>
|
||||
<Product>纵横家</Product>
|
||||
<Company>优创未来(UCVL)</Company>
|
||||
<Description>纵横家 Windows 智能网络客户端</Description>
|
||||
|
||||
+30
-4
@@ -26,8 +26,23 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
private readonly string _xrayDirectory = Path.Combine(AppContext.BaseDirectory, "xray");
|
||||
private string? _baseConfigJson;
|
||||
private string? _tailnetFallbackConfigJson;
|
||||
// Retain only the authenticated in-memory alternative. A physical-network
|
||||
// recovery already has to restart the core, so it can recheck the overlay
|
||||
// instead of permanently retaining an earlier public fallback.
|
||||
private string? _preferredTailnetConfigJson;
|
||||
private string? _tailnetInterfaceName;
|
||||
internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null;
|
||||
internal (string Address, int Port)? PreferredTailnetEndpoint
|
||||
{
|
||||
get
|
||||
{
|
||||
var current = _baseConfigJson;
|
||||
var preferred = _preferredTailnetConfigJson;
|
||||
if (!IsRunning || current is null || preferred is null
|
||||
|| !TailnetTransport.SameAuthorizedFallback(preferred, current)) return null;
|
||||
return (TailnetTransport.Address(preferred)!, TailnetTransport.Port(preferred));
|
||||
}
|
||||
}
|
||||
private string _routeMode = "smart";
|
||||
private string _nodeSlug = "";
|
||||
private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe");
|
||||
@@ -57,8 +72,11 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
token.ThrowIfCancellationRequested();
|
||||
_baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson,
|
||||
async (config, rebindToken) => { _baseConfigJson = config; await StartCoreAsync(rebindToken); },
|
||||
StopCoreAsync, CheckProxyHealthAsync, token);
|
||||
if (!UsesTailnet) _tailnetFallbackConfigJson = null;
|
||||
StopCoreAsync, CheckProxyHealthAsync, token,
|
||||
preferredTailnetConfig: _preferredTailnetConfigJson,
|
||||
requireRoute: address => { TailnetTransport.RequireExistingRoute(address); },
|
||||
endpointProbe: TailnetTransport.ProbeEndpointAsync,
|
||||
diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage));
|
||||
}
|
||||
catch { await StopCoreAsync(); throw; }
|
||||
finally { _lifecycle.Release(); }
|
||||
@@ -166,18 +184,25 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
}
|
||||
|
||||
internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken,
|
||||
string? tailnetFallbackConfigJson = null)
|
||||
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null)
|
||||
{
|
||||
if (TailnetTransport.Address(configJson) is not null
|
||||
&& !TailnetTransport.SameAuthorizedFallback(configJson, tailnetFallbackConfigJson))
|
||||
throw new InvalidOperationException("Tailscale 原入口与已授权线路不匹配。");
|
||||
var preferred = preferredTailnetConfigJson
|
||||
?? (TailnetTransport.Address(configJson) is not null ? configJson : null);
|
||||
var original = tailnetFallbackConfigJson
|
||||
?? (TailnetTransport.Address(configJson) is null ? configJson : null);
|
||||
if (preferred is not null && !TailnetTransport.SameAuthorizedFallback(preferred, original))
|
||||
throw new InvalidOperationException("Tailscale 恢复入口与已授权线路不匹配。");
|
||||
await InitializeAsync(cancellationToken);
|
||||
await _lifecycle.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
await StopCoreAsync();
|
||||
_baseConfigJson = configJson;
|
||||
_tailnetFallbackConfigJson = tailnetFallbackConfigJson;
|
||||
_tailnetFallbackConfigJson = preferred is not null ? original : tailnetFallbackConfigJson;
|
||||
_preferredTailnetConfigJson = preferred;
|
||||
_routeMode = routeMode;
|
||||
_nodeSlug = nodeSlug;
|
||||
await StartCoreAsync(cancellationToken);
|
||||
@@ -212,6 +237,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
|
||||
await StopCoreAsync().ConfigureAwait(false);
|
||||
_baseConfigJson = null;
|
||||
_tailnetFallbackConfigJson = null;
|
||||
_preferredTailnetConfigJson = null;
|
||||
_tailnetInterfaceName = null;
|
||||
_nodeSlug = "";
|
||||
_boundNetwork = null;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
#requires -Version 7.0
|
||||
# Build/package only. The only executed app modes are the six reviewed offline
|
||||
# self-tests below, offline startup UI and --installer-verify; no installation/network/TUN commands.
|
||||
# self-tests below, offline startup/preview UI and --installer-verify; no installation/network/TUN commands.
|
||||
param(
|
||||
[string]$OutputDirectory,
|
||||
[string]$ToolRoot,
|
||||
[string]$DependencyPayloadRoot,
|
||||
[ValidateSet(2,3,4)][int]$PreviewRevision = 2,
|
||||
[switch]$FormalChannel,
|
||||
[ValidateSet('0.2.20','0.2.21')][string]$FormalVersion = '0.2.21'
|
||||
[ValidateSet('0.2.20','0.2.21','0.2.22','0.2.23','0.2.24','0.3.0')][string]$FormalVersion = '0.2.21'
|
||||
)
|
||||
$ErrorActionPreference='Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
@@ -76,7 +76,11 @@ function Run-Offline([string]$File,[string]$Argument,[int]$Timeout=45){
|
||||
return $child.ExitCode
|
||||
} finally {$child.Dispose()}
|
||||
}
|
||||
$results=@(foreach($name in @('tailnet-transport-self-test','connection-health-self-test','connection-selection-self-test','private-auxiliary-self-test','learning-self-test','window-chrome-self-test','installation-self-test')){
|
||||
$offlineTests=@('tailnet-transport-self-test','connection-health-self-test','connection-selection-self-test','private-auxiliary-self-test','learning-self-test','window-chrome-self-test','installation-self-test')
|
||||
if($FormalChannel -and $FormalVersion -eq '0.3.0'){
|
||||
$offlineTests+=@('public-tailnet-selection-self-test','learning-sync-coordinator-self-test','tailnet-readiness-self-test','nextgen-lifecycle-self-test','network-handover-self-test','dashboard-interaction-self-test')
|
||||
}
|
||||
$results=@(foreach($name in $offlineTests){
|
||||
$report=Join-Path $candidate ($name+'.json');if(Test-Path -LiteralPath $report){throw 'Stale offline report'}
|
||||
$exit=Run-Offline $exe ('--'+$name)
|
||||
$parsed=Get-Content -LiteralPath $report -Raw | ConvertFrom-Json
|
||||
@@ -97,6 +101,16 @@ if($startupExit -ne 0 -or $startup.passed -ne $true){throw 'Offline startup/logi
|
||||
foreach($name in @('startup-self-test.json','startup-login-test.png')){
|
||||
Copy-Checked (Join-Path $candidate $name) (Join-Path $evidence $name) | Out-Null
|
||||
}
|
||||
if($FormalChannel -and $FormalVersion -eq '0.3.0'){
|
||||
$previewExit=Run-Offline $exe '--render-preview'
|
||||
$previewReport=Join-Path $candidate 'dashboard-ui-self-test.json'
|
||||
$preview=Get-Content -LiteralPath $previewReport -Raw | ConvertFrom-Json
|
||||
if($previewExit -ne 0 -or $preview.passed -ne $true){throw 'Exact-build dashboard preview failed'}
|
||||
Copy-Checked $previewReport (Join-Path $evidence 'dashboard-ui-self-test.json') | Out-Null
|
||||
foreach($previewImage in Get-ChildItem -LiteralPath $candidate -Filter 'preview-*.png' -File){
|
||||
Copy-Checked $previewImage.FullName (Join-Path $evidence $previewImage.Name) | Out-Null
|
||||
}
|
||||
}
|
||||
foreach($name in $results.Test){Copy-Item -LiteralPath (Join-Path $candidate ($name+'.json')) -Destination (Join-Path $evidence ($name+'.json'))}
|
||||
if(Test-Path -LiteralPath (Join-Path $candidate 'window-chrome-offline.png')){Copy-Item -LiteralPath (Join-Path $candidate 'window-chrome-offline.png') -Destination (Join-Path $evidence 'window-chrome-offline.png')}
|
||||
$manifest=@(foreach($name in $expected){
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# 纵横家 Windows 0.3.0 — 连接可靠性升级候选
|
||||
|
||||
本包为 Windows x64 候选,尚未替换现用客户端,也未进入正式自动更新源。
|
||||
|
||||
## 连接与恢复
|
||||
|
||||
- 自动连接先并行检测当前账号授权的内网入口,按端口响应时间排序;其他可用内网节点尝试完后才使用公网。端口可达不等于代理认证成功,最终仍验证实际代理出口。
|
||||
- 物理网络切换时,可重新验证同节点缓存的已授权 Tailscale 入口,不因早先公网回退一直沿用公网。
|
||||
- 即使物理网卡不变,也会在现有代理可用时低频检查已授权 Tailscale 入口。两次成功后通过托盘提示恢复;“优先内网重连(会重建连接)”是明确的用户操作,不会静默中断长连接,也不宣称无缝迁移。
|
||||
- 连接过程中可点击取消。取消、账号替换或退出后的迟到结果不能重新显示连接成功,取消后不自动重连。
|
||||
- 保留手动固定节点、服务端授权、管理员明确禁用内网入口及独立现有路由检查;不切换用户的 Tailscale 账号、ACL 或退出节点。
|
||||
|
||||
## 账号与后台兼容
|
||||
|
||||
- 账号刷新增加会话代际检查,旧账号的迟到资料或 401/403 不能修改或清除新账号。
|
||||
- 学习上传、规则下载和回执分别退避;上传 404 不再阻断规则下载。上传单轮最多使用 4 秒,总同步仍限 15 秒。
|
||||
- 404/405 按 2、4、8、15 分钟退避,临时错误按 1、2、4、5 分钟退避。当前账号的 401/403 仍按失效授权处理,不视为可忽略的功能缺失。
|
||||
- 本地规则过期和路径验证不依赖后台是否在线。诊断使用固定原因码,不记录令牌、配置正文或密码。
|
||||
|
||||
## 界面与统计
|
||||
|
||||
- 固定高度单页,不引入滚动;使用 Tailscale 时只将左侧原有区域分为代理速度和 Tailscale 速度两部分。
|
||||
- 右侧显示真实代理速度,可选择近 1、5、15、60 分钟;累计流量只显示数值,不把每日用量伪造成速度曲线。
|
||||
- Tailscale 数据是当前纵横家代理链路的分项,已包含在代理累计中,不代表整机 Tailscale 流量,不重复计费。
|
||||
- 保留山水背景、透明卡片、登录前退出和登录后托盘操作。
|
||||
|
||||
## 验证与边界
|
||||
|
||||
通过的检查、精确 EXE 与安装包哈希以本包 evidence 和 frozen-candidate.json 为准。旧版 427 项记录不自动沿用于新代码。
|
||||
|
||||
离线检查和隔离安装不能替代真实代理认证、TUN/UDP 共存、已登录业务长连接及实际用户升级验收。当前没有实测带宽提升比例;Tailscale 的 100 段入口也可能通过 DERP 中继,不保证底层点对点直连。
|
||||
|
||||
本轮不部署后台、不操作手机夜猫或电视,不将安卓、iOS、macOS 候选混称为本次 Windows 正式版本。安装包无 Authenticode 签名,系统必要的权限提示仍可能出现。
|
||||
Reference in New Issue
Block a user