| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | using System.Diagnostics; |
| | | 3 | | using System.Threading.Channels; |
| | | 4 | | |
| | | 5 | | namespace AsyncResponse.Transports.NATS; |
| | | 6 | | |
| | | 7 | | internal enum NatsSubscriberRole |
| | | 8 | | { |
| | | 9 | | Worker, |
| | | 10 | | ResponseIngress |
| | | 11 | | } |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Applies the acknowledgement, redelivery, and dead-letter policy to JetStream deliveries. |
| | | 15 | | /// <list type="bullet"> |
| | | 16 | | /// <item><description><see cref="NatsAckMode.AckAfterHandlerCompletes"/>: run the handler, then ACK; |
| | | 17 | | /// on failure NAK for redelivery until <see cref="NatsSubscriberOptions.MaxDeliveryAttempts"/>, then |
| | | 18 | | /// dead-letter and terminate.</description></item> |
| | | 19 | | /// <item><description><see cref="NatsAckMode.AckAfterEnqueue"/>: enqueue to a bounded background |
| | | 20 | | /// queue and ACK immediately; background handler failures are dead-lettered and reported.</description></item> |
| | | 21 | | /// </list> |
| | | 22 | | /// </summary> |
| | | 23 | | internal sealed class NatsMessageDispatcher : IAsyncDisposable |
| | | 24 | | { |
| | | 25 | | private readonly Func<NatsJobDelivery, CancellationToken, Task> _handler; |
| | | 26 | | private readonly INatsJetStreamTransport _jetStream; |
| | | 27 | | private readonly NatsAsyncResponseTransportOptions _options; |
| | | 28 | | private readonly NatsSubscriberOptions _subscriberOptions; |
| | | 29 | | private readonly NatsTransportSubjectSchema _schema; |
| | | 30 | | private readonly ILogger _logger; |
| | | 31 | | private readonly NatsSubscriberRole _role; |
| | | 32 | | private readonly string _consumer; |
| | | 33 | | |
| | | 34 | | private readonly Channel<NatsJobDelivery>? _backgroundQueue; |
| | | 35 | | private readonly Task[]? _backgroundWorkers; |
| | | 36 | | private readonly CancellationTokenSource? _backgroundCts; |
| | | 37 | | |
| | | 38 | | /// <summary>Runs the NatsMessageDispatcher operation.</summary> |
| | 3 | 39 | | public NatsMessageDispatcher( |
| | 3 | 40 | | Func<NatsJobDelivery, CancellationToken, Task> handler, |
| | 3 | 41 | | INatsJetStreamTransport jetStream, |
| | 3 | 42 | | NatsAsyncResponseTransportOptions options, |
| | 3 | 43 | | NatsSubscriberOptions subscriberOptions, |
| | 3 | 44 | | NatsTransportSubjectSchema schema, |
| | 3 | 45 | | ILogger logger, |
| | 3 | 46 | | NatsSubscriberRole role, |
| | 3 | 47 | | string consumer) |
| | | 48 | | { |
| | 3 | 49 | | NatsTransportOptionsValidator.ValidateSubscriber(options, subscriberOptions, role.ToString()); |
| | | 50 | | |
| | 3 | 51 | | _handler = handler; |
| | 3 | 52 | | _jetStream = jetStream; |
| | 3 | 53 | | _options = options; |
| | 3 | 54 | | _subscriberOptions = subscriberOptions; |
| | 3 | 55 | | _schema = schema; |
| | 3 | 56 | | _logger = logger; |
| | 3 | 57 | | _role = role; |
| | 3 | 58 | | _consumer = consumer; |
| | | 59 | | |
| | 3 | 60 | | if (subscriberOptions.AckMode is NatsAckMode.AckAfterEnqueue) |
| | | 61 | | { |
| | 3 | 62 | | _backgroundQueue = Channel.CreateBounded<NatsJobDelivery>(new BoundedChannelOptions(subscriberOptions.Backgr |
| | 3 | 63 | | { |
| | 3 | 64 | | SingleReader = false, |
| | 3 | 65 | | SingleWriter = true, |
| | 3 | 66 | | FullMode = BoundedChannelFullMode.Wait |
| | 3 | 67 | | }); |
| | 3 | 68 | | _backgroundCts = new CancellationTokenSource(); |
| | 3 | 69 | | _backgroundWorkers = new Task[subscriberOptions.BackgroundWorkerCount]; |
| | 3 | 70 | | for (var i = 0; i < _backgroundWorkers.Length; i++) |
| | 3 | 71 | | _backgroundWorkers[i] = Task.Run(() => BackgroundWorkerLoopAsync(_backgroundCts.Token)); |
| | | 72 | | } |
| | 3 | 73 | | } |
| | | 74 | | |
| | | 75 | | /// <summary>Handles the delivered message.</summary> |
| | | 76 | | public async Task HandleAsync(NatsJobDelivery delivery, CancellationToken cancellationToken) |
| | | 77 | | { |
| | 3 | 78 | | if (_subscriberOptions.AckMode is NatsAckMode.AckAfterEnqueue) |
| | | 79 | | { |
| | 3 | 80 | | await HandleEarlyAckAsync(delivery, cancellationToken).ConfigureAwait(false); |
| | 3 | 81 | | return; |
| | | 82 | | } |
| | | 83 | | |
| | | 84 | | try |
| | | 85 | | { |
| | 3 | 86 | | await ExecuteHandlerAsync(delivery, cancellationToken).ConfigureAwait(false); |
| | 3 | 87 | | await delivery.AckAsync().ConfigureAwait(false); |
| | 3 | 88 | | } |
| | 3 | 89 | | catch (Exception ex) |
| | | 90 | | { |
| | 2 | 91 | | await HandleFailureAsync(delivery, ex, cancellationToken).ConfigureAwait(false); |
| | | 92 | | } |
| | 3 | 93 | | } |
| | | 94 | | |
| | | 95 | | // Single choke point for handler execution so both ACK modes emit the consumer receive span. |
| | | 96 | | private async Task ExecuteHandlerAsync(NatsJobDelivery delivery, CancellationToken cancellationToken) |
| | | 97 | | { |
| | 3 | 98 | | using var activity = AsyncResponseDiagnostics.StartActivity( |
| | 3 | 99 | | "asyncresponse.nats.receive", |
| | 3 | 100 | | ActivityKind.Consumer); |
| | 3 | 101 | | activity?.SetTag("asyncresponse.transport", "nats"); |
| | 3 | 102 | | activity?.SetTag("asyncresponse.nats.role", _role.ToString()); |
| | 3 | 103 | | activity?.SetTag("asyncresponse.nats.ack_mode", _subscriberOptions.AckMode.ToString()); |
| | 3 | 104 | | activity?.SetTag("messaging.system", "nats"); |
| | 3 | 105 | | activity?.SetTag("messaging.destination.name", delivery.Subject); |
| | 3 | 106 | | activity?.SetTag("messaging.nats.num_delivered", delivery.NumDelivered); |
| | | 107 | | |
| | 3 | 108 | | if (delivery.Headers.TryGetValue(_options.CorrelationIdHeader, out var correlationId)) |
| | 3 | 109 | | AsyncResponseDiagnostics.SetCorrelationId(activity, correlationId); |
| | | 110 | | |
| | | 111 | | try |
| | | 112 | | { |
| | 3 | 113 | | await _handler(delivery, cancellationToken).ConfigureAwait(false); |
| | 3 | 114 | | } |
| | 2 | 115 | | catch (Exception ex) |
| | | 116 | | { |
| | 2 | 117 | | AsyncResponseDiagnostics.SetError(activity, ex); |
| | 3 | 118 | | throw; |
| | | 119 | | } |
| | 3 | 120 | | } |
| | | 121 | | |
| | | 122 | | private async Task HandleEarlyAckAsync(NatsJobDelivery delivery, CancellationToken cancellationToken) |
| | | 123 | | { |
| | | 124 | | // Accept into the background queue and ACK. If the queue is saturated, wait for a worker to |
| | | 125 | | // free a slot instead of NAKing: the wait blocks the consume loop, so the subscriber stops |
| | | 126 | | // pulling new messages until capacity frees rather than churning NAK/redeliver cycles. |
| | 3 | 127 | | if (_backgroundQueue!.Writer.TryWrite(delivery)) |
| | | 128 | | { |
| | 3 | 129 | | await delivery.AckAsync().ConfigureAwait(false); |
| | 3 | 130 | | return; |
| | | 131 | | } |
| | | 132 | | |
| | | 133 | | try |
| | | 134 | | { |
| | 2 | 135 | | _logger.LogDebug("Background queue full for {Role}; pausing the consume loop until capacity frees.", _role); |
| | 2 | 136 | | await _backgroundQueue.Writer.WriteAsync(delivery, cancellationToken).ConfigureAwait(false); |
| | 2 | 137 | | await delivery.AckAsync().ConfigureAwait(false); |
| | 2 | 138 | | } |
| | 2 | 139 | | catch (Exception ex) when (ex is OperationCanceledException or ChannelClosedException) |
| | | 140 | | { |
| | | 141 | | // Subscriber stopping or dispatcher disposing: NAK so JetStream redelivers elsewhere. |
| | 2 | 142 | | _logger.LogDebug("Background queue unavailable for {Role} during shutdown; NAKing message for redelivery.", |
| | 2 | 143 | | await delivery.NakAsync(_subscriberOptions.RedeliveryDelay).ConfigureAwait(false); |
| | | 144 | | } |
| | 3 | 145 | | } |
| | | 146 | | |
| | | 147 | | private async Task BackgroundWorkerLoopAsync(CancellationToken cancellationToken) |
| | | 148 | | { |
| | | 149 | | // Token-less ReadAllAsync: on shutdown the queue is completed and fully drained, so every |
| | | 150 | | // already-ACKed delivery is attempted (with the drain token once the drain budget lapses) |
| | | 151 | | // instead of being silently dropped; each failure is dead-lettered and surfaced below. |
| | 3 | 152 | | await foreach (var delivery in _backgroundQueue!.Reader.ReadAllAsync().ConfigureAwait(false)) |
| | | 153 | | { |
| | | 154 | | try |
| | | 155 | | { |
| | 3 | 156 | | await ExecuteHandlerAsync(delivery, cancellationToken).ConfigureAwait(false); |
| | 3 | 157 | | } |
| | 3 | 158 | | catch (Exception ex) |
| | | 159 | | { |
| | 2 | 160 | | _logger.LogError(ex, "Background handler failed for {Role} on subject {Subject} after early ACK.", _role |
| | 2 | 161 | | await DeadLetterAsync(delivery, ex, CancellationToken.None).ConfigureAwait(false); |
| | 2 | 162 | | await InvokeBackgroundFailureAsync(delivery, ex).ConfigureAwait(false); |
| | 3 | 163 | | } |
| | 3 | 164 | | } |
| | 3 | 165 | | } |
| | | 166 | | |
| | | 167 | | private async Task HandleFailureAsync(NatsJobDelivery delivery, Exception exception, CancellationToken cancellationT |
| | | 168 | | { |
| | 2 | 169 | | var maxAttempts = _subscriberOptions.MaxDeliveryAttempts; |
| | 2 | 170 | | if (maxAttempts > 0 && delivery.NumDelivered >= maxAttempts) |
| | | 171 | | { |
| | 2 | 172 | | _logger.LogError( |
| | 2 | 173 | | exception, |
| | 2 | 174 | | "Message on subject {Subject} ({Role}) failed after {Attempts} attempts; dead-lettering.", |
| | 2 | 175 | | delivery.Subject, |
| | 2 | 176 | | _role, |
| | 2 | 177 | | delivery.NumDelivered); |
| | | 178 | | |
| | 2 | 179 | | var shouldTerminate = await DeadLetterAsync(delivery, exception, cancellationToken).ConfigureAwait(false); |
| | 2 | 180 | | if (shouldTerminate) |
| | | 181 | | { |
| | 2 | 182 | | await delivery.TermAsync().ConfigureAwait(false); |
| | | 183 | | } |
| | | 184 | | else |
| | | 185 | | { |
| | 2 | 186 | | _logger.LogWarning( |
| | 2 | 187 | | exception, |
| | 2 | 188 | | "Dead-letter publish failed for subject {Subject} ({Role}); NAKing so the message can be retried.", |
| | 2 | 189 | | delivery.Subject, |
| | 2 | 190 | | _role); |
| | 2 | 191 | | await delivery.NakAsync(_subscriberOptions.RedeliveryDelay).ConfigureAwait(false); |
| | | 192 | | } |
| | | 193 | | } |
| | | 194 | | else |
| | | 195 | | { |
| | 2 | 196 | | _logger.LogWarning( |
| | 2 | 197 | | exception, |
| | 2 | 198 | | "Message on subject {Subject} ({Role}) failed on attempt {Attempt}; NAKing for redelivery.", |
| | 2 | 199 | | delivery.Subject, |
| | 2 | 200 | | _role, |
| | 2 | 201 | | delivery.NumDelivered); |
| | 2 | 202 | | await delivery.NakAsync(_subscriberOptions.RedeliveryDelay).ConfigureAwait(false); |
| | | 203 | | } |
| | 2 | 204 | | } |
| | | 205 | | |
| | | 206 | | private async Task<bool> DeadLetterAsync(NatsJobDelivery delivery, Exception exception, CancellationToken cancellati |
| | | 207 | | { |
| | 2 | 208 | | if (!_options.DeadLetterEnabled) |
| | | 209 | | { |
| | 2 | 210 | | _logger.LogError( |
| | 2 | 211 | | exception, |
| | 2 | 212 | | "Message on subject {Subject} ({Role}) is unprocessable and dead-lettering is disabled; it will be dropp |
| | 2 | 213 | | delivery.Subject, |
| | 2 | 214 | | _role); |
| | 2 | 215 | | return true; |
| | | 216 | | } |
| | | 217 | | |
| | 2 | 218 | | var headers = new Dictionary<string, string>(delivery.Headers, StringComparer.OrdinalIgnoreCase) |
| | 2 | 219 | | { |
| | 2 | 220 | | ["AR-DeadLetter-Reason"] = SanitizeHeaderValue(exception.Message), |
| | 2 | 221 | | ["AR-DeadLetter-Source-Subject"] = delivery.Subject, |
| | 2 | 222 | | ["AR-DeadLetter-Role"] = _role.ToString() |
| | 2 | 223 | | }; |
| | | 224 | | |
| | | 225 | | try |
| | | 226 | | { |
| | 2 | 227 | | await _jetStream.PublishAsync(_schema.DeadLetterSubject, delivery.Payload, headers, cancellationToken).Confi |
| | 2 | 228 | | _logger.LogInformation("Dead-lettered message from subject {Subject} ({Role}) to {DeadLetterSubject}.", deli |
| | 2 | 229 | | return true; |
| | | 230 | | } |
| | 2 | 231 | | catch (Exception ex) |
| | | 232 | | { |
| | 2 | 233 | | _logger.LogError(ex, "Failed to dead-letter message from subject {Subject} ({Role}).", delivery.Subject, _ro |
| | 2 | 234 | | return false; |
| | | 235 | | } |
| | 2 | 236 | | } |
| | | 237 | | |
| | | 238 | | private async Task InvokeBackgroundFailureAsync(NatsJobDelivery delivery, Exception exception) |
| | | 239 | | { |
| | 2 | 240 | | if (_subscriberOptions.OnBackgroundFailure is null) |
| | 2 | 241 | | return; |
| | | 242 | | |
| | | 243 | | try |
| | | 244 | | { |
| | 2 | 245 | | delivery.Headers.TryGetValue(_options.CorrelationIdHeader, out var correlationId); |
| | 2 | 246 | | var context = new NatsBackgroundFailureContext(delivery.Subject, _consumer, _role.ToString(), delivery.NumDe |
| | 2 | 247 | | await _subscriberOptions.OnBackgroundFailure(context).ConfigureAwait(false); |
| | 2 | 248 | | } |
| | 2 | 249 | | catch (Exception ex) |
| | | 250 | | { |
| | 2 | 251 | | _logger.LogError(ex, "OnBackgroundFailure callback threw for {Role}.", _role); |
| | 2 | 252 | | } |
| | 2 | 253 | | } |
| | | 254 | | |
| | | 255 | | private static string SanitizeHeaderValue(string value) |
| | 3 | 256 | | => value.Replace('\r', ' ').Replace('\n', ' '); |
| | | 257 | | |
| | | 258 | | /// <summary>Releases resources held by this instance.</summary> |
| | | 259 | | public async ValueTask DisposeAsync() |
| | | 260 | | { |
| | 3 | 261 | | if (_backgroundQueue is null) |
| | 3 | 262 | | return; |
| | | 263 | | |
| | 3 | 264 | | _backgroundQueue.Writer.TryComplete(); |
| | | 265 | | try |
| | | 266 | | { |
| | 3 | 267 | | await Task.WhenAll(_backgroundWorkers!).WaitAsync(_subscriberOptions.BackgroundDrainTimeout).ConfigureAwait( |
| | 3 | 268 | | _backgroundCts!.Dispose(); |
| | 3 | 269 | | } |
| | | 270 | | catch (TimeoutException) |
| | | 271 | | { |
| | 2 | 272 | | _logger.LogWarning("Background handlers for {Role} did not drain within {Timeout}.", _role, _subscriberOptio |
| | 2 | 273 | | await _backgroundCts!.CancelAsync().ConfigureAwait(false); |
| | | 274 | | |
| | | 275 | | // The workers are still running and observe _backgroundCts.Token inside ReadAllAsync, so disposing |
| | | 276 | | // it now would throw ObjectDisposedException inside them. Dispose once they actually finish, off |
| | | 277 | | // the shutdown path, so the source is not leaked either. |
| | 3 | 278 | | _ = Task.WhenAll(_backgroundWorkers!).ContinueWith( |
| | 3 | 279 | | _ => _backgroundCts.Dispose(), |
| | 3 | 280 | | CancellationToken.None, |
| | 3 | 281 | | TaskContinuationOptions.ExecuteSynchronously, |
| | 3 | 282 | | TaskScheduler.Default); |
| | | 283 | | } |
| | 2 | 284 | | catch (Exception ex) |
| | | 285 | | { |
| | | 286 | | // WhenAll only completes once every worker has finished, so the source is safe to dispose here. |
| | 2 | 287 | | _logger.LogDebug(ex, "Background worker drain for {Role} ended with an error.", _role); |
| | 2 | 288 | | _backgroundCts!.Dispose(); |
| | 3 | 289 | | } |
| | 3 | 290 | | } |
| | | 291 | | } |