using System.Threading.Channels;
using Titano.Protocol;
namespace Titano.Server.Events;
///
/// Fan-out of server events to WebSocket subscribers (BRIEF ยง14.3). Each subscriber has a bounded queue that drops
/// its oldest events when it falls behind, so a slow client never holds up the server.
///
public sealed class EventHub
{
private const int QueueLength = 512;
private readonly Lock _gate = new();
private Channel[] _subscribers = [];
public int SubscriberCount => Volatile.Read(ref _subscribers).Length;
public Subscription Subscribe()
{
var channel = Channel.CreateBounded(new BoundedChannelOptions(QueueLength)
{
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
});
lock (_gate) _subscribers = [.. _subscribers, channel];
return new Subscription(this, channel);
}
public void Publish(ServerEvent e)
{
foreach (var subscriber in Volatile.Read(ref _subscribers)) subscriber.Writer.TryWrite(e);
}
private void Remove(Channel channel)
{
lock (_gate) _subscribers = [.. _subscribers.Where(c => c != channel)];
channel.Writer.TryComplete();
}
/// One subscriber's queue; dispose to unsubscribe.
public sealed class Subscription(EventHub hub, Channel channel) : IDisposable
{
public ChannelReader Reader => channel.Reader;
public void Dispose() => hub.Remove(channel);
}
}