Files
ucvl-zonghengjia-open-source/windows/NodeTrafficMonitor.cs
T

241 lines
14 KiB
C#

using System.Text.Json.Serialization;
namespace UCVL.VPNPlus;
internal sealed class NodeTrafficSnapshot
{
[JsonPropertyName("contract")] public int Contract { get; init; }
[JsonPropertyName("scope")] public string Scope { get; init; } = "";
[JsonPropertyName("source")] public string Source { get; init; } = "";
[JsonPropertyName("direction")] public string Direction { get; init; } = "";
[JsonPropertyName("counter_since")] public string CounterSince { get; init; } = "";
[JsonPropertyName("generated_at")] public DateTimeOffset GeneratedAt { get; init; }
[JsonPropertyName("nodes")] public List<NodeTrafficReading> Nodes { get; init; } = [];
}
internal sealed class NodeTrafficReading
{
[JsonPropertyName("slug")] public string Slug { get; init; } = "";
[JsonPropertyName("name")] public string Name { get; init; } = "";
[JsonPropertyName("region")] public string Region { get; init; } = "";
[JsonPropertyName("current_upload_bytes_per_second")] public long? UploadRate { get; init; }
[JsonPropertyName("current_download_bytes_per_second")] public long? DownloadRate { get; init; }
[JsonPropertyName("total_upload_bytes")] public long? TotalUpload { get; init; }
[JsonPropertyName("total_download_bytes")] public long? TotalDownload { get; init; }
[JsonPropertyName("sampled_at")] public DateTimeOffset? SampledAt { get; init; }
[JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; }
[JsonPropertyName("stale")] public bool Stale { get; init; }
[JsonPropertyName("counter_epoch")] public string? CounterEpoch { get; init; }
}
// Read-only display contract: no personal accounting or route/core mutations.
internal static class NodeTrafficPresentation
{
internal static readonly string[] Slugs = ["aliyun-tokyo-002", "aliyun-siliconvalley-003"];
internal static bool Valid(NodeTrafficSnapshot value, DateTimeOffset now) => value.Contract == 1
&& value.Scope == "server_host_interface" && value.Source == "linux_host_interface"
&& value.Direction == "interface_perspective" && value.CounterSince == "boot_or_interface_reset"
&& value.GeneratedAt <= now.AddSeconds(5) && value.GeneratedAt >= now.AddSeconds(-15)
&& value.Nodes is { Count: <= 2 } && value.Nodes.All(n => n is not null)
&& value.Nodes.Select(n => n.Slug).Distinct(StringComparer.Ordinal).Count() == value.Nodes.Count
&& value.Nodes.All(n => Slugs.Contains(n.Slug, StringComparer.Ordinal)
&& n.UploadRate is not < 0 && n.DownloadRate is not < 0
&& n.TotalUpload is not < 0 && n.TotalDownload is not < 0
&& (n.IntervalSeconds is null || double.IsFinite(n.IntervalSeconds.Value) && n.IntervalSeconds > 0 && n.IntervalSeconds <= 30));
internal static bool Fresh(NodeTrafficReading row, DateTimeOffset now) => !row.Stale
&& row.SampledAt is { } sampled && sampled <= now.AddSeconds(5) && sampled >= now.AddSeconds(-15)
&& row.IntervalSeconds is > 0 and <= 30 && !string.IsNullOrWhiteSpace(row.CounterEpoch);
internal static string Bytes(long? bytes, bool speed = false)
{
if (speed) return SpeedDisplay.Format(bytes);
if (bytes is null or < 0) return "—";
var value = (double)bytes.Value;
string[] units = ["B", "KB", "MB", "GB", "TB"];
var unit = 0;
while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; }
return $"{value:0.##} {units[unit]}" + (speed ? "/s" : "");
}
// The contract describes the host interface: receiving is ingress and
// transmitting is egress, independently of a client's upload direction.
internal static NodeTrafficBarRates BarRates(NodeTrafficSnapshot? snapshot, NodeTrafficReading? row,
DateTimeOffset now, bool samplingAvailable = true) => samplingAvailable && snapshot is not null && row is not null
&& Valid(snapshot, now) && Fresh(row, now)
? new(row.DownloadRate, row.UploadRate) : new(null, null);
internal static double BarMaximum(IEnumerable<NodeTrafficBarRates> rows)
{
var peak = rows.SelectMany(row => new[] { row.Ingress, row.Egress })
.Where(rate => rate is >= 0).Select(rate => (double)rate!.Value).DefaultIfEmpty(0).Max();
return ChartAxisY.Create(peak, true).MaximumBytes;
}
internal static int? BarWidth(long? rate, double maximum, int width) => rate is null or < 0 ? null
: rate == 0 ? 0 : Math.Clamp((int)Math.Round(Math.Clamp(rate.Value / maximum, 0, 1) * width), 1, Math.Max(1, width));
}
internal readonly record struct NodeTrafficBarRates(long? Ingress, long? Egress);
// One buffered surface, not a table of native child HWNDs. A snapshot swaps
// atomically on the UI thread and never changes row count or window height.
internal sealed class NodeTrafficPanel : CardPanel
{
private readonly Func<DateTimeOffset> _clock;
private readonly ToolTip _details = new() { InitialDelay = 350, ReshowDelay = 100, AutoPopDelay = 15_000 };
private NodeTrafficSnapshot? _snapshot;
private string _status = "等待服务器采样";
private string _detailText = "等待服务器采样";
internal void SetSnapshot(NodeTrafficSnapshot value) { _snapshot = value; _status = "每 5 秒更新"; Invalidate(); }
internal void Unavailable(string status, bool clear = false) { if (clear) _snapshot = null; _status = status; Invalidate(); }
internal NodeTrafficPanel(Func<DateTimeOffset>? clock = null)
{
_clock = clock ?? (() => DateTimeOffset.UtcNow);
AccessibleName = "VPN 服务器流入流出实时速度与累计流量,上入下出细柱";
}
internal static (Rectangle Title, Rectangle[] Rows) TextLayout(Size size, int dpi, int fontHeight)
{
var pad = Math.Max(2, 4 * dpi / 96);
// A 7.5pt YaHei line is 16px at native 96 DPI. Keep two complete
// lines in the compact 38px card; fractional-DPI fonts vary slightly.
var verticalPad = Math.Max(2, 3 * dpi / 96);
var contentHeight = Math.Max(0, size.Height - verticalPad * 2);
var title = contentHeight >= fontHeight * 3;
var height = contentHeight / (title ? 3 : 2);
Rectangle Line(int row) => new(pad, verticalPad + row * height, Math.Max(0, size.Width - pad * 2), height);
return (title ? Line(0) : Rectangle.Empty, [Line(title ? 1 : 0), Line(title ? 2 : 1)]);
}
internal static (Rectangle Text, Rectangle Ingress, Rectangle Egress) RowLayout(Rectangle row, int dpi)
{
var scale = Math.Max(1f, dpi / 96f);
var width = Math.Min((int)Math.Round(54 * scale), Math.Max(1, row.Width / 5));
var gap = Math.Max(1, (int)Math.Round(2 * scale));
var height = Math.Max(1, Math.Min((int)Math.Round(3 * scale), (row.Height - gap) / 2));
var top = row.Top + Math.Max(0, (row.Height - height * 2 - gap) / 2);
var left = row.Right - width;
return (new(row.Left, row.Top, Math.Max(0, left - gap * 2 - row.Left), row.Height),
new(left, top, width, height), new(left, top + height + gap, width, height));
}
internal static void PaintBars(Graphics graphics, Rectangle ingress, Rectangle egress,
NodeTrafficBarRates rates, double maximum)
{
Draw(ingress, rates.Ingress, Brand.Cyan);
Draw(egress, rates.Egress, Brand.RoyalBlue);
void Draw(Rectangle track, long? rate, Color color)
{
using var background = new SolidBrush(Color.FromArgb(38, color));
graphics.FillRectangle(background, track);
var width = NodeTrafficPresentation.BarWidth(rate, maximum, track.Width);
if (width is > 0)
{
using var fill = new SolidBrush(color);
graphics.FillRectangle(fill, new Rectangle(track.Location, new Size(width.Value, track.Height)));
}
else if (width is null)
{
// Missing/stale data has its own marker, never a fake zero bar.
using var unavailable = new Pen(Brand.Muted);
var center = track.Left + track.Width / 2;
graphics.DrawLine(unavailable, center - 2, track.Top + track.Height / 2, center + 2, track.Top + track.Height / 2);
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing) _details.Dispose();
base.Dispose(disposing);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var now = _clock();
var compact=Width<720*DeviceDpi/96;
using var font = Brand.Font(7.5f);
var layout = TextLayout(ClientSize, DeviceDpi, TextRenderer.MeasureText(e.Graphics, "VPN002 上传", font).Height);
var flags = ChartAxis.PaintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis;
if (!layout.Title.IsEmpty) TextRenderer.DrawText(e.Graphics, "服务器整机流量 · 细柱上入下出 · 累计自网卡启动 / 重置", font,
layout.Title, Brand.Muted, flags);
var rows = NodeTrafficPresentation.Slugs.Select(slug => _snapshot?.Nodes.SingleOrDefault(n => n.Slug == slug)).ToArray();
var rates = rows.Select(row => NodeTrafficPresentation.BarRates(_snapshot, row, now, _status == "每 5 秒更新")).ToArray();
var maximum = NodeTrafficPresentation.BarMaximum(rates);
var details = new List<string>();
for (var i = 0; i < 2; i++)
{
var row = rows[i];
var fresh = row is not null && _snapshot is not null && NodeTrafficPresentation.Valid(_snapshot, now)
&& NodeTrafficPresentation.Fresh(row, now) && _status == "每 5 秒更新";
var name = i == 0 ? "VPN002 东京" : "VPN003 美国";
var up = fresh ? row!.UploadRate : null;
var down = fresh ? row!.DownloadRate : null;
var status = fresh ? row!.SampledAt!.Value.LocalDateTime.ToString("HH:mm:ss")
: row?.SampledAt is { } oldTime ? $"过期 {oldTime.LocalDateTime:HH:mm:ss}" : "等待上报";
var text = $"{name} {status} 入{NodeTrafficPresentation.Bytes(down, true)} 出{NodeTrafficPresentation.Bytes(up, true)}"
+ $" 累计入{NodeTrafficPresentation.Bytes(row?.TotalDownload)} 出{NodeTrafficPresentation.Bytes(row?.TotalUpload)}";
details.Add(text);
if(compact)text=$"{(i==0?"VPN002东京":"VPN003美国")} {(fresh?status:row?.SampledAt is { } age?$"过期{age.LocalDateTime:HH:mm}":"待上报")} 入{NodeTrafficPresentation.Bytes(down,true)} 出{NodeTrafficPresentation.Bytes(up,true)} Σ入{NodeTrafficPresentation.Bytes(row?.TotalDownload)} 出{NodeTrafficPresentation.Bytes(row?.TotalUpload)}";
var rowLayout = RowLayout(layout.Rows[i], DeviceDpi);
TextRenderer.DrawText(e.Graphics, text, font,
rowLayout.Text, Brand.Text, flags);
PaintBars(e.Graphics, rowLayout.Ingress, rowLayout.Egress, rates[i], maximum);
}
AccessibleDescription = _status + ";细柱上方为流入,下方为流出,两台使用同一量程,上限 "
+ SpeedDisplay.Format(maximum) + "。速率为采样区间平均。服务器整机网卡数据,不是本账号代理流量,不计入套餐用量;过期累计保留采样时间。"
+ Environment.NewLine + string.Join(Environment.NewLine, details);
if (_detailText != AccessibleDescription)
{
_detailText = AccessibleDescription;
_details.SetToolTip(this, _detailText);
}
}
}
internal sealed partial class MainForm
{
private readonly NodeTrafficPanel _nodeTrafficPanel = new();
private readonly System.Windows.Forms.Timer _nodeTrafficTimer = new() { Interval = 5_000 };
private bool _canViewNodeTraffic, _nodeTrafficReading;
private DateTimeOffset _nextNodeTrafficAttempt;
private void BuildNodeTrafficMonitor()
{
_nodeTrafficPanel.Visible = false;
_dashboardBody.Controls.Add(_nodeTrafficPanel);
_nodeTrafficTimer.Tick += async (_, _) => await RefreshNodeTrafficAsync();
_nodeTrafficPanel.Disposed += (_, _) => _nodeTrafficTimer.Dispose();
}
private void SetNodeTrafficPermission(bool allowed)
{
if (_canViewNodeTraffic != allowed) _nodeTrafficPanel.Unavailable("等待服务器采样", clear: true);
_canViewNodeTraffic = allowed;
_nodeTrafficPanel.Visible = allowed;
if (allowed && !_preview && !_uiOnly && !_exiting) _nodeTrafficTimer.Start();
else _nodeTrafficTimer.Stop();
LayoutDashboard();
}
private async Task RefreshNodeTrafficAsync()
{
_nodeTrafficPanel.Invalidate();
if (!_canViewNodeTraffic || _nodeTrafficReading || _preview || _uiOnly || _exiting
|| string.IsNullOrWhiteSpace(_accessToken) || DateTimeOffset.UtcNow < _nextNodeTrafficAttempt) return;
var token = _accessToken;
var revision = _sessionRevision;
bool Current() => !_exiting && !IsDisposed && _canViewNodeTraffic && _sessionRevision == revision && _accessToken == token;
_nodeTrafficReading = true;
try
{
var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token);
if (!Current()) return;
if (!NodeTrafficPresentation.Valid(result, DateTimeOffset.UtcNow)) throw new IOException("监控契约或时间戳无效。");
_nodeTrafficPanel.SetSnapshot(result);
}
catch (ApiException error) when (error.StatusCode is 401 or 403)
{
if (Current()) { _nodeTrafficPanel.Unavailable("监控权限不可用", clear: true); SetNodeTrafficPermission(false); }
// An optional monitor must not log out or disconnect the VPN.
}
catch (ApiException error) when (error.StatusCode is 404 or 405)
{
if (Current()) { _nextNodeTrafficAttempt = DateTimeOffset.UtcNow.AddMinutes(2); _nodeTrafficPanel.Unavailable("后台尚未提供服务器监控"); }
}
catch (OperationCanceledException) { if (Current()) _nodeTrafficPanel.Unavailable("采样请求超时"); }
catch (Exception) { if (Current()) _nodeTrafficPanel.Unavailable("服务器采样暂不可用"); }
finally { _nodeTrafficReading = false; }
}
}