70 lines
2.3 KiB
C#
70 lines
2.3 KiB
C#
using System.Text.RegularExpressions;
|
|||
|
|
|
||
|
|
namespace decePubClient.Services
|
||
|
|
{
|
||
|
|
/// <summary>One request HttpService sent, for the nerd stats.</summary>
|
||
|
|
public sealed record RequestStat(DateTime At, string Method, string Route, int Status, double DurationMs, long? Bytes,
|
||
|
|
int? RateLimitRemaining, DateTime? RateLimitReset);
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// The last requests HttpService sent (a ring of Capacity entries), with route templates instead of ids. It holds no
|
||
|
|
/// bodies and no tokens: method, route, status, duration, size and PrivaPub's rate limit headers only.
|
||
|
|
/// </summary>
|
||
|
|
public partial class RequestStats
|
||
|
|
{
|
||
|
|
public const int Capacity = 200;
|
||
|
|
|
||
|
|
readonly RequestStat[] ring = new RequestStat[Capacity];
|
||
|
|
int next;
|
||
|
|
int count;
|
||
|
|
|
||
|
|
public event Action Recorded;
|
||
|
|
|
||
|
|
public int Count => count;
|
||
|
|
|
||
|
|
public void Record(RequestStat stat)
|
||
|
|
{
|
||
|
|
lock (ring)
|
||
|
|
{
|
||
|
|
ring[next] = stat;
|
||
|
|
next = (next + 1) % Capacity;
|
||
|
|
count = Math.Min(count + 1, Capacity);
|
||
|
|
}
|
||
|
|
Recorded?.Invoke();
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>The recorded requests, newest first.</summary>
|
||
|
|
public List<RequestStat> Latest(int take = Capacity)
|
||
|
|
{
|
||
|
|
lock (ring)
|
||
|
|
{
|
||
|
|
var latest = new List<RequestStat>(Math.Min(take, count));
|
||
|
|
for (var i = 1; i <= Math.Min(take, count); i++)
|
||
|
|
latest.Add(ring[(next - i + Capacity) % Capacity]);
|
||
|
|
return latest;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>The newest request to a route template, or null.</summary>
|
||
|
|
public RequestStat LastOf(string route) => Latest().FirstOrDefault(stat => stat.Route == route);
|
||
|
|
|
||
|
|
/// <summary>The mean duration of the successful requests recorded, in milliseconds.</summary>
|
||
|
|
public double? AverageMs()
|
||
|
|
{
|
||
|
|
var answered = Latest().Where(stat => stat.Status is >= 200 and < 400).ToList();
|
||
|
|
return answered.Count == 0 ? null : answered.Average(stat => stat.DurationMs);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>The route without its query, with ids replaced by :id, so requests to the same endpoint group.</summary>
|
||
|
|
public static string Template(string uri)
|
||
|
|
{
|
||
|
|
var path = uri?.Split('?', 2)[0] ?? string.Empty;
|
||
|
|
if (Uri.TryCreate(path, UriKind.Absolute, out var absolute))
|
||
|
|
path = absolute.AbsolutePath.TrimStart('/');
|
||
|
|
return Id().Replace(path, "/:id$1");
|
||
|
|
}
|
||
|
|
|
||
|
|
[GeneratedRegex(@"/(?:[0-9a-f]{24}|[0-9a-f]{32}|\d{6,}|[0-9A-Za-z_-]{20,})(/|$)")]
|
||
|
|
private static partial Regex Id();
|
||
|
|
}
|
||
|
|
}
|