using System.Collections.Concurrent;
using ClassNotify.Shared.Models;
namespace ClassNotify.Shared.Services;
///
/// Thread-safe client notification buffer and FIFO delivery dispatcher for Windows Service.
/// Guarantees strict FIFO delivery order, single-concurrent flushing via SemaphoreSlim(1,1),
/// and atomic peek-then-dequeue so broken-pipe failures leave the item at the head of the queue.
/// When a backlog exists, new live notifications are enqueued to preserve FIFO order and never bypass pending items.
///
public class ClientNotificationBuffer
{
private readonly ConcurrentQueue _pendingQueue = new();
private readonly SemaphoreSlim _flushLock = new(1, 1);
public int PendingCount => _pendingQueue.Count;
public IReadOnlyCollection GetPendingSnapshot() => _pendingQueue.ToArray();
public void Enqueue(NotificationDto notification)
{
if (notification == null) return;
_pendingQueue.Enqueue(notification);
}
public void Clear()
{
while (_pendingQueue.TryDequeue(out _)) { }
}
///
/// Delivers the notification to the client or safely buffers it.
/// If there is an existing backlog, the notification is enqueued to the tail of the backlog
/// to preserve strict FIFO ordering, and a flush is triggered if connected.
/// If there is no backlog and the client is connected, an immediate live delivery is attempted.
/// If delivery fails, the notification is buffered so it can be flushed on reconnect.
///
public async Task DeliverOrBufferAsync(
NotificationDto notification,
Func isClientConnected,
Func> sendToClientAsync,
int waitAttempts = 0,
int delayMsBetweenAttempts = 500)
{
if (notification == null) return false;
await _flushLock.WaitAsync();
try
{
// Case 1: Existing backlog exists. Must enqueue behind backlog to guarantee FIFO ordering!
if (!_pendingQueue.IsEmpty)
{
_pendingQueue.Enqueue(notification);
if (isClientConnected())
{
await FlushInternalUnderLockAsync(isClientConnected, sendToClientAsync, DateTimeOffset.UtcNow);
}
return false;
}
// Case 2: No backlog. If client is connected, attempt immediate live send.
if (isClientConnected())
{
bool success = false;
try
{
success = await sendToClientAsync(notification);
}
catch
{
success = false;
}
if (success)
{
return true;
}
}
// Case 3: Client handshaking / transient wait window
for (int i = 0; i < waitAttempts; i++)
{
if (delayMsBetweenAttempts > 0)
{
await Task.Delay(delayMsBetweenAttempts);
}
if (isClientConnected())
{
bool success = false;
try
{
success = await sendToClientAsync(notification);
}
catch
{
success = false;
}
if (success)
{
return true;
}
}
}
// Delivery failed or client not connected: buffer notification for next reconnect flush
_pendingQueue.Enqueue(notification);
return false;
}
finally
{
_flushLock.Release();
}
}
///
/// Flushes pending notifications to the connected client.
/// Uses peek-then-dequeue: only dequeues upon verified successful send.
/// If send fails or client disconnects, the failed notification remains at the head of the queue,
/// flushing stops immediately, and strict FIFO order is naturally preserved.
///
public async Task FlushAsync(
Func isClientConnected,
Func> sendToClientAsync,
DateTimeOffset? currentUtc = null)
{
var now = currentUtc ?? DateTimeOffset.UtcNow;
await _flushLock.WaitAsync();
try
{
return await FlushInternalUnderLockAsync(isClientConnected, sendToClientAsync, now);
}
finally
{
_flushLock.Release();
}
}
private async Task FlushInternalUnderLockAsync(
Func isClientConnected,
Func> sendToClientAsync,
DateTimeOffset now)
{
int flushed = 0;
while (_pendingQueue.TryPeek(out var notif))
{
// Drop expired notification while waiting in queue
if (notif.ExpiresAt.HasValue && notif.ExpiresAt.Value <= now)
{
_pendingQueue.TryDequeue(out _);
continue;
}
if (!isClientConnected())
{
// Client not connected: halt flush, leave notif at head of queue
break;
}
bool success;
try
{
success = await sendToClientAsync(notif);
}
catch
{
success = false;
}
if (success)
{
// Dequeue ONLY after successful delivery
_pendingQueue.TryDequeue(out _);
flushed++;
}
else
{
// Send failed (pipe broken mid-send). Do NOT dequeue!
// notif remains at the head of the queue. Halt flushing to preserve FIFO order.
break;
}
}
return flushed;
}
public void Remove(string notificationId)
{
if (string.IsNullOrEmpty(notificationId)) return;
_flushLock.Wait();
try
{
var items = _pendingQueue.ToArray();
while (_pendingQueue.TryDequeue(out _)) { }
foreach (var item in items)
{
if (!string.Equals(item.Id, notificationId, StringComparison.OrdinalIgnoreCase))
{
_pendingQueue.Enqueue(item);
}
}
}
finally
{
_flushLock.Release();
}
}
}