using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
namespace ClassNotify.Shared.Services;
///
/// Client-side idempotent duplicate suppression for at-least-once message delivery.
/// Ensures running clients do not display duplicate popups or trigger multiple TTS announcements
/// when catching up or receiving retransmitted notifications with the same Notification ID.
///
public class ClientNotificationDeduplicator
{
private readonly ConcurrentDictionary _processedMessageIds = new();
private readonly int _maxCapacity;
private readonly TimeSpan _retentionPeriod;
private readonly object _cleanupLock = new();
public ClientNotificationDeduplicator(int maxCapacity = 1000, TimeSpan? retentionPeriod = null)
{
_maxCapacity = maxCapacity;
_retentionPeriod = retentionPeriod ?? TimeSpan.FromHours(24);
}
///
/// Atomically attempts to mark the notification as processed.
///
/// The unique notification ID.
/// True if this is the first time receiving this ID (allow processing); False if duplicate (suppress presentation).
public bool TryProcess(string notificationId)
{
if (string.IsNullOrWhiteSpace(notificationId)) return false;
var now = DateTimeOffset.UtcNow;
if (!_processedMessageIds.TryAdd(notificationId, now))
{
// Key already exists -> atomic duplicate detection
return false;
}
// Bounded capacity protection
if (_processedMessageIds.Count > _maxCapacity)
{
ThreadPool.QueueUserWorkItem(_ => CleanupStaleEntries());
}
return true;
}
///
/// Checks whether an ID has been seen without mutating deduplication state.
///
public bool IsProcessed(string notificationId)
{
return !string.IsNullOrWhiteSpace(notificationId) && _processedMessageIds.ContainsKey(notificationId);
}
public int Count => _processedMessageIds.Count;
public void Clear()
{
_processedMessageIds.Clear();
}
private void CleanupStaleEntries()
{
if (!Monitor.TryEnter(_cleanupLock)) return;
try
{
var threshold = DateTimeOffset.UtcNow.Subtract(_retentionPeriod);
foreach (var kvp in _processedMessageIds)
{
if (kvp.Value < threshold)
{
_processedMessageIds.TryRemove(kvp.Key, out _);
}
}
// If still over capacity after expiry cleanup, purge oldest half
if (_processedMessageIds.Count > _maxCapacity)
{
var removeCount = _processedMessageIds.Count - (_maxCapacity / 2);
var oldestKeys = _processedMessageIds
.OrderBy(kvp => kvp.Value)
.Take(removeCount)
.Select(kvp => kvp.Key)
.ToList();
foreach (var key in oldestKeys)
{
_processedMessageIds.TryRemove(key, out _);
}
}
}
catch
{
// Best effort cleanup
}
finally
{
Monitor.Exit(_cleanupLock);
}
}
}