| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using System.Threading.Channels; |
| | | 3 | | |
| | | 4 | | namespace Kestrun.Sse; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// In-memory implementation of <see cref="ISseBroadcaster"/>. |
| | | 8 | | /// Tracks connected clients and broadcasts formatted SSE payloads via per-client channels. |
| | | 9 | | /// </summary> |
| | 6 | 10 | | public sealed class InMemorySseBroadcaster(Serilog.ILogger logger) : ISseBroadcaster |
| | | 11 | | { |
| | 6 | 12 | | private readonly ConcurrentDictionary<string, Channel<string>> _clients = new(); |
| | 6 | 13 | | private readonly Serilog.ILogger _logger = logger; |
| | | 14 | | |
| | | 15 | | /// <inheritdoc /> |
| | 15 | 16 | | public int ConnectedCount => _clients.Count; |
| | | 17 | | |
| | | 18 | | /// <inheritdoc /> |
| | | 19 | | public SseClientSubscription Subscribe(CancellationToken cancellationToken) |
| | | 20 | | { |
| | 7 | 21 | | var clientId = Guid.NewGuid().ToString("n"); |
| | | 22 | | |
| | 7 | 23 | | var channel = Channel.CreateBounded<string>(new BoundedChannelOptions(capacity: 256) |
| | 7 | 24 | | { |
| | 7 | 25 | | SingleReader = true, |
| | 7 | 26 | | SingleWriter = false, |
| | 7 | 27 | | FullMode = BoundedChannelFullMode.DropOldest |
| | 7 | 28 | | }); |
| | | 29 | | |
| | 7 | 30 | | if (!_clients.TryAdd(clientId, channel)) |
| | | 31 | | { |
| | | 32 | | // Extremely unlikely; retry once with a different id. |
| | 0 | 33 | | clientId = Guid.NewGuid().ToString("n"); |
| | 0 | 34 | | if (!_clients.TryAdd(clientId, channel)) |
| | | 35 | | { |
| | 0 | 36 | | throw new InvalidOperationException("Failed to register SSE client."); |
| | | 37 | | } |
| | | 38 | | } |
| | | 39 | | |
| | 7 | 40 | | if (cancellationToken.CanBeCanceled) |
| | | 41 | | { |
| | 2 | 42 | | _ = cancellationToken.Register(() => RemoveClient(clientId)); |
| | | 43 | | } |
| | | 44 | | |
| | 7 | 45 | | _logger.Debug("SSE client subscribed: {ClientId} (total={Count})", clientId, ConnectedCount); |
| | 7 | 46 | | return new SseClientSubscription(clientId, channel.Reader); |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <inheritdoc /> |
| | | 50 | | public ValueTask BroadcastAsync(string? eventName, string data, string? id = null, int? retryMs = null, Cancellation |
| | | 51 | | { |
| | 4 | 52 | | if (_clients.IsEmpty) |
| | | 53 | | { |
| | 1 | 54 | | return ValueTask.CompletedTask; |
| | | 55 | | } |
| | | 56 | | |
| | 3 | 57 | | var payload = SseEventFormatter.Format(eventName, data, id, retryMs); |
| | 3 | 58 | | var failedClientIds = new List<string>(); |
| | | 59 | | |
| | 13 | 60 | | foreach (var kvp in _clients) |
| | | 61 | | { |
| | 4 | 62 | | if (cancellationToken.IsCancellationRequested) |
| | | 63 | | { |
| | 1 | 64 | | break; |
| | | 65 | | } |
| | | 66 | | |
| | 3 | 67 | | if (!kvp.Value.Writer.TryWrite(payload)) |
| | | 68 | | { |
| | 1 | 69 | | failedClientIds.Add(kvp.Key); |
| | | 70 | | } |
| | | 71 | | } |
| | | 72 | | |
| | 8 | 73 | | foreach (var clientId in failedClientIds) |
| | | 74 | | { |
| | 1 | 75 | | RemoveClient(clientId); |
| | | 76 | | } |
| | | 77 | | |
| | 3 | 78 | | return ValueTask.CompletedTask; |
| | | 79 | | } |
| | | 80 | | |
| | | 81 | | private void RemoveClient(string clientId) |
| | | 82 | | { |
| | 2 | 83 | | if (_clients.TryRemove(clientId, out var channel)) |
| | | 84 | | { |
| | 2 | 85 | | _ = channel.Writer.TryComplete(); |
| | 2 | 86 | | _logger.Debug("SSE client removed: {ClientId} (total={Count})", clientId, ConnectedCount); |
| | | 87 | | } |
| | 2 | 88 | | } |
| | | 89 | | } |