wabbajack/Wabbajack.Services.OSIntegrated/LoggingRateLimiterReporter.cs

61 lines
1.7 KiB
C#
Raw Normal View History

2021-09-27 12:42:46 +00:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.Extensions.Logging;
using Wabbajack.Common;
using Wabbajack.RateLimiter;
2021-10-23 16:51:17 +00:00
namespace Wabbajack.Services.OSIntegrated;
public class LoggingRateLimiterReporter : IDisposable
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
private readonly IEnumerable<IResource> _limiters;
private readonly ILogger<LoggingRateLimiterReporter> _logger;
private readonly Timer _timer;
private StatusReport[] _prevReport;
private long _reportNumber;
public LoggingRateLimiterReporter(ILogger<LoggingRateLimiterReporter> logger, IEnumerable<IResource> limiters)
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
_logger = logger;
_limiters = limiters.ToArray();
_timer = new Timer(StartLoop, null, TimeSpan.FromSeconds(0.25), TimeSpan.FromSeconds(1));
_prevReport = NextReport();
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
public void Dispose()
{
_timer.Dispose();
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
private StatusReport[] NextReport()
{
return _limiters.Select(r => r.StatusReport).ToArray();
}
2021-09-27 12:42:46 +00:00
2021-10-23 16:51:17 +00:00
private void StartLoop(object? state)
{
_reportNumber += 1;
var report = NextReport();
var sb = new StringBuilder();
sb.Append($"[#{_reportNumber}] ");
var found = false;
2021-10-23 16:51:17 +00:00
foreach (var (prev, next, limiter) in _prevReport.Zip(report, _limiters))
2021-09-27 12:42:46 +00:00
{
2021-10-23 16:51:17 +00:00
var throughput = next.Transferred - prev.Transferred;
if (throughput > 0)
{
found = true;
sb.Append($"{limiter.Name}: [{next.Running}/{next.Pending}] {throughput.ToFileSizeString()}/sec ");
}
2021-09-27 12:42:46 +00:00
}
if (found)
_logger.LogInformation(sb.ToString());
2021-10-23 16:51:17 +00:00
_prevReport = report;
2021-09-27 12:42:46 +00:00
}
}