| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | |
| | | 3 | | namespace NLightning.Infrastructure.Protocol.Services; |
| | | 4 | | |
| | | 5 | | using Domain.Exceptions; |
| | | 6 | | using Domain.Protocol.Interfaces; |
| | | 7 | | using Domain.Protocol.Messages; |
| | | 8 | | using Domain.Protocol.Payloads; |
| | | 9 | | using Domain.Serialization.Interfaces; |
| | | 10 | | using Domain.Transport; |
| | | 11 | | using Exceptions; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Service for sending and receiving messages. |
| | | 15 | | /// </summary> |
| | | 16 | | /// <remarks> |
| | | 17 | | /// This class is used to send and receive messages over a transport service. |
| | | 18 | | /// </remarks> |
| | | 19 | | /// <seealso cref="IMessageService" /> |
| | | 20 | | internal sealed class MessageService : IMessageService |
| | | 21 | | { |
| | | 22 | | private readonly ILogger<IMessageService> _logger; |
| | | 23 | | private readonly IMessageSerializer _messageSerializer; |
| | | 24 | | private readonly ITransportService? _transportService; |
| | | 25 | | |
| | | 26 | | private volatile bool _disposed; |
| | 20 | 27 | | private readonly object _disposeLock = new(); |
| | | 28 | | |
| | | 29 | | /// <inheritdoc /> |
| | | 30 | | public event EventHandler<IMessage?>? OnMessageReceived; |
| | | 31 | | |
| | | 32 | | public event EventHandler<Exception>? OnExceptionRaised; |
| | | 33 | | |
| | | 34 | | /// <inheritdoc /> |
| | 4 | 35 | | public bool IsConnected => _transportService?.IsConnected ?? false; |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Initializes a new <see cref="MessageService"/> class. |
| | | 39 | | /// </summary> |
| | | 40 | | /// <param name="logger">The logger.</param> |
| | | 41 | | /// <param name="messageSerializer">The message serializer.</param> |
| | | 42 | | /// <param name="transportService">The transport service.</param> |
| | 20 | 43 | | public MessageService(ILogger<IMessageService> logger, IMessageSerializer messageSerializer, |
| | 20 | 44 | | ITransportService transportService) |
| | | 45 | | { |
| | 20 | 46 | | _logger = logger; |
| | 20 | 47 | | _messageSerializer = messageSerializer; |
| | 20 | 48 | | _transportService = transportService; |
| | | 49 | | |
| | 20 | 50 | | _transportService.MessageReceived += ReceiveMessage; |
| | 20 | 51 | | _transportService.ExceptionRaised += RaiseException; |
| | 20 | 52 | | } |
| | | 53 | | |
| | | 54 | | /// <inheritdoc /> |
| | | 55 | | /// <exception cref="ObjectDisposedException">Thrown when the object is disposed.</exception> |
| | | 56 | | public async Task SendMessageAsync(IMessage message, bool throwOnException = false, |
| | | 57 | | CancellationToken cancellationToken = default) |
| | | 58 | | { |
| | 8 | 59 | | lock (_disposeLock) |
| | 8 | 60 | | if (_disposed) |
| | | 61 | | { |
| | 4 | 62 | | var connectionException = new ConnectionException($"{nameof(MessageService)} was disposed.", |
| | 4 | 63 | | new ObjectDisposedException(nameof(MessageService))); |
| | 4 | 64 | | if (throwOnException) |
| | 4 | 65 | | throw connectionException; |
| | | 66 | | |
| | 0 | 67 | | RaiseException(this, connectionException); |
| | 0 | 68 | | return; |
| | | 69 | | } |
| | | 70 | | |
| | | 71 | | try |
| | | 72 | | { |
| | 4 | 73 | | if (cancellationToken.IsCancellationRequested) |
| | 0 | 74 | | return; |
| | | 75 | | |
| | 4 | 76 | | if (_transportService == null) |
| | | 77 | | { |
| | 0 | 78 | | var connectionException = new ConnectionException($"{nameof(MessageService)} is not initialized"); |
| | 0 | 79 | | if (throwOnException) |
| | 0 | 80 | | throw connectionException; |
| | | 81 | | |
| | 0 | 82 | | RaiseException(this, connectionException); |
| | 0 | 83 | | return; |
| | | 84 | | } |
| | | 85 | | |
| | 4 | 86 | | await _transportService.WriteMessageAsync(message, cancellationToken); |
| | 4 | 87 | | } |
| | 0 | 88 | | catch (Exception e) |
| | | 89 | | { |
| | 0 | 90 | | var connectionException = new ConnectionException("Failed to send message", e); |
| | 0 | 91 | | if (throwOnException) |
| | 0 | 92 | | throw connectionException; |
| | | 93 | | |
| | 0 | 94 | | RaiseException(this, connectionException); |
| | 0 | 95 | | } |
| | 4 | 96 | | } |
| | | 97 | | |
| | | 98 | | private void ReceiveMessage(object? _, MemoryStream stream) |
| | | 99 | | { |
| | | 100 | | try |
| | | 101 | | { |
| | 4 | 102 | | lock (_disposeLock) |
| | | 103 | | { |
| | 4 | 104 | | if (_disposed) |
| | 0 | 105 | | return; |
| | | 106 | | |
| | 4 | 107 | | var message = _messageSerializer.DeserializeMessageAsync(stream).GetAwaiter().GetResult(); |
| | 4 | 108 | | if (message is not null) |
| | | 109 | | { |
| | 4 | 110 | | OnMessageReceived?.Invoke(this, message); |
| | | 111 | | } |
| | 4 | 112 | | } |
| | 4 | 113 | | } |
| | 0 | 114 | | catch (MessageSerializationException mse) |
| | | 115 | | { |
| | 0 | 116 | | var message = mse.Message; |
| | 0 | 117 | | if (mse.InnerException is PayloadSerializationException pse) |
| | | 118 | | { |
| | 0 | 119 | | message = pse.InnerException is not null ? pse.InnerException.Message : pse.Message; |
| | | 120 | | } |
| | 0 | 121 | | else if (mse.InnerException is not null) |
| | | 122 | | { |
| | 0 | 123 | | message = mse.InnerException.Message; |
| | | 124 | | } |
| | | 125 | | |
| | 0 | 126 | | _logger.LogError(mse, "Failed to deserialize message: {Message}", message); |
| | 0 | 127 | | SendMessageAsync(new ErrorMessage(new ErrorPayload(message))).GetAwaiter().GetResult(); |
| | 0 | 128 | | RaiseException(this, mse); |
| | 0 | 129 | | } |
| | 0 | 130 | | catch (Exception e) |
| | | 131 | | { |
| | 0 | 132 | | _logger.LogError(e, "Failed to receive message"); |
| | 0 | 133 | | RaiseException(this, e); |
| | 0 | 134 | | } |
| | 4 | 135 | | } |
| | | 136 | | |
| | | 137 | | private void RaiseException(object? sender, Exception e) |
| | | 138 | | { |
| | 0 | 139 | | OnExceptionRaised?.Invoke(sender, new ConnectionException("Error received from transportService", e)); |
| | 0 | 140 | | } |
| | | 141 | | |
| | | 142 | | #region Dispose Pattern |
| | | 143 | | |
| | | 144 | | /// <inheritdoc /> |
| | | 145 | | /// <remarks> |
| | | 146 | | /// Disposes the TransportService. |
| | | 147 | | /// </remarks> |
| | | 148 | | public void Dispose() |
| | | 149 | | { |
| | 8 | 150 | | Dispose(true); |
| | 8 | 151 | | GC.SuppressFinalize(this); |
| | 8 | 152 | | } |
| | | 153 | | |
| | | 154 | | private void Dispose(bool disposing) |
| | | 155 | | { |
| | 16 | 156 | | lock (_disposeLock) |
| | | 157 | | { |
| | 16 | 158 | | if (_disposed) |
| | 0 | 159 | | return; |
| | | 160 | | |
| | 16 | 161 | | if (disposing && _transportService is not null) |
| | | 162 | | { |
| | 8 | 163 | | _transportService.MessageReceived -= ReceiveMessage; |
| | 8 | 164 | | _transportService.ExceptionRaised -= RaiseException; |
| | 8 | 165 | | _transportService.Dispose(); |
| | | 166 | | } |
| | | 167 | | |
| | 16 | 168 | | _disposed = true; |
| | 16 | 169 | | } |
| | 16 | 170 | | } |
| | | 171 | | |
| | | 172 | | ~MessageService() |
| | | 173 | | { |
| | 8 | 174 | | Dispose(false); |
| | 16 | 175 | | } |
| | | 176 | | |
| | | 177 | | #endregion |
| | | 178 | | } |