| | 1 | | using Microsoft.Extensions.Logging; |
| | 2 | | using NostrSure.Infrastructure.Client.Abstractions; |
| | 3 | | using System.Net.WebSockets; |
| | 4 | |
|
| | 5 | | namespace NostrSure.Infrastructure.Client.Implementation; |
| | 6 | |
|
| | 7 | | /// <summary> |
| | 8 | | /// Manages WebSocket connection state tracking and notifications |
| | 9 | | /// </summary> |
| | 10 | | public sealed class ConnectionStateManager : IConnectionStateManager |
| | 11 | | { |
| | 12 | | private readonly ILogger<ConnectionStateManager>? _logger; |
| 17 | 13 | | private WebSocketState _currentState = WebSocketState.None; |
| 17 | 14 | | private readonly object _stateLock = new(); |
| | 15 | |
|
| 17 | 16 | | public ConnectionStateManager(ILogger<ConnectionStateManager>? logger = null) |
| 17 | 17 | | { |
| 17 | 18 | | _logger = logger; |
| 17 | 19 | | } |
| | 20 | |
|
| | 21 | | public WebSocketState CurrentState |
| | 22 | | { |
| | 23 | | get |
| 13 | 24 | | { |
| 13 | 25 | | lock (_stateLock) |
| 13 | 26 | | { |
| 13 | 27 | | return _currentState; |
| | 28 | | } |
| 13 | 29 | | } |
| | 30 | | } |
| | 31 | |
|
| 8 | 32 | | public bool IsConnected => CurrentState == WebSocketState.Open; |
| | 33 | |
|
| | 34 | | public event EventHandler<WebSocketState>? StateChanged; |
| | 35 | |
|
| | 36 | | public void UpdateState(WebSocketState newState) |
| 11 | 37 | | { |
| | 38 | | WebSocketState previousState; |
| | 39 | |
|
| 11 | 40 | | lock (_stateLock) |
| 11 | 41 | | { |
| 11 | 42 | | previousState = _currentState; |
| 11 | 43 | | if (previousState == newState) |
| 1 | 44 | | return; // No change, don't fire event |
| | 45 | |
|
| 10 | 46 | | _currentState = newState; |
| 10 | 47 | | } |
| | 48 | |
|
| 10 | 49 | | _logger?.LogDebug("WebSocket state changed from {PreviousState} to {NewState}", |
| 10 | 50 | | previousState, newState); |
| | 51 | |
|
| | 52 | | // Fire event outside the lock to prevent deadlocks |
| 10 | 53 | | StateChanged?.Invoke(this, newState); |
| 11 | 54 | | } |
| | 55 | | } |