| | 1 | | using Microsoft.Extensions.Logging; |
| | 2 | | using NostrSure.Domain.Entities; |
| | 3 | | using NostrSure.Infrastructure.Client.Abstractions; |
| | 4 | | using NostrSure.Infrastructure.Client.Messages; |
| | 5 | | using System.Collections.Concurrent; |
| | 6 | | using System.Net.WebSockets; |
| | 7 | | using System.Runtime.CompilerServices; |
| | 8 | |
|
| | 9 | | namespace NostrSure.Infrastructure.Client.Implementation; |
| | 10 | |
|
| | 11 | | /// <summary> |
| | 12 | | /// Main Nostr client implementation |
| | 13 | | /// </summary> |
| | 14 | | public class NostrClient : INostrClient |
| | 15 | | { |
| | 16 | | private readonly IWebSocketFactory _webSocketFactory; |
| | 17 | | private readonly IMessageSerializer _messageSerializer; |
| | 18 | | private readonly ISubscriptionManager _subscriptionManager; |
| | 19 | | private readonly IEventDispatcher _eventDispatcher; |
| | 20 | | private readonly IHealthPolicy _healthPolicy; |
| | 21 | | private readonly ILogger<NostrClient>? _logger; |
| | 22 | |
|
| | 23 | | private IWebSocketConnection? _connection; |
| 28 | 24 | | private readonly ConcurrentQueue<NostrMessage> _messageQueue = new(); |
| 28 | 25 | | private readonly CancellationTokenSource _cancellationTokenSource = new(); |
| | 26 | | private bool _disposed; |
| | 27 | |
|
| | 28 | | // Events |
| | 29 | | public event Func<RelayEventMessage, Task>? OnEvent; |
| | 30 | | public event Func<EoseMessage, Task>? OnEndOfStoredEvents; |
| | 31 | | public event Func<NoticeMessage, Task>? OnNotice; |
| | 32 | | public event Func<ClosedMessage, Task>? OnClosed; |
| | 33 | | public event Func<OkMessage, Task>? OnOk; |
| | 34 | | public event Func<Exception, Task>? OnError; |
| | 35 | |
|
| 11 | 36 | | public string? RelayUrl { get; private set; } |
| 12 | 37 | | public bool IsConnected => _connection?.State == WebSocketState.Open; |
| | 38 | |
|
| 28 | 39 | | public NostrClient( |
| 28 | 40 | | IWebSocketFactory webSocketFactory, |
| 28 | 41 | | IMessageSerializer messageSerializer, |
| 28 | 42 | | ISubscriptionManager subscriptionManager, |
| 28 | 43 | | IEventDispatcher eventDispatcher, |
| 28 | 44 | | IHealthPolicy healthPolicy, |
| 28 | 45 | | ILogger<NostrClient>? logger = null) |
| 28 | 46 | | { |
| 28 | 47 | | _webSocketFactory = webSocketFactory ?? throw new ArgumentNullException(nameof(webSocketFactory)); |
| 28 | 48 | | _messageSerializer = messageSerializer ?? throw new ArgumentNullException(nameof(messageSerializer)); |
| 28 | 49 | | _subscriptionManager = subscriptionManager ?? throw new ArgumentNullException(nameof(subscriptionManager)); |
| 28 | 50 | | _eventDispatcher = eventDispatcher ?? throw new ArgumentNullException(nameof(eventDispatcher)); |
| 28 | 51 | | _healthPolicy = healthPolicy ?? throw new ArgumentNullException(nameof(healthPolicy)); |
| 28 | 52 | | _logger = logger; |
| | 53 | |
|
| | 54 | | // Wire up event dispatcher to our events |
| 28 | 55 | | _eventDispatcher.OnEvent += (msg) => OnEvent?.Invoke(msg) ?? Task.CompletedTask; |
| 29 | 56 | | _eventDispatcher.OnEndOfStoredEvents += (msg) => OnEndOfStoredEvents?.Invoke(msg) ?? Task.CompletedTask; |
| 29 | 57 | | _eventDispatcher.OnNotice += (msg) => OnNotice?.Invoke(msg) ?? Task.CompletedTask; |
| 28 | 58 | | _eventDispatcher.OnClosed += (msg) => OnClosed?.Invoke(msg) ?? Task.CompletedTask; |
| 28 | 59 | | _eventDispatcher.OnOk += (msg) => OnOk?.Invoke(msg) ?? Task.CompletedTask; |
| 28 | 60 | | } |
| | 61 | |
|
| | 62 | | public async Task ConnectAsync(string relayUrl, CancellationToken cancellationToken = default) |
| 13 | 63 | | { |
| 13 | 64 | | if (string.IsNullOrWhiteSpace(relayUrl)) |
| 1 | 65 | | throw new ArgumentException("Relay URL cannot be null or empty", nameof(relayUrl)); |
| | 66 | |
|
| 12 | 67 | | if (!Uri.TryCreate(relayUrl, UriKind.Absolute, out var uri)) |
| 1 | 68 | | throw new ArgumentException("Invalid relay URL", nameof(relayUrl)); |
| | 69 | |
|
| 11 | 70 | | if (uri.Scheme != "ws" && uri.Scheme != "wss") |
| 1 | 71 | | throw new ArgumentException("Relay URL must use ws:// or wss:// scheme", nameof(relayUrl)); |
| | 72 | |
|
| 10 | 73 | | var combinedToken = CancellationTokenSource |
| 10 | 74 | | .CreateLinkedTokenSource(cancellationToken, _cancellationTokenSource.Token) |
| 10 | 75 | | .Token; |
| | 76 | |
|
| 10 | 77 | | var attempt = 0; |
| 10 | 78 | | while (!combinedToken.IsCancellationRequested) |
| 10 | 79 | | { |
| | 80 | | try |
| 10 | 81 | | { |
| 10 | 82 | | _connection = _webSocketFactory.Create(); |
| 10 | 83 | | SetupConnectionEvents(); |
| | 84 | |
|
| | 85 | | // Set timeout for connection (requirement R1: within 5 seconds) |
| 10 | 86 | | using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); |
| 10 | 87 | | using var timeoutToken = CancellationTokenSource.CreateLinkedTokenSource( |
| 10 | 88 | | combinedToken, timeoutCts.Token); |
| | 89 | |
|
| 10 | 90 | | await _connection.ConnectAsync(uri, timeoutToken.Token); |
| | 91 | |
|
| 10 | 92 | | RelayUrl = relayUrl; |
| 10 | 93 | | _logger?.LogInformation("Connected to relay: {RelayUrl}", relayUrl); |
| | 94 | |
|
| 10 | 95 | | return; // Success |
| | 96 | | } |
| 0 | 97 | | catch (Exception ex) when (!cancellationToken.IsCancellationRequested) |
| 0 | 98 | | { |
| 0 | 99 | | attempt++; |
| 0 | 100 | | _logger?.LogWarning(ex, "Connection attempt {Attempt} failed to {RelayUrl}", attempt, relayUrl); |
| | 101 | |
|
| 0 | 102 | | if (!_healthPolicy.ShouldRetry(attempt)) |
| 0 | 103 | | { |
| 0 | 104 | | _logger?.LogError("Max connection attempts reached for {RelayUrl}", relayUrl); |
| 0 | 105 | | if (OnError != null) |
| 0 | 106 | | await OnError.Invoke(ex); |
| 0 | 107 | | throw; |
| | 108 | | } |
| | 109 | |
|
| 0 | 110 | | await _healthPolicy.DelayAsync(attempt, combinedToken); |
| 0 | 111 | | } |
| 0 | 112 | | } |
| 10 | 113 | | } |
| | 114 | |
|
| | 115 | | public async Task SubscribeAsync(string subscriptionId, Dictionary<string, object> filter, |
| | 116 | | CancellationToken cancellationToken = default) |
| 5 | 117 | | { |
| 5 | 118 | | if (string.IsNullOrWhiteSpace(subscriptionId)) |
| 0 | 119 | | throw new ArgumentException("Subscription ID cannot be null or empty", nameof(subscriptionId)); |
| | 120 | |
|
| 5 | 121 | | ArgumentNullException.ThrowIfNull(filter); |
| | 122 | |
|
| 5 | 123 | | if (!IsConnected) |
| 1 | 124 | | throw new InvalidOperationException("Not connected to a relay"); |
| | 125 | |
|
| | 126 | | try |
| 4 | 127 | | { |
| 4 | 128 | | _subscriptionManager.AddSubscription(subscriptionId); |
| | 129 | |
|
| 4 | 130 | | var reqMessage = new object[] { "REQ", subscriptionId, filter }; |
| 4 | 131 | | var json = _messageSerializer.Serialize(reqMessage); |
| | 132 | |
|
| 4 | 133 | | await _connection!.SendAsync(json, cancellationToken); |
| 4 | 134 | | _logger?.LogDebug("Sent subscription: {SubscriptionId}", subscriptionId); |
| 4 | 135 | | } |
| 0 | 136 | | catch (Exception ex) |
| 0 | 137 | | { |
| 0 | 138 | | _subscriptionManager.RemoveSubscription(subscriptionId); |
| 0 | 139 | | _logger?.LogError(ex, "Failed to send subscription: {SubscriptionId}", subscriptionId); |
| 0 | 140 | | throw; |
| | 141 | | } |
| 4 | 142 | | } |
| | 143 | |
|
| | 144 | | public async Task CloseSubscriptionAsync(string subscriptionId, CancellationToken cancellationToken = default) |
| 2 | 145 | | { |
| 2 | 146 | | if (string.IsNullOrWhiteSpace(subscriptionId)) |
| 0 | 147 | | throw new ArgumentException("Subscription ID cannot be null or empty", nameof(subscriptionId)); |
| | 148 | |
|
| 2 | 149 | | if (!IsConnected) |
| 0 | 150 | | throw new InvalidOperationException("Not connected to a relay"); |
| | 151 | |
|
| | 152 | | try |
| 2 | 153 | | { |
| 2 | 154 | | var closeMessage = new object[] { "CLOSE", subscriptionId }; |
| 2 | 155 | | var json = _messageSerializer.Serialize(closeMessage); |
| | 156 | |
|
| 2 | 157 | | await _connection!.SendAsync(json, cancellationToken); |
| 2 | 158 | | _subscriptionManager.RemoveSubscription(subscriptionId); |
| | 159 | |
|
| 2 | 160 | | _logger?.LogDebug("Closed subscription: {SubscriptionId}", subscriptionId); |
| 2 | 161 | | } |
| 0 | 162 | | catch (Exception ex) |
| 0 | 163 | | { |
| 0 | 164 | | _logger?.LogError(ex, "Failed to close subscription: {SubscriptionId}", subscriptionId); |
| 0 | 165 | | throw; |
| | 166 | | } |
| 2 | 167 | | } |
| | 168 | |
|
| | 169 | | public async Task PublishAsync(NostrEvent nostrEvent, CancellationToken cancellationToken = default) |
| 3 | 170 | | { |
| 3 | 171 | | ArgumentNullException.ThrowIfNull(nostrEvent); |
| | 172 | |
|
| 3 | 173 | | if (!IsConnected) |
| 1 | 174 | | throw new InvalidOperationException("Not connected to a relay"); |
| | 175 | |
|
| | 176 | | try |
| 2 | 177 | | { |
| 2 | 178 | | var eventMessage = new object[] { "EVENT", nostrEvent }; |
| 2 | 179 | | var json = _messageSerializer.Serialize(eventMessage); |
| | 180 | |
|
| 2 | 181 | | await _connection!.SendAsync(json, cancellationToken); |
| 2 | 182 | | _logger?.LogDebug("Published event: {EventId}", nostrEvent.Id); |
| 2 | 183 | | } |
| 0 | 184 | | catch (Exception ex) |
| 0 | 185 | | { |
| 0 | 186 | | _logger?.LogError(ex, "Failed to publish event: {EventId}", nostrEvent.Id); |
| 0 | 187 | | throw; |
| | 188 | | } |
| 2 | 189 | | } |
| | 190 | |
|
| | 191 | | public async IAsyncEnumerable<NostrMessage> StreamAsync(string? subscriptionId = null, |
| | 192 | | [EnumeratorCancellation] CancellationToken cancellationToken = |
| 1 | 193 | | { |
| 1 | 194 | | var combinedToken = CancellationTokenSource |
| 1 | 195 | | .CreateLinkedTokenSource(cancellationToken, _cancellationTokenSource.Token) |
| 1 | 196 | | .Token; |
| | 197 | |
|
| 1 | 198 | | while (!combinedToken.IsCancellationRequested) |
| 1 | 199 | | { |
| 1 | 200 | | if (_messageQueue.TryDequeue(out var message)) |
| 1 | 201 | | { |
| | 202 | | // Filter by subscription ID if specified |
| 1 | 203 | | if (subscriptionId == null || IsMessageForSubscription(message, subscriptionId)) |
| 1 | 204 | | { |
| 1 | 205 | | yield return message; |
| 0 | 206 | | } |
| 0 | 207 | | } |
| | 208 | | else |
| 0 | 209 | | { |
| | 210 | | // Wait a bit before checking again |
| 0 | 211 | | await Task.Delay(10, combinedToken); |
| 0 | 212 | | } |
| 0 | 213 | | } |
| 1 | 214 | | } |
| | 215 | |
|
| | 216 | | private void SetupConnectionEvents() |
| 10 | 217 | | { |
| 10 | 218 | | if (_connection == null) return; |
| | 219 | |
|
| 10 | 220 | | _connection.MessageReceived += OnMessageReceived; |
| 10 | 221 | | _connection.ErrorOccurred += OnConnectionError; |
| 10 | 222 | | _connection.Disconnected += OnConnectionDisconnected; |
| 10 | 223 | | } |
| | 224 | |
|
| | 225 | | private void OnMessageReceived(object? sender, string json) |
| 2 | 226 | | { |
| | 227 | | try |
| 2 | 228 | | { |
| 2 | 229 | | var message = _messageSerializer.Deserialize(json); |
| 2 | 230 | | _messageQueue.Enqueue(message); |
| 2 | 231 | | _eventDispatcher.Dispatch(message); |
| 2 | 232 | | } |
| 0 | 233 | | catch (Exception ex) |
| 0 | 234 | | { |
| 0 | 235 | | _logger?.LogError(ex, "Failed to process received message: {Json}", json); |
| 0 | 236 | | OnError?.Invoke(ex); |
| 0 | 237 | | } |
| 2 | 238 | | } |
| | 239 | |
|
| | 240 | | private void OnConnectionError(object? sender, Exception ex) |
| 0 | 241 | | { |
| 0 | 242 | | _logger?.LogError(ex, "WebSocket connection error"); |
| 0 | 243 | | OnError?.Invoke(ex); |
| 0 | 244 | | } |
| | 245 | |
|
| | 246 | | private void OnConnectionDisconnected(object? sender, EventArgs e) |
| 0 | 247 | | { |
| 0 | 248 | | _logger?.LogWarning("WebSocket disconnected from {RelayUrl}", RelayUrl); |
| | 249 | |
|
| | 250 | | // Attempt reconnection in background |
| 0 | 251 | | _ = Task.Run(async () => |
| 0 | 252 | | { |
| 0 | 253 | | if (RelayUrl != null && !_cancellationTokenSource.Token.IsCancellationRequested) |
| 0 | 254 | | { |
| 0 | 255 | | try |
| 0 | 256 | | { |
| 0 | 257 | | await ConnectAsync(RelayUrl, _cancellationTokenSource.Token); |
| 0 | 258 | | } |
| 0 | 259 | | catch (Exception ex) |
| 0 | 260 | | { |
| 0 | 261 | | _logger?.LogError(ex, "Failed to reconnect to {RelayUrl}", RelayUrl); |
| 0 | 262 | | await OnError?.Invoke(ex)!; |
| 0 | 263 | | } |
| 0 | 264 | | } |
| 0 | 265 | | }); |
| 0 | 266 | | } |
| | 267 | |
|
| | 268 | | private static bool IsMessageForSubscription(NostrMessage message, string subscriptionId) |
| 1 | 269 | | { |
| 1 | 270 | | return message switch |
| 1 | 271 | | { |
| 0 | 272 | | RelayEventMessage eventMsg => eventMsg.SubscriptionId == subscriptionId, |
| 1 | 273 | | EoseMessage eoseMsg => eoseMsg.SubscriptionId == subscriptionId, |
| 0 | 274 | | ClosedMessage closedMsg => closedMsg.SubscriptionId == subscriptionId, |
| 0 | 275 | | _ => true // NOTICE, OK messages are global |
| 1 | 276 | | }; |
| 1 | 277 | | } |
| | 278 | |
|
| | 279 | | public void Dispose() |
| 23 | 280 | | { |
| 23 | 281 | | if (!_disposed) |
| 23 | 282 | | { |
| 23 | 283 | | _cancellationTokenSource.Cancel(); |
| 23 | 284 | | _connection?.Dispose(); |
| 23 | 285 | | _cancellationTokenSource.Dispose(); |
| 23 | 286 | | _disposed = true; |
| 23 | 287 | | } |
| 23 | 288 | | } |
| | 289 | | } |