| | | 1 | | using Amazon.SQS; |
| | | 2 | | using Amazon.SQS.Model; |
| | | 3 | | using Microsoft.Extensions.Hosting; |
| | | 4 | | using Microsoft.Extensions.Logging; |
| | | 5 | | using Microsoft.Extensions.Options; |
| | | 6 | | using System.Text.Json; |
| | | 7 | | |
| | | 8 | | namespace AsyncResponse.Transports.SQS; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Provisions the worker and response queues (each with a dead-letter queue wired through a native |
| | | 12 | | /// redrive policy) when <see cref="SqsAsyncResponseOptions.CreateQueues"/> is enabled. Registered |
| | | 13 | | /// before the subscribers so provisioning completes before consumption starts; queues configured as |
| | | 14 | | /// URLs are assumed to exist and are skipped. |
| | | 15 | | /// </summary> |
| | 3 | 16 | | internal sealed class SqsQueueProvisioningService( |
| | 3 | 17 | | IOptions<SqsAsyncResponseOptions> options, |
| | 3 | 18 | | ISqsClient client, |
| | 3 | 19 | | ILogger<SqsQueueProvisioningService> logger) : IHostedService |
| | | 20 | | { |
| | | 21 | | private const int MaxAttempts = 40; |
| | | 22 | | |
| | | 23 | | /// <summary>Creates the configured queues and their dead-letter pairs.</summary> |
| | | 24 | | public async Task StartAsync(CancellationToken cancellationToken) |
| | | 25 | | { |
| | 3 | 26 | | var o = options.Value; |
| | 3 | 27 | | if (!o.CreateQueues) |
| | 2 | 28 | | return; |
| | | 29 | | |
| | 3 | 30 | | SqsOptionsValidator.ValidateCommon(o); |
| | | 31 | | |
| | 3 | 32 | | foreach (var queue in new[] { o.WorkerQueue, o.ResponseQueue }) |
| | | 33 | | { |
| | 3 | 34 | | if (SqsQueueAddress.IsUrl(queue)) |
| | | 35 | | { |
| | 2 | 36 | | logger.LogInformation("SQS queue {Queue} is configured as a URL; skipping provisioning.", queue); |
| | 2 | 37 | | continue; |
| | | 38 | | } |
| | | 39 | | |
| | 3 | 40 | | await EnsureQueueWithDeadLetterAsync(o, queue, cancellationToken).ConfigureAwait(false); |
| | | 41 | | } |
| | 3 | 42 | | } |
| | | 43 | | |
| | | 44 | | /// <summary>No-op.</summary> |
| | 3 | 45 | | public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; |
| | | 46 | | |
| | | 47 | | internal async Task EnsureQueueWithDeadLetterAsync( |
| | | 48 | | SqsAsyncResponseOptions o, |
| | | 49 | | string queueName, |
| | | 50 | | CancellationToken cancellationToken) |
| | | 51 | | { |
| | 3 | 52 | | var fifo = SqsQueueAddress.IsFifo(queueName); |
| | | 53 | | // A FIFO queue's dead-letter queue must itself be FIFO, and FIFO names must end in ".fifo". |
| | 3 | 54 | | var deadLetterQueueName = fifo |
| | 3 | 55 | | ? $"{queueName[..^".fifo".Length]}{o.DeadLetterQueueSuffix}.fifo" |
| | 3 | 56 | | : $"{queueName}{o.DeadLetterQueueSuffix}"; |
| | | 57 | | |
| | 3 | 58 | | var fifoAttributes = fifo |
| | 3 | 59 | | ? new Dictionary<string, string>(StringComparer.Ordinal) { [QueueAttributeName.FifoQueue] = "true" } |
| | 3 | 60 | | : new Dictionary<string, string>(StringComparer.Ordinal); |
| | | 61 | | |
| | 3 | 62 | | var deadLetterQueueUrl = await CreateOrUpdateQueueAsync(deadLetterQueueName, fifoAttributes, cancellationToken) |
| | 3 | 63 | | .ConfigureAwait(false); |
| | 3 | 64 | | var deadLetterQueueArn = await RetryAsync( |
| | 3 | 65 | | () => client.GetQueueArnAsync(deadLetterQueueUrl, cancellationToken), |
| | 3 | 66 | | cancellationToken).ConfigureAwait(false); |
| | | 67 | | |
| | 3 | 68 | | var attributes = new Dictionary<string, string>(fifoAttributes, StringComparer.Ordinal) |
| | 3 | 69 | | { |
| | 3 | 70 | | [QueueAttributeName.RedrivePolicy] = AsyncResponseJson.Serialize(new Dictionary<string, string> |
| | 3 | 71 | | { |
| | 3 | 72 | | ["deadLetterTargetArn"] = deadLetterQueueArn, |
| | 3 | 73 | | ["maxReceiveCount"] = o.MaxReceiveCount.ToString() |
| | 3 | 74 | | }) |
| | 3 | 75 | | }; |
| | | 76 | | |
| | 3 | 77 | | await CreateOrUpdateQueueAsync(queueName, attributes, cancellationToken).ConfigureAwait(false); |
| | | 78 | | |
| | 3 | 79 | | logger.LogInformation( |
| | 3 | 80 | | "SQS queue {Queue} provisioned with dead-letter queue {DeadLetterQueue} (maxReceiveCount={MaxReceiveCount}). |
| | 3 | 81 | | queueName, |
| | 3 | 82 | | deadLetterQueueName, |
| | 3 | 83 | | o.MaxReceiveCount); |
| | 3 | 84 | | } |
| | | 85 | | |
| | | 86 | | private async Task<string> CreateOrUpdateQueueAsync( |
| | | 87 | | string queueName, |
| | | 88 | | IReadOnlyDictionary<string, string> attributes, |
| | | 89 | | CancellationToken cancellationToken) |
| | | 90 | | { |
| | 3 | 91 | | return await RetryAsync(CreateAsync, cancellationToken).ConfigureAwait(false); |
| | | 92 | | |
| | | 93 | | async Task<string> CreateAsync() |
| | | 94 | | { |
| | | 95 | | try |
| | | 96 | | { |
| | 3 | 97 | | return await client.CreateQueueAsync(queueName, attributes, cancellationToken).ConfigureAwait(false); |
| | | 98 | | } |
| | | 99 | | catch (QueueNameExistsException) |
| | | 100 | | { |
| | | 101 | | // The queue exists with different attributes (for example a redrive policy set by an |
| | | 102 | | // earlier run against a different DLQ ARN): converge by re-applying the attributes. |
| | 2 | 103 | | var queueUrl = await client.GetQueueUrlAsync(queueName, cancellationToken).ConfigureAwait(false); |
| | 2 | 104 | | if (attributes.Count > 0) |
| | 2 | 105 | | await client.SetQueueAttributesAsync(queueUrl, attributes, cancellationToken).ConfigureAwait(false); |
| | 2 | 106 | | return queueUrl; |
| | | 107 | | } |
| | 0 | 108 | | } |
| | 3 | 109 | | } |
| | | 110 | | |
| | | 111 | | private async Task<T> RetryAsync<T>(Func<Task<T>> operation, CancellationToken cancellationToken) |
| | | 112 | | { |
| | 3 | 113 | | var o = options.Value; |
| | 3 | 114 | | for (var attempt = 1; ; attempt++) |
| | | 115 | | { |
| | | 116 | | try |
| | | 117 | | { |
| | 3 | 118 | | return await operation().ConfigureAwait(false); |
| | | 119 | | } |
| | 2 | 120 | | catch (Exception ex) when (attempt < MaxAttempts && !cancellationToken.IsCancellationRequested) |
| | | 121 | | { |
| | | 122 | | // Startup ordering against a fresh endpoint (LocalStack still booting, transient |
| | | 123 | | // networking) resolves within a few retries; anything persistent still surfaces. |
| | 2 | 124 | | var delay = AsyncResponseRetry.Backoff(attempt, o.SubscriberRetryBaseDelay, o.SubscriberRetryMaxDelay); |
| | 2 | 125 | | logger.LogWarning(ex, "SQS queue provisioning attempt {Attempt} failed; retrying in {Delay}.", attempt, |
| | 2 | 126 | | await Task.Delay(delay, cancellationToken).ConfigureAwait(false); |
| | | 127 | | } |
| | | 128 | | } |
| | 3 | 129 | | } |
| | | 130 | | } |