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("sample_period_seconds")] public int SamplePeriodSeconds { get; init; } [JsonPropertyName("history_since")] public DateTimeOffset? HistorySince { get; init; } [JsonPropertyName("nodes")] public List 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; } [JsonPropertyName("history")] public List History { get; init; }=[]; } internal sealed class NodeTrafficHistoryReading { [JsonPropertyName("sampled_at")] public DateTimeOffset SampledAt { get; init; } [JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; } [JsonPropertyName("upload_bytes_per_second")] public long? Upload { get; init; } [JsonPropertyName("download_bytes_per_second")] public long? Download { get; init; } [JsonPropertyName("counter_epoch")] public string CounterEpoch { get; init; }=""; [JsonPropertyName("interface")] public string Interface { get; init; }=""; [JsonPropertyName("quality")] public string Quality { get; init; }=""; [JsonPropertyName("gap_before")] public bool GapBefore { get; init; } } // Read-only display contract: no personal accounting or route/core mutations. internal static class NodeTrafficPresentation { 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.SamplePeriodSeconds is 0 or 1 && value.GeneratedAt <= now.AddSeconds(5) && value.GeneratedAt >= now.AddSeconds(-15) && value.Nodes is { Count: <= 32 } && 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 => n.Slug is { Length: > 0 and <= 80 } && n.Slug.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_') && n.Name is { Length: <= 120 } && n.Region is { Length: <= 160 } && 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==0&&n.UploadRate is null&&n.DownloadRate is null) && n.IntervalSeconds <=(n.UploadRate is null&&n.DownloadRate is null?86400:30)) && n.History is {Count:<=3600} && n.History.All(point=>point is not null&&ValidHistory(point,value.GeneratedAt)) && n.History.Zip(n.History.Skip(1),(first,second)=>second.SampledAt>first.SampledAt ||second.SampledAt==first.SampledAt&&second.CounterEpoch!=first.CounterEpoch).All(ordered=>ordered)); private static bool ValidHistory(NodeTrafficHistoryReading point,DateTimeOffset generated) => point.SampledAt>=generated.AddHours(-1).AddSeconds(-5)&&point.SampledAt<=generated.AddSeconds(5) &&point.CounterEpoch is {Length:>0 and <=128}&&point.Interface is {Length:<=80} &&point.Quality is "ok" or "baseline" or "reset" or "gap" or "interface_changed" or "boot_changed" &&(point.IntervalSeconds is null||double.IsFinite(point.IntervalSeconds.Value)&&point.IntervalSeconds>=(point.Quality=="ok"?double.Epsilon:0) &&point.IntervalSeconds<=(point.Quality=="ok"?30:86400)) &&(point.Quality=="ok"?point.Upload is >=0&&point.Download is >=0&&point.IntervalSeconds is >0 :point.Upload is null&&point.Download is null); 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 && row.UploadRate is >=0 && row.DownloadRate is >=0 && !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 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 _clock; private readonly Font _plotFont=Brand.Font(7.5f); private readonly ToolTip _details = new() { InitialDelay = 350, ReshowDelay = 100, AutoPopDelay = 15_000 }; private NodeTrafficSnapshot? _snapshot; private string _status = "等待服务器采样"; private string _detailText = "等待服务器采样"; private readonly Dictionary _histories = new(StringComparer.Ordinal); private readonly Dictionary> _historyRecords=new(StringComparer.Ordinal); private int _periodMinutes = 5; private string? _historySource; internal int ServerCount => _snapshot?.Nodes.Count ?? 0; internal int HistoryCount(string slug) => _histories.TryGetValue(slug, out var history) ? history.PointCount : 0; internal TrafficChartTimeline.Sample[] History(string slug) => _histories.TryGetValue(slug, out var history) ? history.Visible(TimeSpan.FromMinutes(_periodMinutes)) : []; internal void SetPeriodMinutes(int minutes) { if (minutes is not (1 or 5 or 15 or 60)) throw new ArgumentOutOfRangeException(nameof(minutes)); _periodMinutes=minutes; Invalidate(); } internal void SetSnapshot(NodeTrafficSnapshot value) { var now=_clock(); if(!NodeTrafficPresentation.Valid(value,now)) { Unavailable("服务器采样契约无效"); return; } if(_snapshot is not null && value.GeneratedAt<_snapshot.GeneratedAt)return; if(_historySource!=value.Scope) { _histories.Clear();_historyRecords.Clear();_historySource=value.Scope; } var allowed=value.Nodes.Select(row=>row.Slug).ToHashSet(StringComparer.Ordinal); foreach(var slug in _histories.Keys.Where(slug=>!allowed.Contains(slug)).ToArray()) { _histories.Remove(slug); _historyRecords.Remove(slug); } _snapshot=value; _status="每 5 秒更新"; foreach(var row in value.Nodes) { if(!_histories.TryGetValue(row.Slug,out var timeline)) _histories[row.Slug]=timeline=new TrafficChartTimeline(_clock); if(!_historyRecords.TryGetValue(row.Slug,out var records)) _historyRecords[row.Slug]=records=new SortedDictionary<(DateTimeOffset At,string Epoch),NodeTrafficHistoryReading>(); var changed=false; foreach(var point in row.History)changed|=records.TryAdd((point.SampledAt,point.CounterEpoch),point); if(NodeTrafficPresentation.Fresh(row,now)) changed|=records.TryAdd((row.SampledAt!.Value,row.CounterEpoch!),new NodeTrafficHistoryReading { SampledAt=row.SampledAt.Value,CounterEpoch=row.CounterEpoch!,IntervalSeconds=row.IntervalSeconds, Upload=row.UploadRate,Download=row.DownloadRate,Quality="ok" }); while(records.Count>3600||records.Count>0&&records.First().Key.At? 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(); _plotFont.Dispose(); } base.Dispose(disposing); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var now = _clock(); // Keep one owned font: allocating a Font on every repaint continually // fills TextRenderer's native HFONT cache during live sample updates. var font = _plotFont; var scale=Math.Max(1f,DeviceDpi/96f); int S(int n)=>(int)Math.Round(n*scale); var flags = ChartAxis.PaintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis; var title=new Rectangle(S(10),S(2),Width-S(20),S(17)); var heading=_snapshot?.SamplePeriodSeconds==1?"服务器出入 · 1秒采样"+(_periodMinutes>5?" · 仅已获取":""):"服务器出入速度趋势"; TextRenderer.DrawText(e.Graphics,heading,font,title,Brand.Text,flags); var legendWidth=S(65); TextRenderer.DrawText(e.Graphics,"● 流入",font,new Rectangle(Width-S(140),S(2),legendWidth,S(17)),Brand.Cyan,flags); TextRenderer.DrawText(e.Graphics,"● 流出",font,new Rectangle(Width-S(72),S(2),legendWidth,S(17)),Brand.RoyalBlue,flags); var rows=_snapshot?.Nodes??[]; var envelopeValid=_snapshot is not null&&NodeTrafficPresentation.Valid(_snapshot,now); var remaining=new Rectangle(S(8),S(21),Width-S(16),Math.Max(0,Height-S(25))); if(rows.Count==0) { TextRenderer.DrawText(e.Graphics,_status=="每 5 秒更新"?"暂无服务器采样":_status,font,remaining,Brand.Muted, flags|TextFormatFlags.HorizontalCenter); AccessibleDescription="服务器整机网卡速率;"+_status+";暂无数据,不使用本机个人代理流量代替服务器采样。"; if(_detailText!=AccessibleDescription) { _detailText=AccessibleDescription; _details.SetToolTip(this,_detailText); } return; } var details = new List(); for (var i = 0; i < rows.Count; i++) { var row = rows[i]; var fresh = envelopeValid && NodeTrafficPresentation.Fresh(row, now) && _status == "每 5 秒更新"; var name = !string.IsNullOrWhiteSpace(row.Name)?row.Name:row.Slug switch { "aliyun-tokyo-002"=>"VPN002 东京", "aliyun-siliconvalley-003"=>"VPN003 美国", _=>row.Slug }; 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); var lineTop=remaining.Top+remaining.Height*i/rows.Count; var lineBottom=remaining.Top+remaining.Height*(i+1)/rows.Count; var bounds=new Rectangle(remaining.Left,lineTop,remaining.Width,lineBottom-lineTop); var nameWidth=Math.Min(S(85),bounds.Width/5); var rateWidth=Math.Min(S(154),bounds.Width*2/5); TextRenderer.DrawText(e.Graphics,name,font,new Rectangle(bounds.Left,bounds.Top,nameWidth,bounds.Height),Brand.Text,flags); var rateLeft=bounds.Right-rateWidth; var chart=new RectangleF(bounds.Left+nameWidth+S(4),bounds.Top+S(3),Math.Max(1,rateLeft-S(8)-bounds.Left-nameWidth),Math.Max(1,bounds.Height-S(7))); using(var grid=new Pen(Color.FromArgb(100,Brand.Muted),Math.Max(1,scale*.5f))) e.Graphics.DrawLine(grid,chart.Left,chart.Bottom,chart.Right,chart.Bottom); if(_histories.TryGetValue(row.Slug,out var timeline)) { timeline.AdvanceClock(now); var points=timeline.Visible(TimeSpan.FromMinutes(_periodMinutes)); var maximum=ChartAxisY.Create(points.Select(p=>Math.Max(p.Up,p.Down)).DefaultIfEmpty(1024).Max(),true).MaximumBytes; foreach(var segment in points.GroupBy(point=>point.Segment)) { var samples=segment.ToArray(); PointF[] Line(bool inbound)=>samples.Select(point=>new PointF( chart.Left+(float)Math.Clamp(1-(timeline.End-point.Time).TotalMinutes/_periodMinutes,0,1)*chart.Width, chart.Bottom-(float)((inbound?point.Down:point.Up)/maximum)*chart.Height)).ToArray(); ChartAxis.Curve(e.Graphics,Line(true),Brand.Cyan,DeviceDpi,dots:samples.Length==1); ChartAxis.Curve(e.Graphics,Line(false),Brand.RoyalBlue,DeviceDpi,dots:samples.Length==1); } } if(!fresh) TextRenderer.DrawText(e.Graphics,"暂无数据",font,Rectangle.Round(chart),Brand.Muted,flags|TextFormatFlags.HorizontalCenter); var columnWidth=rateWidth/2; TextRenderer.DrawText(e.Graphics,"入 "+SpeedDisplay.Format(down),font,new Rectangle(rateLeft,bounds.Top,columnWidth,bounds.Height),Brand.Cyan,flags); TextRenderer.DrawText(e.Graphics,"出 "+SpeedDisplay.Format(up),font,new Rectangle(rateLeft+columnWidth,bounds.Top,rateWidth-columnWidth,bounds.Height),Brand.RoyalBlue,flags); } AccessibleDescription = _status + ";每台服务器各自一张流入、流出趋势图;青色流入,蓝色流出。近 "+_periodMinutes+" 分钟。" +"服务器真实1秒网卡采样,客户端每5秒获取批次。青色流入(RX),蓝色流出(TX)。包含系统及隧道开销,不是本账号代理用量;过期累计保留采样时间。" + 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 bool _nodeTrafficDiscovery; private long _nodeTrafficDiscoveryRevision=long.MinValue; private DateTimeOffset? _nodeTrafficSince; private string? _nodeTrafficSlugs; 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) { _nodeTrafficDiscovery=false; if(!allowed) { _nodeTrafficSince=null; _nodeTrafficSlugs=null; } if (_canViewNodeTraffic != allowed) _nodeTrafficPanel.Unavailable("等待服务器采样", clear: true); _canViewNodeTraffic = allowed; _nodeTrafficPanel.Visible = allowed; if (allowed && !_preview && !_uiOnly && !_exiting) _nodeTrafficTimer.Start(); else _nodeTrafficTimer.Stop(); LayoutDashboard(); } private void ConfigureNodeTrafficMonitor(Profile profile) { if(_preview||_uiOnly) { SetNodeTrafficPermission(profile.CanViewNodeTraffic); return; } // Legacy profiles have no staff/monitor flag. Probe the read-only staff // endpoint once per login; only a successful server authorization shows // the panel. A 403 hides it and stops polling for that session. if(_nodeTrafficDiscoveryRevision!=_sessionRevision) { _nodeTrafficDiscoveryRevision=_sessionRevision; _nodeTrafficDiscovery=true; _nextNodeTrafficAttempt=DateTimeOffset.MinValue; } if((_canViewNodeTraffic||_nodeTrafficDiscovery)&&!_exiting) { _nodeTrafficTimer.Start(); _=RefreshNodeTrafficAsync(); } } private async Task RefreshNodeTrafficAsync() { _nodeTrafficPanel.Invalidate(); if (!(_canViewNodeTraffic||_nodeTrafficDiscovery) || _nodeTrafficReading || _preview || _uiOnly || _exiting || string.IsNullOrWhiteSpace(_accessToken) || DateTimeOffset.UtcNow < _nextNodeTrafficAttempt) return; var token = _accessToken; var revision = _sessionRevision; bool Current() => !_exiting && !IsDisposed && (_canViewNodeTraffic||_nodeTrafficDiscovery) && _sessionRevision == revision && _accessToken == token; _nodeTrafficReading = true; try { var since=_nodeTrafficSince; var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token,since); if (!Current()) return; if (!NodeTrafficPresentation.Valid(result, DateTimeOffset.UtcNow)) throw new IOException("监控契约或时间戳无效。"); if(!_canViewNodeTraffic)SetNodeTrafficPermission(true); _nodeTrafficPanel.SetSnapshot(result); var slugs=string.Join(",",result.Nodes.Select(row=>row.Slug).OrderBy(slug=>slug,StringComparer.Ordinal)); if(_nodeTrafficSlugs is not null&&_nodeTrafficSlugs!=slugs)_nodeTrafficSince=null; else { var latest=result.Nodes.Select(row=>row.History.LastOrDefault()?.SampledAt??row.SampledAt) .Where(at=>at is { } sampled&&sampled>=DateTimeOffset.UtcNow.AddSeconds(-15)&&sampled<=DateTimeOffset.UtcNow.AddSeconds(5)) .Select(at=>at!.Value).ToArray(); if(latest.Length>0) { var cursor=latest.Min().AddSeconds(-2); if(_nodeTrafficSince is null||cursor>_nodeTrafficSince)_nodeTrafficSince=cursor; } } _nodeTrafficSlugs=slugs; } 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(ApiException error) when(error.StatusCode==400) { if(Current()) { _nodeTrafficSince=null; _nodeTrafficPanel.Unavailable("正在重新获取服务器采样"); } } catch (OperationCanceledException) { if (Current()) _nodeTrafficPanel.Unavailable("采样请求超时"); } catch (Exception) { if (Current()) _nodeTrafficPanel.Unavailable("服务器采样暂不可用"); } finally { _nodeTrafficReading = false; } } }