| | | 1 | | using Microsoft.Extensions.Logging; |
| | | 2 | | using System.Diagnostics; |
| | | 3 | | using System.Threading.Channels; |
| | | 4 | | |
| | | 5 | | namespace AsyncResponse.Transports.AzureServiceBus; |
| | | 6 | | |
| | | 7 | | internal enum AzureServiceBusSubscriberRole |
| | | 8 | | { |
| | | 9 | | Worker, |
| | | 10 | | ResponseIngress |
| | | 11 | | } |
| | | 12 | | |
| | | 13 | | internal abstract class AzureServiceBusMessageDispatcher : IAsyncDisposable |
| | | 14 | | { |
| | | 15 | | private readonly Func<AzureServiceBusTransportDelivery, CancellationToken, Task> _handler; |
| | | 16 | | private readonly AzureServiceBusAsyncResponseOptions _transportOptions; |
| | | 17 | | private readonly AzureServiceBusSubscriberOptions _subscriberOptions; |
| | | 18 | | private readonly string _queue; |
| | | 19 | | private readonly AzureServiceBusSubscriberRole _role; |
| | | 20 | | |
| | 3 | 21 | | protected AzureServiceBusMessageDispatcher( |
| | 3 | 22 | | Func<AzureServiceBusTransportDelivery, CancellationToken, Task> handler, |
| | 3 | 23 | | AzureServiceBusAsyncResponseOptions transportOptions, |
| | 3 | 24 | | AzureServiceBusSubscriberOptions subscriberOptions, |
| | 3 | 25 | | ILogger logger, |
| | 3 | 26 | | string queue, |
| | 3 | 27 | | AzureServiceBusSubscriberRole role) |
| | | 28 | | { |
| | 3 | 29 | | _handler = handler; |
| | 3 | 30 | | _transportOptions = transportOptions; |
| | 3 | 31 | | _subscriberOptions = subscriberOptions; |
| | 3 | 32 | | Logger = logger; |
| | 3 | 33 | | _queue = queue; |
| | 3 | 34 | | _role = role; |
| | 3 | 35 | | } |
| | | 36 | | |
| | | 37 | | protected ILogger Logger { get; } |
| | 3 | 38 | | protected int MaxDeliveryAttempts => _subscriberOptions.MaxDeliveryAttempts; |
| | | 39 | | |
| | | 40 | | /// <summary>Creates the dispatcher configured by the subscriber options.</summary> |
| | | 41 | | public static AzureServiceBusMessageDispatcher Create( |
| | | 42 | | Func<AzureServiceBusTransportDelivery, CancellationToken, Task> handler, |
| | | 43 | | AzureServiceBusAsyncResponseOptions transportOptions, |
| | | 44 | | AzureServiceBusSubscriberOptions subscriberOptions, |
| | | 45 | | ILogger logger, |
| | | 46 | | string queue, |
| | | 47 | | AzureServiceBusSubscriberRole role) |
| | | 48 | | { |
| | 3 | 49 | | AzureServiceBusOptionsValidator.ValidateSubscriber(transportOptions, subscriberOptions, role); |
| | | 50 | | |
| | 3 | 51 | | return subscriberOptions.AckMode == AzureServiceBusAckMode.AckAfterHandlerCompletes |
| | 3 | 52 | | ? new AwaitingAzureServiceBusMessageDispatcher( |
| | 3 | 53 | | handler, |
| | 3 | 54 | | transportOptions, |
| | 3 | 55 | | subscriberOptions, |
| | 3 | 56 | | logger, |
| | 3 | 57 | | queue, |
| | 3 | 58 | | role) |
| | 3 | 59 | | : new QueuedAzureServiceBusMessageDispatcher( |
| | 3 | 60 | | handler, |
| | 3 | 61 | | transportOptions, |
| | 3 | 62 | | subscriberOptions, |
| | 3 | 63 | | logger, |
| | 3 | 64 | | queue, |
| | 3 | 65 | | role); |
| | | 66 | | } |
| | | 67 | | |
| | | 68 | | /// <summary>Validates the supplied subscriber options.</summary> |
| | | 69 | | public static void ValidateOptions( |
| | | 70 | | AzureServiceBusAsyncResponseOptions transportOptions, |
| | | 71 | | AzureServiceBusSubscriberOptions subscriberOptions, |
| | | 72 | | AzureServiceBusSubscriberRole role) |
| | 3 | 73 | | => AzureServiceBusOptionsValidator.ValidateSubscriber(transportOptions, subscriberOptions, role); |
| | | 74 | | |
| | | 75 | | /// <summary>Handles the delivered message.</summary> |
| | | 76 | | public abstract Task HandleAsync( |
| | | 77 | | AzureServiceBusTransportDelivery delivery, |
| | | 78 | | CancellationToken subscriberCancellationToken); |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// Whether the dispatcher can accept more deliveries right now. Awaiting dispatchers always can |
| | | 82 | | /// (handlers run inline); the queued dispatcher returns <c>false</c> while its bounded queue is |
| | | 83 | | /// saturated so the receive loop stops pulling messages instead of receiving and abandoning them — |
| | | 84 | | /// every abandon burns <c>DeliveryCount</c> toward the entity's MaxDeliveryCount. |
| | | 85 | | /// </summary> |
| | 1 | 86 | | public virtual bool CanAcceptMore => true; |
| | | 87 | | |
| | | 88 | | /// <summary> |
| | | 89 | | /// Number of deliveries the dispatcher can accept right now. The receive loop requests at most |
| | | 90 | | /// this many messages per receive in early-ACK mode so a burst never overflows the background queue. |
| | | 91 | | /// </summary> |
| | 3 | 92 | | public virtual int FreeCapacity => int.MaxValue; |
| | | 93 | | |
| | | 94 | | /// <summary> |
| | | 95 | | /// Waits until the dispatcher can accept at least one more delivery. Completes immediately for |
| | | 96 | | /// awaiting dispatchers; the queued dispatcher waits for a background worker to free a slot. |
| | | 97 | | /// </summary> |
| | 3 | 98 | | public virtual ValueTask WaitForCapacityAsync(CancellationToken cancellationToken) => ValueTask.CompletedTask; |
| | | 99 | | |
| | | 100 | | /// <summary>Releases resources held by this instance.</summary> |
| | 3 | 101 | | public virtual ValueTask DisposeAsync() => ValueTask.CompletedTask; |
| | | 102 | | |
| | | 103 | | protected async Task ExecuteHandlerAsync( |
| | | 104 | | AzureServiceBusTransportDelivery delivery, |
| | | 105 | | CancellationToken cancellationToken, |
| | | 106 | | bool logFailures = true) |
| | | 107 | | { |
| | 3 | 108 | | using var activity = AsyncResponseDiagnostics.StartActivity( |
| | 3 | 109 | | "asyncresponse.azure_service_bus.receive", |
| | 3 | 110 | | ActivityKind.Consumer); |
| | 3 | 111 | | activity?.SetTag("asyncresponse.transport", "azure_service_bus"); |
| | 3 | 112 | | activity?.SetTag("asyncresponse.azure_service_bus.role", _role.ToString()); |
| | 3 | 113 | | activity?.SetTag("asyncresponse.azure_service_bus.ack_mode", _subscriberOptions.AckMode.ToString()); |
| | 3 | 114 | | activity?.SetTag("messaging.system", "azure_service_bus"); |
| | 3 | 115 | | activity?.SetTag("messaging.destination.name", _queue); |
| | 3 | 116 | | activity?.SetTag("messaging.message.id", delivery.MessageId); |
| | 3 | 117 | | activity?.SetTag("messaging.azure_service_bus.sequence_number", delivery.SequenceNumber); |
| | | 118 | | |
| | 3 | 119 | | if (!string.IsNullOrWhiteSpace(delivery.CorrelationId)) |
| | 3 | 120 | | AsyncResponseDiagnostics.SetCorrelationId(activity, delivery.CorrelationId); |
| | | 121 | | |
| | | 122 | | try |
| | | 123 | | { |
| | 3 | 124 | | await _handler(delivery, cancellationToken).ConfigureAwait(false); |
| | 3 | 125 | | } |
| | 2 | 126 | | catch (Exception ex) |
| | | 127 | | { |
| | 2 | 128 | | if (logFailures) |
| | 2 | 129 | | Logger.LogError(ex, "Azure Service Bus message handling failed for message {MessageId}.", delivery.Messa |
| | 2 | 130 | | AsyncResponseDiagnostics.SetError(activity, ex); |
| | 3 | 131 | | throw; |
| | | 132 | | } |
| | 3 | 133 | | } |
| | | 134 | | |
| | | 135 | | protected async ValueTask NotifyBackgroundFailureAsync( |
| | | 136 | | AzureServiceBusTransportDelivery delivery, |
| | | 137 | | Exception exception, |
| | | 138 | | string queue, |
| | | 139 | | AzureServiceBusSubscriberRole role) |
| | | 140 | | { |
| | 2 | 141 | | var callback = _subscriberOptions.OnBackgroundFailure; |
| | 2 | 142 | | if (callback is null) |
| | 2 | 143 | | return; |
| | | 144 | | |
| | | 145 | | try |
| | | 146 | | { |
| | 2 | 147 | | var context = new AzureServiceBusBackgroundFailureContext( |
| | 2 | 148 | | queue, |
| | 2 | 149 | | role.ToString(), |
| | 2 | 150 | | delivery.SequenceNumber, |
| | 2 | 151 | | delivery.MessageId, |
| | 2 | 152 | | delivery.CorrelationId ?? TryReadApplicationCorrelationId(delivery), |
| | 2 | 153 | | exception); |
| | 2 | 154 | | await callback(context).ConfigureAwait(false); |
| | 2 | 155 | | } |
| | 2 | 156 | | catch (Exception callbackException) |
| | | 157 | | { |
| | 2 | 158 | | Logger.LogError( |
| | 2 | 159 | | callbackException, |
| | 2 | 160 | | "Azure Service Bus background failure callback failed for already-completed message {MessageId} on {Queu |
| | 2 | 161 | | delivery.MessageId, |
| | 2 | 162 | | queue); |
| | 2 | 163 | | } |
| | 2 | 164 | | } |
| | | 165 | | |
| | | 166 | | private string? TryReadApplicationCorrelationId(AzureServiceBusTransportDelivery delivery) |
| | | 167 | | { |
| | 2 | 168 | | if (!string.IsNullOrWhiteSpace(_transportOptions.CorrelationIdProperty) |
| | 2 | 169 | | && delivery.ApplicationProperties.TryGetValue(_transportOptions.CorrelationIdProperty, out var value)) |
| | | 170 | | { |
| | 2 | 171 | | return AzureServiceBusCorrelationIdExtractor.TryConvertProperty(value); |
| | | 172 | | } |
| | | 173 | | |
| | 3 | 174 | | return null; |
| | | 175 | | } |
| | | 176 | | } |
| | | 177 | | |
| | | 178 | | internal sealed class AwaitingAzureServiceBusMessageDispatcher( |
| | | 179 | | Func<AzureServiceBusTransportDelivery, CancellationToken, Task> handler, |
| | | 180 | | AzureServiceBusAsyncResponseOptions transportOptions, |
| | | 181 | | AzureServiceBusSubscriberOptions subscriberOptions, |
| | | 182 | | ILogger logger, |
| | | 183 | | string queue, |
| | | 184 | | AzureServiceBusSubscriberRole role) |
| | | 185 | | : AzureServiceBusMessageDispatcher(handler, transportOptions, subscriberOptions, logger, queue, role) |
| | | 186 | | { |
| | | 187 | | /// <summary>Handles the delivered message.</summary> |
| | | 188 | | public override async Task HandleAsync( |
| | | 189 | | AzureServiceBusTransportDelivery delivery, |
| | | 190 | | CancellationToken subscriberCancellationToken) |
| | | 191 | | { |
| | | 192 | | try |
| | | 193 | | { |
| | | 194 | | await ExecuteHandlerAsync(delivery, subscriberCancellationToken).ConfigureAwait(false); |
| | | 195 | | await delivery.CompleteAsync().ConfigureAwait(false); |
| | | 196 | | } |
| | | 197 | | catch (Exception ex) |
| | | 198 | | { |
| | | 199 | | if (MaxDeliveryAttempts > 0 && delivery.DeliveryCount >= MaxDeliveryAttempts) |
| | | 200 | | { |
| | | 201 | | await delivery.DeadLetterAsync( |
| | | 202 | | "AsyncResponseHandlerFailed", |
| | | 203 | | ex.Message).ConfigureAwait(false); |
| | | 204 | | return; |
| | | 205 | | } |
| | | 206 | | |
| | | 207 | | await delivery.AbandonAsync().ConfigureAwait(false); |
| | | 208 | | } |
| | | 209 | | } |
| | | 210 | | } |
| | | 211 | | |
| | | 212 | | internal sealed class QueuedAzureServiceBusMessageDispatcher : AzureServiceBusMessageDispatcher |
| | | 213 | | { |
| | | 214 | | private readonly Channel<AzureServiceBusTransportDelivery> _queue; |
| | | 215 | | private readonly Task[] _workers; |
| | | 216 | | private readonly CancellationTokenSource _drainCancellation = new(); |
| | | 217 | | private readonly TimeSpan _drainTimeout; |
| | | 218 | | private readonly int _capacity; |
| | | 219 | | private readonly string _queueName; |
| | | 220 | | private readonly AzureServiceBusSubscriberRole _role; |
| | | 221 | | private int _pendingCount; |
| | | 222 | | private int _runningCount; |
| | | 223 | | private int _disposeStarted; |
| | | 224 | | |
| | | 225 | | /// <summary>Creates an ACK-after-enqueue dispatcher with a bounded background queue.</summary> |
| | | 226 | | public QueuedAzureServiceBusMessageDispatcher( |
| | | 227 | | Func<AzureServiceBusTransportDelivery, CancellationToken, Task> handler, |
| | | 228 | | AzureServiceBusAsyncResponseOptions transportOptions, |
| | | 229 | | AzureServiceBusSubscriberOptions subscriberOptions, |
| | | 230 | | ILogger logger, |
| | | 231 | | string queue, |
| | | 232 | | AzureServiceBusSubscriberRole role) |
| | | 233 | | : base(handler, transportOptions, subscriberOptions, logger, queue, role) |
| | | 234 | | { |
| | | 235 | | _drainTimeout = subscriberOptions.BackgroundDrainTimeout; |
| | | 236 | | _capacity = subscriberOptions.BackgroundQueueCapacity; |
| | | 237 | | _queueName = queue; |
| | | 238 | | _role = role; |
| | | 239 | | _queue = Channel.CreateBounded<AzureServiceBusTransportDelivery>(new BoundedChannelOptions(subscriberOptions.Bac |
| | | 240 | | { |
| | | 241 | | AllowSynchronousContinuations = false, |
| | | 242 | | FullMode = BoundedChannelFullMode.Wait, |
| | | 243 | | SingleReader = subscriberOptions.BackgroundWorkerCount == 1, |
| | | 244 | | SingleWriter = false |
| | | 245 | | }); |
| | | 246 | | |
| | | 247 | | _workers = Enumerable.Range(0, subscriberOptions.BackgroundWorkerCount) |
| | | 248 | | .Select(workerIndex => Task.Run(() => RunWorkerAsync(workerIndex))) |
| | | 249 | | .ToArray(); |
| | | 250 | | |
| | | 251 | | Logger.LogInformation( |
| | | 252 | | "Created Azure Service Bus ACK-after-enqueue dispatcher for {Queue} with {WorkerCount} worker(s), queue capa |
| | | 253 | | _queueName, |
| | | 254 | | subscriberOptions.BackgroundWorkerCount, |
| | | 255 | | subscriberOptions.BackgroundQueueCapacity, |
| | | 256 | | _drainTimeout); |
| | | 257 | | } |
| | | 258 | | |
| | | 259 | | internal int PendingCount => Volatile.Read(ref _pendingCount); |
| | | 260 | | internal int RunningCount => Volatile.Read(ref _runningCount); |
| | | 261 | | |
| | | 262 | | public override bool CanAcceptMore => Volatile.Read(ref _pendingCount) < _capacity; |
| | | 263 | | |
| | | 264 | | public override int FreeCapacity => Math.Max(0, _capacity - Volatile.Read(ref _pendingCount)); |
| | | 265 | | |
| | | 266 | | public override async ValueTask WaitForCapacityAsync(CancellationToken cancellationToken) |
| | | 267 | | { |
| | | 268 | | // WaitToWriteAsync completes when the bounded channel has room (or the channel is completed |
| | | 269 | | // during dispose, in which case there is nothing left to gate). |
| | | 270 | | while (!CanAcceptMore) |
| | | 271 | | { |
| | | 272 | | if (!await _queue.Writer.WaitToWriteAsync(cancellationToken).ConfigureAwait(false)) |
| | | 273 | | return; |
| | | 274 | | } |
| | | 275 | | } |
| | | 276 | | |
| | | 277 | | /// <summary>Handles the delivered message.</summary> |
| | | 278 | | public override async Task HandleAsync( |
| | | 279 | | AzureServiceBusTransportDelivery delivery, |
| | | 280 | | CancellationToken subscriberCancellationToken) |
| | | 281 | | { |
| | | 282 | | Interlocked.Increment(ref _pendingCount); |
| | | 283 | | if (!_queue.Writer.TryWrite(delivery)) |
| | | 284 | | { |
| | | 285 | | // The receive loop gates on free capacity, so this only covers the residual race between |
| | | 286 | | // its capacity check and this write. The abandon burns one DeliveryCount, but the loop |
| | | 287 | | // never receives while saturated, so a healthy message cannot repeat this path toward |
| | | 288 | | // the entity's MaxDeliveryCount. |
| | | 289 | | Interlocked.Decrement(ref _pendingCount); |
| | | 290 | | Logger.LogWarning( |
| | | 291 | | "Azure Service Bus background queue rejected message {MessageId} for {Queue}; abandoning for redelivery. |
| | | 292 | | delivery.MessageId, |
| | | 293 | | _queueName, |
| | | 294 | | PendingCount, |
| | | 295 | | RunningCount); |
| | | 296 | | await delivery.AbandonAsync().ConfigureAwait(false); |
| | | 297 | | return; |
| | | 298 | | } |
| | | 299 | | |
| | | 300 | | // The delivery now belongs to a background worker, which decrements _pendingCount when it dequeues. |
| | | 301 | | // Do not touch the counter or abandon here, even if the Complete below fails — the message is already |
| | | 302 | | // executing in-process and abandoning it would trigger a duplicate execution via redelivery. |
| | | 303 | | try |
| | | 304 | | { |
| | | 305 | | await delivery.CompleteAsync().ConfigureAwait(false); |
| | | 306 | | } |
| | | 307 | | catch (Exception ex) |
| | | 308 | | { |
| | | 309 | | Logger.LogError( |
| | | 310 | | ex, |
| | | 311 | | "Failed to complete Azure Service Bus message {MessageId} for {Queue} after enqueue; it is being process |
| | | 312 | | delivery.MessageId, |
| | | 313 | | _queueName); |
| | | 314 | | } |
| | | 315 | | } |
| | | 316 | | |
| | | 317 | | /// <summary>Releases resources held by this instance.</summary> |
| | | 318 | | public override async ValueTask DisposeAsync() |
| | | 319 | | { |
| | | 320 | | if (Interlocked.Exchange(ref _disposeStarted, 1) != 0) |
| | | 321 | | return; |
| | | 322 | | |
| | | 323 | | Logger.LogInformation( |
| | | 324 | | "Draining Azure Service Bus ACK-after-enqueue dispatcher for {Queue}. Pending={PendingCount}, Running={Runni |
| | | 325 | | _queueName, |
| | | 326 | | PendingCount, |
| | | 327 | | RunningCount); |
| | | 328 | | _queue.Writer.TryComplete(); |
| | | 329 | | |
| | | 330 | | try |
| | | 331 | | { |
| | | 332 | | await Task.WhenAll(_workers).WaitAsync(_drainTimeout).ConfigureAwait(false); |
| | | 333 | | _drainCancellation.Dispose(); |
| | | 334 | | } |
| | | 335 | | catch (TimeoutException ex) |
| | | 336 | | { |
| | | 337 | | _drainCancellation.Cancel(); |
| | | 338 | | Logger.LogWarning( |
| | | 339 | | ex, |
| | | 340 | | "Timed out while draining Azure Service Bus ACK-after-enqueue dispatcher for {Queue}. Pending={PendingCo |
| | | 341 | | _queueName, |
| | | 342 | | PendingCount, |
| | | 343 | | RunningCount); |
| | | 344 | | |
| | | 345 | | _ = Task.WhenAll(_workers).ContinueWith( |
| | | 346 | | _ => _drainCancellation.Dispose(), |
| | | 347 | | CancellationToken.None, |
| | | 348 | | TaskContinuationOptions.ExecuteSynchronously, |
| | | 349 | | TaskScheduler.Default); |
| | | 350 | | } |
| | | 351 | | } |
| | | 352 | | |
| | | 353 | | private async Task RunWorkerAsync(int workerIndex) |
| | | 354 | | { |
| | | 355 | | await foreach (var delivery in _queue.Reader.ReadAllAsync().ConfigureAwait(false)) |
| | | 356 | | { |
| | | 357 | | Interlocked.Decrement(ref _pendingCount); |
| | | 358 | | Interlocked.Increment(ref _runningCount); |
| | | 359 | | |
| | | 360 | | try |
| | | 361 | | { |
| | | 362 | | Logger.LogDebug( |
| | | 363 | | "Azure Service Bus background worker {WorkerIndex} handling message {MessageId} for {Queue}. Pending |
| | | 364 | | workerIndex, |
| | | 365 | | delivery.MessageId, |
| | | 366 | | _queueName, |
| | | 367 | | PendingCount, |
| | | 368 | | RunningCount); |
| | | 369 | | await ExecuteHandlerAsync( |
| | | 370 | | delivery, |
| | | 371 | | _drainCancellation.Token, |
| | | 372 | | logFailures: false).ConfigureAwait(false); |
| | | 373 | | } |
| | | 374 | | catch (Exception ex) |
| | | 375 | | { |
| | | 376 | | Logger.LogError( |
| | | 377 | | ex, |
| | | 378 | | "Azure Service Bus background handler failed for already-completed message {MessageId} on {Queue}.", |
| | | 379 | | delivery.MessageId, |
| | | 380 | | _queueName); |
| | | 381 | | await NotifyBackgroundFailureAsync( |
| | | 382 | | delivery, |
| | | 383 | | ex, |
| | | 384 | | _queueName, |
| | | 385 | | _role).ConfigureAwait(false); |
| | | 386 | | } |
| | | 387 | | finally |
| | | 388 | | { |
| | | 389 | | Interlocked.Decrement(ref _runningCount); |
| | | 390 | | } |
| | | 391 | | } |
| | | 392 | | } |
| | | 393 | | } |