| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | |
| | | 3 | | namespace Kestrun.SignalR; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// In-memory thread-safe implementation of <see cref="IConnectionTracker"/>. |
| | | 7 | | /// </summary> |
| | | 8 | | public sealed class InMemoryConnectionTracker : IConnectionTracker |
| | | 9 | | { |
| | 1 | 10 | | private readonly ConcurrentDictionary<string, byte> _connections = new(); |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Gets the current number of connected clients. |
| | | 14 | | /// </summary> |
| | 0 | 15 | | public int ConnectedCount => _connections.Count; |
| | | 16 | | |
| | | 17 | | /// <summary> |
| | | 18 | | /// Records a new connection. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="connectionId">The ID of the connection.</param> |
| | | 21 | | public void OnConnected(string connectionId) |
| | | 22 | | { |
| | 0 | 23 | | if (!string.IsNullOrEmpty(connectionId)) |
| | | 24 | | { |
| | 0 | 25 | | _connections[connectionId] = 1; |
| | | 26 | | } |
| | 0 | 27 | | } |
| | | 28 | | |
| | | 29 | | /// <summary> |
| | | 30 | | /// Records a disconnection. |
| | | 31 | | /// </summary> |
| | | 32 | | /// <param name="connectionId">The ID of the connection.</param> |
| | | 33 | | public void OnDisconnected(string connectionId) |
| | | 34 | | { |
| | 0 | 35 | | if (!string.IsNullOrEmpty(connectionId)) |
| | | 36 | | { |
| | 0 | 37 | | _ = _connections.TryRemove(connectionId, out _); |
| | | 38 | | } |
| | 0 | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Returns a snapshot of current connection identifiers. |
| | | 43 | | /// </summary> |
| | | 44 | | /// <returns>A read-only collection of connection IDs.</returns> |
| | 0 | 45 | | public IReadOnlyCollection<string> GetConnections() => _connections.Keys as IReadOnlyCollection<string> ?? [.. _conn |
| | | 46 | | } |