33 lines
898 B
C#
33 lines
898 B
C#
using Heimdall.Application.Services;
|
|
using Heimdall.Domain.Enums;
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
|
|
namespace Heimdall.Infrastructure.Services;
|
|
|
|
public class NotificationRateLimiter : INotificationRateLimiter
|
|
{
|
|
private readonly IMemoryCache _cache;
|
|
|
|
public NotificationRateLimiter(IMemoryCache cache) => _cache = cache;
|
|
|
|
public bool ShouldSend(Guid cameraId, EventType type, Guid? recipientId)
|
|
{
|
|
var key = $"notif-rate:{cameraId}:{type}:{recipientId ?? Guid.Empty}";
|
|
|
|
var counter = _cache.GetOrCreate(key, entry =>
|
|
{
|
|
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(1);
|
|
return new AtomicCounter();
|
|
})!;
|
|
|
|
return counter.Increment() <= 20;
|
|
}
|
|
|
|
private sealed class AtomicCounter
|
|
{
|
|
private int _value;
|
|
|
|
public int Increment() => Interlocked.Increment(ref _value);
|
|
}
|
|
}
|