| | | 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, IDelayedWorkerTransport, IAsyncDisposable |
| | | 15 | | { |
| | | 16 | | private readonly AzureServiceBusAsyncResponseOptions _options; |
| | | 17 | | private readonly IAzureServiceBusClient _client; |
| | | 18 | | private readonly bool _disposeClient; |
| | 232 | 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) |
| | 4 | 26 | | : this( |
| | 4 | 27 | | options, |
| | 4 | 28 | | new AzureServiceBusClientAdapter(new ServiceBusClient( |
| | 4 | 29 | | AzureServiceBusOptionsValidator.Required(options.Value.ConnectionString, nameof(options.Value.Connection |
| | 4 | 30 | | ownsClient: true), |
| | 4 | 31 | | disposeClient: true) |
| | | 32 | | { |
| | 2 | 33 | | } |
| | | 34 | | |
| | | 35 | | internal AzureServiceBusWorkerTransport( |
| | | 36 | | IOptions<AzureServiceBusAsyncResponseOptions> options, |
| | | 37 | | IAzureServiceBusClient client) |
| | 230 | 38 | | : this(options, client, disposeClient: false) |
| | | 39 | | { |
| | 218 | 40 | | } |
| | | 41 | | |
| | 232 | 42 | | private AzureServiceBusWorkerTransport( |
| | 232 | 43 | | IOptions<AzureServiceBusAsyncResponseOptions> options, |
| | 232 | 44 | | IAzureServiceBusClient client, |
| | 232 | 45 | | bool disposeClient) |
| | | 46 | | { |
| | 232 | 47 | | _options = options.Value; |
| | 232 | 48 | | AzureServiceBusOptionsValidator.ValidateCommon(_options); |
| | 220 | 49 | | _client = client; |
| | 220 | 50 | | _disposeClient = disposeClient; |
| | 220 | 51 | | } |
| | | 52 | | |
| | | 53 | | private async Task<IAzureServiceBusSender> GetSenderAsync(CancellationToken cancellationToken) |
| | | 54 | | { |
| | 429 | 55 | | var sender = Volatile.Read(ref _sender); |
| | 429 | 56 | | if (sender is not null) |
| | 216 | 57 | | return sender; |
| | | 58 | | |
| | 213 | 59 | | await _senderGate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | | 60 | | try |
| | | 61 | | { |
| | 213 | 62 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | 211 | 63 | | _sender ??= _client.CreateSender(_options.WorkerQueue); |
| | 211 | 64 | | return _sender; |
| | | 65 | | } |
| | | 66 | | finally |
| | | 67 | | { |
| | 213 | 68 | | _senderGate.Release(); |
| | | 69 | | } |
| | 427 | 70 | | } |
| | | 71 | | |
| | | 72 | | /// <summary>Publishes the supplied worker job.</summary> |
| | | 73 | | public Task PublishAsync(WorkerJobEnvelope job, CancellationToken cancellationToken = default) |
| | 430 | 74 | | => PublishCoreAsync(job, delay: null, cancellationToken); |
| | | 75 | | |
| | | 76 | | /// <inheritdoc/> |
| | | 77 | | /// <remarks>Service Bus scheduled messages accept any future enqueue time; no per-hop chunking is needed.</remarks> |
| | 5 | 78 | | public TimeSpan MaxPublishDelay => AsyncResponseChannelOptions.MaxPersistenceTtl; |
| | | 79 | | |
| | | 80 | | /// <inheritdoc/> |
| | | 81 | | public Task PublishAsync(WorkerJobEnvelope job, TimeSpan delay, CancellationToken cancellationToken = default) |
| | | 82 | | { |
| | 1 | 83 | | ArgumentOutOfRangeException.ThrowIfGreaterThan(delay, MaxPublishDelay); |
| | 1 | 84 | | return PublishCoreAsync(job, delay > TimeSpan.Zero ? delay : null, cancellationToken); |
| | | 85 | | } |
| | | 86 | | |
| | | 87 | | private async Task PublishCoreAsync(WorkerJobEnvelope job, TimeSpan? delay, CancellationToken cancellationToken) |
| | | 88 | | { |
| | 431 | 89 | | ArgumentNullException.ThrowIfNull(job); |
| | | 90 | | |
| | 429 | 91 | | using var activity = AsyncResponseDiagnostics.StartActivity( |
| | 429 | 92 | | "asyncresponse.worker.publish", |
| | 429 | 93 | | ActivityKind.Producer, |
| | 429 | 94 | | job.CorrelationId); |
| | 429 | 95 | | activity?.SetTag("asyncresponse.transport", "azure_service_bus"); |
| | 429 | 96 | | activity?.SetTag("messaging.system", "azure_service_bus"); |
| | 429 | 97 | | activity?.SetTag("messaging.destination.name", _options.WorkerQueue); |
| | 429 | 98 | | AsyncResponseDiagnostics.SetReplyTarget(activity, job.ReplyTarget); |
| | 429 | 99 | | AsyncResponseDiagnostics.SetWorker(activity, job.Call); |
| | | 100 | | |
| | | 101 | | try |
| | | 102 | | { |
| | | 103 | | // Every message carries a fresh MessageId: MessageId is the duplicate-detection key, so |
| | | 104 | | // reusing the correlation id would silently drop the second job of a flow published on a |
| | | 105 | | // dedup-enabled queue inside its detection window (distinct jobs of one flow share the |
| | | 106 | | // correlation id). The correlation id still travels in the Service Bus CorrelationId |
| | | 107 | | // system property and the configured application property. |
| | 429 | 108 | | var messageId = Guid.NewGuid().ToString("N"); |
| | 429 | 109 | | var properties = new Dictionary<string, object?>(StringComparer.Ordinal); |
| | 429 | 110 | | if (!string.IsNullOrWhiteSpace(job.CorrelationId)) |
| | 115 | 111 | | properties[_options.CorrelationIdProperty] = job.CorrelationId; |
| | 429 | 112 | | var message = new AzureServiceBusOutboundMessage( |
| | 429 | 113 | | AsyncResponseJson.Serialize(job), |
| | 429 | 114 | | messageId, |
| | 429 | 115 | | string.IsNullOrWhiteSpace(job.CorrelationId) ? null : job.CorrelationId, |
| | 429 | 116 | | properties, |
| | 429 | 117 | | delay is { } pending ? DateTimeOffset.UtcNow.Add(pending) : null); |
| | 429 | 118 | | if (delay is { } delayTag) |
| | 1 | 119 | | activity?.SetTag("asyncresponse.worker.delay_seconds", delayTag.TotalSeconds); |
| | | 120 | | |
| | 429 | 121 | | var sender = await GetSenderAsync(cancellationToken).ConfigureAwait(false); |
| | 427 | 122 | | await SendWithRetryAsync(sender, message, cancellationToken).ConfigureAwait(false); |
| | 421 | 123 | | activity?.SetTag("messaging.message.id", messageId); |
| | 421 | 124 | | } |
| | 8 | 125 | | catch (Exception ex) |
| | | 126 | | { |
| | 8 | 127 | | AsyncResponseDiagnostics.SetError(activity, ex); |
| | 8 | 128 | | throw; |
| | | 129 | | } |
| | 421 | 130 | | } |
| | | 131 | | |
| | | 132 | | private async Task SendWithRetryAsync( |
| | | 133 | | IAzureServiceBusSender sender, |
| | | 134 | | AzureServiceBusOutboundMessage message, |
| | | 135 | | CancellationToken cancellationToken) |
| | | 136 | | { |
| | 433 | 137 | | for (var attempt = 1; ; attempt++) |
| | | 138 | | { |
| | | 139 | | try |
| | | 140 | | { |
| | 433 | 141 | | await sender.SendMessageAsync(message, cancellationToken).ConfigureAwait(false); |
| | 421 | 142 | | return; |
| | | 143 | | } |
| | 12 | 144 | | catch (Exception ex) when (IsTransient(ex) && attempt < _options.PublishMaxAttempts && !cancellationToken.Is |
| | | 145 | | { |
| | 6 | 146 | | var delay = AsyncResponseRetry.Backoff(attempt, _options.PublishRetryBaseDelay, _options.PublishRetryMax |
| | 6 | 147 | | await Task.Delay(delay, cancellationToken).ConfigureAwait(false); |
| | | 148 | | } |
| | | 149 | | } |
| | 421 | 150 | | } |
| | | 151 | | |
| | | 152 | | /// <summary>Runs the IsTransient operation.</summary> |
| | | 153 | | internal static bool IsTransient(Exception exception) |
| | 12 | 154 | | => exception is ServiceBusException { IsTransient: true }; |
| | | 155 | | |
| | | 156 | | /// <summary>Releases resources held by this instance.</summary> |
| | | 157 | | public async ValueTask DisposeAsync() |
| | | 158 | | { |
| | 398 | 159 | | if (Interlocked.Exchange(ref _disposeGate, 1) != 0) |
| | 196 | 160 | | return; |
| | | 161 | | |
| | 202 | 162 | | await _senderGate.WaitAsync().ConfigureAwait(false); |
| | | 163 | | try |
| | | 164 | | { |
| | 202 | 165 | | _disposed = true; |
| | 202 | 166 | | if (_sender is not null) |
| | | 167 | | { |
| | 197 | 168 | | using var cts = new CancellationTokenSource(_options.ShutdownTimeout); |
| | | 169 | | try |
| | | 170 | | { |
| | 197 | 171 | | await _sender.CloseAsync(cts.Token).ConfigureAwait(false); |
| | 195 | 172 | | } |
| | 2 | 173 | | catch |
| | | 174 | | { |
| | | 175 | | // Best effort: the sender link may already be closed by broker-side shutdown. |
| | 2 | 176 | | } |
| | | 177 | | |
| | 197 | 178 | | await _sender.DisposeAsync().ConfigureAwait(false); |
| | 197 | 179 | | } |
| | | 180 | | |
| | 202 | 181 | | if (_disposeClient) |
| | 2 | 182 | | await _client.DisposeAsync().ConfigureAwait(false); |
| | 202 | 183 | | } |
| | | 184 | | finally |
| | | 185 | | { |
| | | 186 | | // Release, never Dispose: SemaphoreSlim.Dispose does not complete pending WaitAsync |
| | | 187 | | // waiters, so disposing here would strand publishers parked on the gate forever (and |
| | | 188 | | // the first woken waiter's finally would throw trying to Release a disposed |
| | | 189 | | // semaphore, never handing the permit on). Released, each parked waiter wakes in |
| | | 190 | | // turn and observes _disposed; the gate holds no unmanaged resources, so leaving it |
| | | 191 | | // undisposed leaks nothing. |
| | 202 | 192 | | _senderGate.Release(); |
| | | 193 | | } |
| | 398 | 194 | | } |
| | | 195 | | } |