using System.Text.Json; namespace UCVL.VPNPlus; internal static class NodeTrafficSelfTest { internal static int Run() { var checks = new Dictionary(); string? error = null; try { var now = new DateTimeOffset(2026, 10, 22, 8, 0, 0, TimeSpan.Zero); NodeTrafficReading Row(string slug = "aliyun-tokyo-002", bool stale = false, DateTimeOffset? sampled = null, long? up = 10, long? down = 20, long? totalUp = 30, long? totalDown = 40, double? interval = 5, string? epoch = "fixture") => new() { Slug = slug, Stale = stale, SampledAt = sampled ?? now, UploadRate = up, DownloadRate = down, TotalUpload = totalUp, TotalDownload = totalDown, IntervalSeconds = interval, CounterEpoch = epoch }; NodeTrafficSnapshot Snapshot(List? rows = null, string scope = "server_host_interface", string source = "linux_host_interface", DateTimeOffset? generated = null, string direction = "interface_perspective") => new() { Contract = 1, Scope = scope, Source = source, Direction = direction, CounterSince = "boot_or_interface_reset", GeneratedAt = generated ?? now, Nodes = rows ?? [Row(), Row(NodeTrafficPresentation.Slugs[1])] }; bool Valid(NodeTrafficSnapshot value) => NodeTrafficPresentation.Valid(value, now); checks["exact_two_authorized_server_contract"] = Valid(Snapshot()); checks["empty_authorized_set_is_not_fake_servers"] = Valid(Snapshot([])); checks["other_nodes_rejected"] = !Valid(Snapshot([Row("phone")])); checks["duplicate_node_rejected"] = !Valid(Snapshot([Row(), Row()])); checks["too_many_rows_rejected"] = !Valid(Snapshot([Row(), Row(), Row()])); checks["proxy_accounting_cannot_be_mislabelled_host"] = !Valid(Snapshot(scope: "server_proxy_aggregate")); checks["unknown_source_rejected"] = !Valid(Snapshot(source: "unknown")); checks["wrong_direction_rejected"] = !Valid(Snapshot(direction: "client_perspective")); checks["stale_envelope_rejected"] = !Valid(Snapshot(generated: now.AddSeconds(-16))); checks["future_envelope_rejected"] = !Valid(Snapshot(generated: now.AddSeconds(6))); checks["negative_upload_rejected"] = !Valid(Snapshot([Row(up: -1)])); checks["negative_download_rejected"] = !Valid(Snapshot([Row(down: -1)])); checks["negative_total_rejected"] = !Valid(Snapshot([Row(totalUp: -1)])); checks["nonfinite_interval_rejected"] = !Valid(Snapshot([Row(interval: double.NaN)])); checks["unbounded_interval_rejected"] = !Valid(Snapshot([Row(interval: 31)])); checks["fresh_sample_is_current"] = NodeTrafficPresentation.Fresh(Row(), now); checks["backend_stale_is_not_live"] = !NodeTrafficPresentation.Fresh(Row(stale: true), now); checks["client_checks_sample_age_independently"] = !NodeTrafficPresentation.Fresh(Row(sampled: now.AddSeconds(-16)), now); checks["future_sample_is_not_live"] = !NodeTrafficPresentation.Fresh(Row(sampled: now.AddSeconds(6)), now); checks["first_counter_has_no_invented_rate"] = !NodeTrafficPresentation.Fresh(Row(up: null, down: null, interval: null), now); checks["reset_epoch_required"] = !NodeTrafficPresentation.Fresh(Row(epoch: null), now); checks["missing_is_dash_not_zero"] = NodeTrafficPresentation.Bytes(null, true) == "—"; checks["measured_zero_retained"] = NodeTrafficPresentation.Bytes(0, true) == "0.0 KB/s"; checks["rate_uses_bytes_not_bits"] = NodeTrafficPresentation.Bytes(204800, true) == "200.0 KB/s"; checks["cumulative_has_no_speed_suffix"] = NodeTrafficPresentation.Bytes(204800) == "200 KB"; var liveBars = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: 10, down: 20), now); checks["top_bar_is_host_ingress_download"] = liveBars.Ingress == 20; checks["bottom_bar_is_host_egress_upload"] = liveBars.Egress == 10; checks["stale_bars_are_missing_not_zero"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(stale: true), now) == new NodeTrafficBarRates(null, null); checks["expired_envelope_hides_live_bars"] = NodeTrafficPresentation.BarRates(Snapshot(generated: now.AddSeconds(-16)), Row(), now) == new NodeTrafficBarRates(null, null); checks["unavailable_sampling_hides_live_bars"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(), now, false) == new NodeTrafficBarRates(null, null); checks["measured_zero_bars_remain_available"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: 0, down: 0), now) == new NodeTrafficBarRates(0, 0); checks["individual_missing_rate_is_not_fabricated"] = NodeTrafficPresentation.BarRates(Snapshot(), Row(up: null, down: 20), now) == new NodeTrafficBarRates(20, null); var commonMaximum = NodeTrafficPresentation.BarMaximum([new(100 * 1024, 200 * 1024), new(20 * 1024, null)]); checks["two_servers_share_one_common_scale"] = commonMaximum > 200 * 1024 && NodeTrafficPresentation.BarWidth(100 * 1024, commonMaximum, 100) < NodeTrafficPresentation.BarWidth(200 * 1024, commonMaximum, 100); checks["bar_zero_and_unavailable_differ"] = NodeTrafficPresentation.BarWidth(null, 40, 44) is null && NodeTrafficPresentation.BarWidth(0, 40, 44) == 0; checks["positive_subpixel_rate_has_only_pixel_minimum"] = NodeTrafficPresentation.BarWidth(1, 100_000, 44) == 1; checks["all_geometry_monitor_tailnet_cases_fit"] = DashboardLayout.SelfTest(); using (var font = Brand.Font(6.5f)) using (var graphics = Graphics.FromHwnd(IntPtr.Zero)) { // Measure a real display context, then normalize once from its // actual DPI. Default MeasureText may already be at 200% DPI. var measuredHeight = TextRenderer.MeasureText(graphics, "VPN002 上传", font).Height; var sourceDpi = graphics.DpiY; foreach (var dpi in new[] { 96, 120, 144, 192, 336, 384 }) foreach (var logicalView in new[] { new Size(480, 312), new Size(620, 350) }) { var view = new Size(logicalView.Width * dpi / 96, logicalView.Height * dpi / 96); var panel = DashboardLayout.Calculate(view, dpi, true, true).ServerTrafficCard; var targetFontHeight = (int)Math.Ceiling(measuredHeight * dpi / (double)sourceDpi); var text = NodeTrafficPanel.TextLayout(panel.Size, dpi, targetFontHeight); checks[$"minimum_two_text_rows_fit_{logicalView.Width}x{logicalView.Height}_{dpi}"] = text.Rows.Length == 2 && text.Rows.All(row => row.Height >= targetFontHeight && row.Bottom <= panel.Height) && !text.Rows[0].IntersectsWith(text.Rows[1]); checks[$"paired_thin_bars_fit_existing_row_{logicalView.Width}x{logicalView.Height}_{dpi}"] = text.Rows.All(row => { var geometry = NodeTrafficPanel.RowLayout(row, dpi); return row.Contains(geometry.Text) && row.Contains(geometry.Ingress) && row.Contains(geometry.Egress) && !geometry.Ingress.IntersectsWith(geometry.Egress) && !geometry.Text.IntersectsWith(geometry.Ingress) && !geometry.Text.IntersectsWith(geometry.Egress) && geometry.Ingress.Top < geometry.Egress.Top && geometry.Ingress.Height <= (int)Math.Round(3d * dpi / 96); }); } } using (var barsImage = new Bitmap(220, 24)) using (var barsGraphics = Graphics.FromImage(barsImage)) { barsGraphics.Clear(Color.White); var geometry = NodeTrafficPanel.RowLayout(new Rectangle(0, 0, 220, 24), 96); NodeTrafficPanel.PaintBars(barsGraphics, geometry.Ingress, geometry.Egress, new(20, 10), 40); checks["painted_top_bar_is_cyan_ingress"] = barsImage.GetPixel(geometry.Ingress.Left + 15, geometry.Ingress.Top + 1).ToArgb() == Brand.Cyan.ToArgb(); checks["painted_bottom_bar_is_blue_egress"] = barsImage.GetPixel(geometry.Egress.Left + 5, geometry.Egress.Top + 1).ToArgb() == Brand.RoyalBlue.ToArgb(); checks["painted_width_reflects_two_distinct_rates"] = barsImage.GetPixel(geometry.Egress.Left + 15, geometry.Egress.Top + 1).ToArgb() != Brand.RoyalBlue.ToArgb(); barsGraphics.Clear(Color.White); NodeTrafficPanel.PaintBars(barsGraphics, geometry.Ingress, geometry.Egress, new(null, 0), 40); checks["missing_bar_has_unavailable_marker"] = barsImage.GetPixel(geometry.Ingress.Left + geometry.Ingress.Width / 2, geometry.Ingress.Top + geometry.Ingress.Height / 2).ToArgb() == Brand.Muted.ToArgb(); checks["measured_zero_has_no_unavailable_marker"] = barsImage.GetPixel(geometry.Egress.Left + geometry.Egress.Width / 2, geometry.Egress.Top + geometry.Egress.Height / 2).ToArgb() != Brand.Muted.ToArgb(); } using (var panel = new NodeTrafficPanel(() => now) { BackColor = Color.White }) { panel.CreateControl(); panel.Size = new Size(464 * panel.DeviceDpi / 96, 38 * panel.DeviceDpi / 96); using var preview = new Bitmap(panel.Width, panel.Height); panel.SetSnapshot(Snapshot([Row(up: 100 * 1024, down: 200 * 1024, totalUp: 2_000_000_000, totalDown: 3_000_000_000), Row(NodeTrafficPresentation.Slugs[1], up: 20 * 1024, down: 40 * 1024, totalUp: 5_000_000_000, totalDown: 6_000_000_000)])); panel.DrawToBitmap(preview, panel.ClientRectangle); checks["actual_panel_describes_ingress_egress_order"] = panel.AccessibleDescription?.Contains("上方为流入,下方为流出") == true; checks["actual_panel_retains_rates_totals_and_sample_time"] = panel.AccessibleDescription?.Contains("200.0 KB/s") == true && panel.AccessibleDescription.Contains("累计入") && panel.AccessibleDescription.Contains(now.LocalDateTime.ToString("HH:mm:ss")); preview.Save(Path.Combine(AppContext.BaseDirectory, "node-traffic-bars-preview.png")); panel.Unavailable("采样请求超时"); panel.DrawToBitmap(preview, panel.ClientRectangle); checks["actual_unavailable_panel_preserves_totals_and_time_without_live_rate"] = panel.AccessibleDescription?.Contains("入— 出—") == true && panel.AccessibleDescription.Contains("累计入2.79 GB") && panel.AccessibleDescription.Contains(now.LocalDateTime.ToString("HH:mm:ss")); } foreach (var tailnet in new[] { false, true }) { var view = new Size(960, 612); var layout = DashboardLayout.Calculate(view, 96, tailnet, true); checks["server_rows_below_real_speed_" + tailnet] = layout.ServerTrafficCard.Top > layout.DailyCard.Bottom && layout.ServerTrafficCard.Top > layout.TrafficCard.Bottom && (!tailnet || layout.ServerTrafficCard.Top > layout.TailnetTrafficCard.Bottom); checks["no_extra_window_height_or_scroll_" + tailnet] = layout.Footer.Bottom <= view.Height && layout.ContentHeight <= view.Height && layout.ServerTrafficCard.Bottom < layout.Footer.Top; } var oldProfile = JsonSerializer.Deserialize("{\"email\":\"fixture@example.invalid\"}")!; checks["older_backend_omission_does_not_enable_monitor"] = !oldProfile.CanViewNodeTraffic; } catch (Exception exception) { error = exception.GetType().Name; } var passed = error is null && checks.Count >= 30 && checks.Values.All(value => value); File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-traffic-self-test.json"), JsonSerializer.Serialize(new { passed, checks, error, scope = "offline contract, fixed-height geometry and real bar painting", network_modified = false, credentials_loaded = false, production_sample_observed = false }, new JsonSerializerOptions { WriteIndented = true })); return passed ? 0 : 84; } }