void.cat/VoidCat/Services/InMemory/InMemoryStatsController.cs

76 lines
2.1 KiB
C#
Raw Normal View History

2022-01-28 00:18:27 +00:00
using Microsoft.Extensions.Caching.Memory;
2022-02-21 22:35:06 +00:00
using VoidCat.Model;
2022-02-16 16:33:00 +00:00
using VoidCat.Services.Abstractions;
2022-01-25 23:39:51 +00:00
2022-02-21 09:39:59 +00:00
namespace VoidCat.Services.InMemory;
2022-02-16 16:33:00 +00:00
2022-02-16 23:19:31 +00:00
public class InMemoryStatsController : IStatsCollector, IStatsReporter
2022-01-25 17:57:07 +00:00
{
2022-02-16 23:19:31 +00:00
private static readonly Guid Global = new Guid("{A98DFDCC-C4E1-4D42-B818-912086FC6157}");
2022-02-16 16:33:00 +00:00
private readonly IMemoryCache _cache;
2022-02-16 23:19:31 +00:00
public InMemoryStatsController(IMemoryCache cache)
2022-02-16 16:33:00 +00:00
{
_cache = cache;
}
2022-06-14 10:46:31 +00:00
/// <inheritdoc />
2022-02-16 16:33:00 +00:00
public ValueTask TrackIngress(Guid id, ulong amount)
2022-01-25 17:57:07 +00:00
{
2022-02-16 16:33:00 +00:00
Incr(IngressKey(id), amount);
2022-02-16 23:19:31 +00:00
Incr(IngressKey(Global), amount);
2022-02-16 16:33:00 +00:00
return ValueTask.CompletedTask;
2022-01-25 17:57:07 +00:00
}
2022-02-16 16:33:00 +00:00
2022-06-14 10:46:31 +00:00
/// <inheritdoc />
2022-02-16 16:33:00 +00:00
public ValueTask TrackEgress(Guid id, ulong amount)
{
Incr(EgressKey(id), amount);
2022-02-16 23:19:31 +00:00
Incr(EgressKey(Global), amount);
2022-02-16 16:33:00 +00:00
return ValueTask.CompletedTask;
}
2022-06-14 10:46:31 +00:00
/// <inheritdoc />
2022-02-16 16:33:00 +00:00
public ValueTask<Bandwidth> GetBandwidth()
2022-02-16 23:19:31 +00:00
=> ValueTask.FromResult(GetBandwidthInternal(Global));
2022-02-16 16:33:00 +00:00
2022-06-14 10:46:31 +00:00
/// <inheritdoc />
public ValueTask<IReadOnlyList<BandwidthPoint>> GetBandwidth(DateTime start, DateTime end)
{
throw new NotImplementedException();
}
/// <inheritdoc />
2022-02-16 16:33:00 +00:00
public ValueTask<Bandwidth> GetBandwidth(Guid id)
=> ValueTask.FromResult(GetBandwidthInternal(id));
2022-06-14 10:46:31 +00:00
/// <inheritdoc />
public ValueTask<IReadOnlyList<BandwidthPoint>> GetBandwidth(Guid id, DateTime start, DateTime end)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public ValueTask Delete(Guid id)
{
_cache.Remove(EgressKey(id));
return ValueTask.CompletedTask;
}
2022-02-16 16:33:00 +00:00
private Bandwidth GetBandwidthInternal(Guid id)
{
var i = _cache.Get(IngressKey(id)) as ulong?;
var o = _cache.Get(EgressKey(id)) as ulong?;
return new(i ?? 0UL, o ?? 0UL);
}
private void Incr(string k, ulong amount)
{
ulong v;
_cache.TryGetValue(k, out v);
_cache.Set(k, v + amount);
}
private string IngressKey(Guid id) => $"stats:ingress:{id}";
private string EgressKey(Guid id) => $"stats:egress:{id}";
2022-06-14 10:46:31 +00:00
}