Windows 0.3.5 traffic trends UI source delta; connection fixes retained; no private history or other platform changes
This commit is contained in:
+209
-35
@@ -10,6 +10,8 @@ internal sealed class NodeTrafficSnapshot
|
||||
[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<NodeTrafficReading> Nodes { get; init; } = [];
|
||||
}
|
||||
|
||||
@@ -26,26 +28,57 @@ internal sealed class NodeTrafficReading
|
||||
[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<NodeTrafficHistoryReading> 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 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.SamplePeriodSeconds is 0 or 1
|
||||
&& 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 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 => Slugs.Contains(n.Slug, StringComparer.Ordinal)
|
||||
&& 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 <= 30));
|
||||
&& (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 && !string.IsNullOrWhiteSpace(row.CounterEpoch);
|
||||
&& 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);
|
||||
@@ -79,16 +112,80 @@ internal readonly record struct NodeTrafficBarRates(long? Ingress, long? Egress)
|
||||
internal sealed class NodeTrafficPanel : CardPanel
|
||||
{
|
||||
private readonly Func<DateTimeOffset> _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 = "等待服务器采样";
|
||||
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(); }
|
||||
private readonly Dictionary<string, TrafficChartTimeline> _histories = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string,SortedDictionary<(DateTimeOffset At,string Epoch),NodeTrafficHistoryReading>> _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<now.AddHours(-1))
|
||||
{records.Remove(records.First().Key);changed=true;}
|
||||
if(changed)
|
||||
{
|
||||
timeline.Reset();
|
||||
string? epoch=null;
|
||||
foreach(var point in records.Values)
|
||||
{
|
||||
if(point.GapBefore||epoch is not null&&epoch!=point.CounterEpoch)timeline.MarkUnavailable(point.SampledAt);
|
||||
epoch=point.CounterEpoch;
|
||||
if(point.Quality=="ok"&&point.Upload is { } up&&point.Download is { } down)
|
||||
timeline.Add(up,down,point.SampledAt);
|
||||
else timeline.MarkUnavailable(point.SampledAt);
|
||||
}
|
||||
}
|
||||
if(!NodeTrafficPresentation.Fresh(row,now) || row.UploadRate is null || row.DownloadRate is null)
|
||||
{ timeline.MarkUnavailable(now); continue; }
|
||||
timeline.AdvanceClock(now);
|
||||
}
|
||||
Invalidate();
|
||||
}
|
||||
internal void Unavailable(string status, bool clear = false)
|
||||
{
|
||||
if(clear) { _snapshot=null; _histories.Clear(); _historyRecords.Clear(); _historySource=null; }
|
||||
else foreach(var timeline in _histories.Values) timeline.MarkUnavailable(_clock());
|
||||
_status=status; Invalidate();
|
||||
}
|
||||
internal NodeTrafficPanel(Func<DateTimeOffset>? clock = null)
|
||||
{
|
||||
_clock = clock ?? (() => DateTimeOffset.UtcNow);
|
||||
AccessibleName = "VPN 服务器流入流出实时速度与累计流量,上入下出细柱";
|
||||
AccessibleName = "各 VPN 服务器流入流出速度趋势,青色为流入,蓝色为流出";
|
||||
}
|
||||
internal static (Rectangle Title, Rectangle[] Rows) TextLayout(Size size, int dpi, int fontHeight)
|
||||
{
|
||||
@@ -139,44 +236,84 @@ internal sealed class NodeTrafficPanel : CardPanel
|
||||
}
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing) _details.Dispose();
|
||||
if (disposing) { _details.Dispose(); _plotFont.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);
|
||||
// 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;
|
||||
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 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<string>();
|
||||
for (var i = 0; i < 2; i++)
|
||||
for (var i = 0; i < rows.Count; i++)
|
||||
{
|
||||
var row = rows[i];
|
||||
var fresh = row is not null && _snapshot is not null && NodeTrafficPresentation.Valid(_snapshot, now)
|
||||
var fresh = envelopeValid
|
||||
&& 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 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)}";
|
||||
+ $" 累计入{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);
|
||||
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 + ";细柱上方为流入,下方为流出,两台使用同一量程,上限 "
|
||||
+ SpeedDisplay.Format(maximum) + "。速率为采样区间平均。服务器整机网卡数据,不是本账号代理流量,不计入套餐用量;过期累计保留采样时间。"
|
||||
AccessibleDescription = _status + ";每台服务器各自一张流入、流出趋势图;青色流入,蓝色流出。近 "+_periodMinutes+" 分钟。"
|
||||
+"服务器真实1秒网卡采样,客户端每5秒获取批次。青色流入(RX),蓝色流出(TX)。包含系统及隧道开销,不是本账号代理用量;过期累计保留采样时间。"
|
||||
+ Environment.NewLine + string.Join(Environment.NewLine, details);
|
||||
if (_detailText != AccessibleDescription)
|
||||
{
|
||||
@@ -191,6 +328,10 @@ 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()
|
||||
{
|
||||
@@ -201,6 +342,8 @@ internal sealed partial class MainForm
|
||||
}
|
||||
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;
|
||||
@@ -208,21 +351,48 @@ internal sealed partial class MainForm
|
||||
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 || _nodeTrafficReading || _preview || _uiOnly || _exiting
|
||||
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 && _sessionRevision == revision && _accessToken == token;
|
||||
bool Current() => !_exiting && !IsDisposed && (_canViewNodeTraffic||_nodeTrafficDiscovery) && _sessionRevision == revision && _accessToken == token;
|
||||
_nodeTrafficReading = true;
|
||||
try
|
||||
{
|
||||
var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token);
|
||||
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)
|
||||
{
|
||||
@@ -233,6 +403,10 @@ internal sealed partial class MainForm
|
||||
{
|
||||
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; }
|
||||
|
||||
Reference in New Issue
Block a user