| | | 1 | | using Microsoft.Extensions.Options; |
| | | 2 | | using Azure.Messaging.ServiceBus; |
| | | 3 | | using System.Diagnostics; |
| | | 4 | | using System.Text.Json; |
| | | 5 | | |
| | | 6 | | namespace AsyncResponse.Transports.AzureServiceBus; |
| | | 7 | | |
| | | 8 | | /// <summary>Publishes <see cref="WorkerJobEnvelope"/> messages to an Azure Service Bus queue.</summary> |
| | | 9 | | /// <remarks> |
| | | 10 | | /// A Service Bus sender is created lazily and reused for the lifetime of the transport. Send |
| | | 11 | | /// operations are explicitly awaited so the method completes only after Service Bus accepts the |
| | | 12 | | /// transfer or the Azure SDK reports a failure. |
| | | 13 | | /// </remarks> |
| | | 14 | | public sealed class AzureServiceBusWorkerTransport : IWorkerTransport, IAsyncDisposable |
| | | 15 | | { |
| | | 16 | | private readonly AzureServiceBusAsyncResponseOptions _options; |
| | | 17 | | private readonly IAzureServiceBusClient _client; |
| | | 18 | | private readonly bool _disposeClient; |
| | 3 | 19 | | private readonly SemaphoreSlim _senderGate = new(1, 1); |
| | | 20 | | private IAzureServiceBusSender? _sender; |
| | | 21 | | private int _disposeGate; |
| | | 22 | | private bool _disposed; |
| | | 23 | | |
| | | 24 | | /// <summary>Creates a worker transport backed by the configured connection string.</summary> |
| | | 25 | | public AzureServiceBusWorkerTransport(IOptions<AzureServiceBusAsyncResponseOptions> options) |
| | 2 | 26 | | : this( |
| | 2 | 27 | | options, |
| | 2 | 28 | | new AzureServiceBusClientAdapter(new ServiceBusClient( |
| | 2 | 29 | | AzureServiceBusOptionsValidator.Required(options.Value.ConnectionString, nameof(options.Value.Connection |
| | 2 | 30 | | ownsClient: true), |
| | 2 | 31 | | disposeClient: true) |
| | | 32 | | { |
| | 3 | 33 | | } |
| | | 34 | | |
| | | 35 | | internal AzureServiceBusWorkerTransport( |
| | | 36 | | IOptions<AzureServiceBusAsyncResponseOptions> options, |
| | | 37 | | IAzureServiceBusClient client) |
| | 3 | 38 | | : this(options, client, disposeClient: false) |
| | | 39 | | { |
| | 3 | 40 | | } |
| | | 41 | | |
| | 3 | 42 | | private AzureServiceBusWorkerTransport( |
| | 3 | 43 | | IOptions<AzureServiceBusAsyncResponseOptions> options, |
| | 3 | 44 | | IAzureServiceBusClient client, |
| | 3 | 45 | | bool disposeClient) |
| | | 46 | | { |
| | 3 | 47 | | _options = options.Value; |
| | 3 | 48 | | AzureServiceBusOptionsValidator.ValidateCommon(_options); |
| | 3 | 49 | | _client = client; |
| | 3 | 50 | | _disposeClient = disposeClient; |
| | 3 | 51 | | } |
| | | 52 | | |
| | | 53 | | private async Task<IAzureServiceBusSender> GetSenderAsync(CancellationToken cancellationToken) |
| | | 54 | | { |
| | 3 | 55 | | var sender = Volatile.Read(ref _sender); |
| | 3 | 56 | | if (sender is not null) |
| | 3 | 57 | | return sender; |
| | | 58 | | |
| | 3 | 59 | | await _senderGate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | | 60 | | try |
| | | 61 | | { |
| | 3 | 62 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | 3 | 63 | | _sender ??= _client.CreateSender(_options.WorkerQueue); |
| | 3 | 64 | | return _sender; |
| | | 65 | | } |
| | | 66 | | finally |
| | | 67 | | { |
| | 3 | 68 | | _senderGate.Release(); |
| | | 69 | | } |
| | 3 | 70 | | } |
| | | 71 | | |
| | | 72 | | /// <summary>Publishes the supplied worker job.</summary> |
| | | 73 | | public async Task PublishAsync(WorkerJobEnvelope job, CancellationToken cancellationToken = default) |
| | | 74 | | { |
| | 3 | 75 | | ArgumentNullException.ThrowIfNull(job); |
| | | 76 | | |
| | 3 | 77 | | using var activity = AsyncResponseDiagnostics.StartActivity( |
| | 3 | 78 | | "asyncresponse.worker.publish", |
| | 3 | 79 | | ActivityKind.Producer, |
| | 3 | 80 | | job.CorrelationId); |
| | 3 | 81 | | activity?.SetTag("asyncresponse.transport", "azure_service_bus"); |
| | 3 | 82 | | activity?.SetTag("messaging.system", "azure_service_bus"); |
| | 3 | 83 | | activity?.SetTag("messaging.destination.name", _options.WorkerQueue); |
| | 3 | 84 | | AsyncResponseDiagnostics.SetReplyTarget(activity, job.ReplyTarget); |
| | 3 | 85 | | AsyncResponseDiagnostics.SetWorker(activity, job.Call); |
| | | 86 | | |
| | | 87 | | try |
| | | 88 | | { |
| | | 89 | | // Every message carries a fresh MessageId: MessageId is the duplicate-detection key, so |
| | | 90 | | // reusing the correlation id would silently drop the second job of a flow published on a |
| | | 91 | | // dedup-enabled queue inside its detection window (distinct jobs of one flow share the |
| | | 92 | | // correlation id). The correlation id still travels in the Service Bus CorrelationId |
| | | 93 | | // system property and the configured application property. |
| | 3 | 94 | | var messageId = Guid.NewGuid().ToString("N"); |
| | 3 | 95 | | var properties = new Dictionary<string, object?>(StringComparer.Ordinal); |
| | 3 | 96 | | if (!string.IsNullOrWhiteSpace(job.CorrelationId)) |
| | 3 | 97 | | properties[_options.CorrelationIdProperty] = job.CorrelationId; |
| | 3 | 98 | | var message = new AzureServiceBusOutboundMessage( |
| | 3 | 99 | | AsyncResponseJson.Serialize(job), |
| | 3 | 100 | | messageId, |
| | 3 | 101 | | string.IsNullOrWhiteSpace(job.CorrelationId) ? null : job.CorrelationId, |
| | 3 | 102 | | properties); |
| | | 103 | | |
| | 3 | 104 | | var sender = await GetSenderAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 105 | | await SendWithRetryAsync(sender, message, cancellationToken).ConfigureAwait(false); |
| | 3 | 106 | | activity?.SetTag("messaging.message.id", messageId); |
| | 3 | 107 | | } |
| | 2 | 108 | | catch (Exception ex) |
| | | 109 | | { |
| | 2 | 110 | | AsyncResponseDiagnostics.SetError(activity, ex); |
| | 3 | 111 | | throw; |
| | | 112 | | } |
| | 3 | 113 | | } |
| | | 114 | | |
| | | 115 | | private async Task SendWithRetryAsync( |
| | | 116 | | IAzureServiceBusSender sender, |
| | | 117 | | AzureServiceBusOutboundMessage message, |
| | | 118 | | CancellationToken cancellationToken) |
| | | 119 | | { |
| | 3 | 120 | | for (var attempt = 1; ; attempt++) |
| | | 121 | | { |
| | | 122 | | try |
| | | 123 | | { |
| | 3 | 124 | | await sender.SendMessageAsync(message, cancellationToken).ConfigureAwait(false); |
| | 3 | 125 | | return; |
| | | 126 | | } |
| | 2 | 127 | | catch (Exception ex) when (IsTransient(ex) && attempt < _options.PublishMaxAttempts && !cancellationToken.Is |
| | | 128 | | { |
| | 2 | 129 | | var delay = RetryDelay(attempt); |
| | 2 | 130 | | await Task.Delay(delay, cancellationToken).ConfigureAwait(false); |
| | | 131 | | } |
| | | 132 | | } |
| | 3 | 133 | | } |
| | | 134 | | |
| | | 135 | | /// <summary>Runs the IsTransient operation.</summary> |
| | | 136 | | internal static bool IsTransient(Exception exception) |
| | 2 | 137 | | => exception is ServiceBusException { IsTransient: true }; |
| | | 138 | | |
| | | 139 | | private TimeSpan RetryDelay(int failedAttempt) |
| | | 140 | | { |
| | 2 | 141 | | var milliseconds = _options.PublishRetryBaseDelay.TotalMilliseconds * Math.Pow(2, failedAttempt - 1); |
| | 3 | 142 | | return TimeSpan.FromMilliseconds(Math.Min(milliseconds, _options.PublishRetryMaxDelay.TotalMilliseconds)); |
| | | 143 | | } |
| | | 144 | | |
| | | 145 | | /// <summary>Releases resources held by this instance.</summary> |
| | | 146 | | public async ValueTask DisposeAsync() |
| | | 147 | | { |
| | 3 | 148 | | if (Interlocked.Exchange(ref _disposeGate, 1) != 0) |
| | 3 | 149 | | return; |
| | | 150 | | |
| | 3 | 151 | | await _senderGate.WaitAsync().ConfigureAwait(false); |
| | | 152 | | try |
| | | 153 | | { |
| | 3 | 154 | | _disposed = true; |
| | 3 | 155 | | if (_sender is not null) |
| | | 156 | | { |
| | 3 | 157 | | using var cts = new CancellationTokenSource(_options.ShutdownTimeout); |
| | | 158 | | try |
| | | 159 | | { |
| | 3 | 160 | | await _sender.CloseAsync(cts.Token).ConfigureAwait(false); |
| | 3 | 161 | | } |
| | 3 | 162 | | catch |
| | | 163 | | { |
| | | 164 | | // Best effort: the sender link may already be closed by broker-side shutdown. |
| | 3 | 165 | | } |
| | | 166 | | |
| | 3 | 167 | | await _sender.DisposeAsync().ConfigureAwait(false); |
| | 3 | 168 | | } |
| | | 169 | | |
| | 3 | 170 | | if (_disposeClient) |
| | 2 | 171 | | await _client.DisposeAsync().ConfigureAwait(false); |
| | 3 | 172 | | } |
| | | 173 | | finally |
| | | 174 | | { |
| | 3 | 175 | | _senderGate.Release(); |
| | 3 | 176 | | _senderGate.Dispose(); |
| | | 177 | | } |
| | 3 | 178 | | } |
| | | 179 | | } |