|
| 1 | +using Azure; |
| 2 | +using Azure.Messaging.ServiceBus.Administration; |
| 3 | + |
| 4 | +using Microsoft.Extensions.DependencyInjection; |
| 5 | +using Microsoft.Extensions.Hosting; |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | + |
| 8 | +namespace Arbiter.Messaging.ServiceBus; |
| 9 | + |
| 10 | +/// <summary> |
| 11 | +/// Initializes configured Azure Service Bus queues, topics, and subscriptions when the host starts. |
| 12 | +/// </summary> |
| 13 | +public sealed class ServiceBusInitializer : IHostedService |
| 14 | +{ |
| 15 | + private readonly ILogger<ServiceBusInitializer> _logger; |
| 16 | + private readonly IServiceProvider _serviceProvider; |
| 17 | + |
| 18 | + /// <summary> |
| 19 | + /// Initializes a new instance of the <see cref="ServiceBusInitializer" /> class. |
| 20 | + /// </summary> |
| 21 | + /// <param name="logger">The logger used to write initialization messages.</param> |
| 22 | + /// <param name="serviceProvider">The service provider used to resolve configured options and dependencies.</param> |
| 23 | + public ServiceBusInitializer(ILogger<ServiceBusInitializer> logger, IServiceProvider serviceProvider) |
| 24 | + { |
| 25 | + ArgumentNullException.ThrowIfNull(logger); |
| 26 | + ArgumentNullException.ThrowIfNull(serviceProvider); |
| 27 | + |
| 28 | + _logger = logger; |
| 29 | + _serviceProvider = serviceProvider; |
| 30 | + } |
| 31 | + |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// Starts Service Bus resource initialization. |
| 35 | + /// </summary> |
| 36 | + /// <param name="cancellationToken">A token used to cancel initialization.</param> |
| 37 | + /// <returns>A task that represents the asynchronous start operation.</returns> |
| 38 | + public async Task StartAsync(CancellationToken cancellationToken) |
| 39 | + { |
| 40 | + var options = _serviceProvider.GetServices<ServiceBusOptions>(); |
| 41 | + if (options?.Any() != true) |
| 42 | + { |
| 43 | + _logger.LogDebug("No Azure Service Bus resources configured for initialization."); |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + foreach (var option in options) |
| 48 | + { |
| 49 | + try |
| 50 | + { |
| 51 | + await Initialize(option, cancellationToken).ConfigureAwait(false); |
| 52 | + } |
| 53 | + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| 54 | + { |
| 55 | + throw; |
| 56 | + } |
| 57 | + catch (Exception ex) |
| 58 | + { |
| 59 | + _logger.LogError(ex, "Error initializing Azure Service Bus resources for '{NameOrConnectionString}': {ErrorMessage}", option.NameOrConnectionString, ex.Message); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + /// <summary> |
| 65 | + /// Stops the hosted service. |
| 66 | + /// </summary> |
| 67 | + /// <param name="cancellationToken">A token used to cancel the stop operation.</param> |
| 68 | + /// <returns>A completed task.</returns> |
| 69 | + public Task StopAsync(CancellationToken cancellationToken) |
| 70 | + { |
| 71 | + return Task.CompletedTask; |
| 72 | + } |
| 73 | + |
| 74 | + |
| 75 | + private async Task Initialize( |
| 76 | + ServiceBusOptions option, |
| 77 | + CancellationToken cancellationToken) |
| 78 | + { |
| 79 | + var connectionString = _serviceProvider.ResolveConnectionString(option.NameOrConnectionString); |
| 80 | + var adminClient = new ServiceBusAdministrationClient(connectionString); |
| 81 | + |
| 82 | + foreach (var queue in option.Queues) |
| 83 | + await InitializeQueue(adminClient, option, queue, cancellationToken).ConfigureAwait(false); |
| 84 | + |
| 85 | + foreach (var topic in option.Topics) |
| 86 | + await InitializeTopic(adminClient, option, topic, cancellationToken).ConfigureAwait(false); |
| 87 | + } |
| 88 | + |
| 89 | + private async Task InitializeQueue( |
| 90 | + ServiceBusAdministrationClient adminClient, |
| 91 | + ServiceBusOptions option, |
| 92 | + string queueName, |
| 93 | + CancellationToken cancellationToken) |
| 94 | + { |
| 95 | + var queue = option.FormatName(queueName); |
| 96 | + |
| 97 | + var queueExists = await adminClient.QueueExistsAsync(queue, cancellationToken).ConfigureAwait(false); |
| 98 | + if (queueExists.Value) |
| 99 | + return; |
| 100 | + |
| 101 | + var options = new CreateQueueOptions(queue) |
| 102 | + { |
| 103 | + DefaultMessageTimeToLive = option.DefaultMessageTimeToLive, |
| 104 | + MaxDeliveryCount = option.MaxDeliveryCount, |
| 105 | + LockDuration = option.LockDuration, |
| 106 | + DeadLetteringOnMessageExpiration = option.DeadLetteringOnMessageExpiration, |
| 107 | + EnableBatchedOperations = option.EnableBatchedOperations, |
| 108 | + }; |
| 109 | + |
| 110 | + _logger.LogInformation("Creating Queue '{QueueName}'", queue); |
| 111 | + |
| 112 | + try |
| 113 | + { |
| 114 | + await adminClient.CreateQueueAsync(options, cancellationToken: cancellationToken).ConfigureAwait(false); |
| 115 | + } |
| 116 | + catch (RequestFailedException ex) when (ex.Status == 409) |
| 117 | + { |
| 118 | + _logger.LogDebug(ex, "Queue '{QueueName}' already exists", queue); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + private async Task InitializeTopic( |
| 123 | + ServiceBusAdministrationClient adminClient, |
| 124 | + ServiceBusOptions option, |
| 125 | + string topicName, |
| 126 | + CancellationToken cancellationToken) |
| 127 | + { |
| 128 | + var topic = option.FormatName(topicName); |
| 129 | + |
| 130 | + var topicExists = await adminClient.TopicExistsAsync(topic, cancellationToken).ConfigureAwait(false); |
| 131 | + if (!topicExists.Value) |
| 132 | + { |
| 133 | + var topicOptions = new CreateTopicOptions(topic) |
| 134 | + { |
| 135 | + DefaultMessageTimeToLive = option.DefaultMessageTimeToLive, |
| 136 | + EnableBatchedOperations = option.EnableBatchedOperations, |
| 137 | + }; |
| 138 | + |
| 139 | + _logger.LogInformation("Creating Topic '{TopicName}'", topic); |
| 140 | + |
| 141 | + try |
| 142 | + { |
| 143 | + await adminClient.CreateTopicAsync(topicOptions, cancellationToken).ConfigureAwait(false); |
| 144 | + } |
| 145 | + catch (RequestFailedException ex) when (ex.Status == 409) |
| 146 | + { |
| 147 | + _logger.LogDebug(ex, "Topic '{TopicName}' already exists", topic); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + if (!option.Subscriptions.TryGetValue(topicName, out var subscriptions)) |
| 152 | + return; |
| 153 | + |
| 154 | + foreach (var subscriptionName in subscriptions) |
| 155 | + { |
| 156 | + var subscriptionExists = await adminClient.SubscriptionExistsAsync(topic, subscriptionName, cancellationToken).ConfigureAwait(false); |
| 157 | + if (subscriptionExists.Value) |
| 158 | + continue; |
| 159 | + |
| 160 | + var subscriptionOptions = new CreateSubscriptionOptions(topic, subscriptionName) |
| 161 | + { |
| 162 | + DefaultMessageTimeToLive = option.DefaultMessageTimeToLive, |
| 163 | + MaxDeliveryCount = option.MaxDeliveryCount, |
| 164 | + LockDuration = option.LockDuration, |
| 165 | + DeadLetteringOnMessageExpiration = option.DeadLetteringOnMessageExpiration, |
| 166 | + EnableBatchedOperations = option.EnableBatchedOperations, |
| 167 | + }; |
| 168 | + |
| 169 | + _logger.LogInformation("Creating Subscription '{SubscriptionName}' for Topic '{TopicName}'", subscriptionName, topic); |
| 170 | + |
| 171 | + try |
| 172 | + { |
| 173 | + await adminClient.CreateSubscriptionAsync(subscriptionOptions, cancellationToken).ConfigureAwait(false); |
| 174 | + } |
| 175 | + catch (RequestFailedException ex) when (ex.Status == 409) |
| 176 | + { |
| 177 | + _logger.LogDebug(ex, "Subscription '{SubscriptionName}' for Topic '{TopicName}' already exists", subscriptionName, topic); |
| 178 | + } |
| 179 | + } |
| 180 | + } |
| 181 | +} |
0 commit comments