using System.Text.RegularExpressions;
namespace decePubClient.Services
{
/// One request HttpService sent, for the nerd stats.
public sealed record RequestStat(DateTime At, string Method, string Route, int Status, double DurationMs, long? Bytes,
int? RateLimitRemaining, DateTime? RateLimitReset);
///
/// 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.
///
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();
}
/// The recorded requests, newest first.
public List Latest(int take = Capacity)
{
lock (ring)
{
var latest = new List(Math.Min(take, count));
for (var i = 1; i <= Math.Min(take, count); i++)
latest.Add(ring[(next - i + Capacity) % Capacity]);
return latest;
}
}
/// The newest request to a route template, or null.
public RequestStat LastOf(string route) => Latest().FirstOrDefault(stat => stat.Route == route);
/// The mean duration of the successful requests recorded, in milliseconds.
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);
}
/// The route without its query, with ids replaced by :id, so requests to the same endpoint group.
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();
}
}