-
Notifications
You must be signed in to change notification settings - Fork 532
/
Copy pathAzureServiceBusExtensions.cs
487 lines (410 loc) · 24.2 KB
/
AzureServiceBusExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text.Json;
using System.Text.Json.Nodes;
using Aspire.Hosting.ApplicationModel;
using Aspire.Hosting.Azure;
using Aspire.Hosting.Azure.ServiceBus;
using Aspire.Hosting.Utils;
using Azure.Messaging.ServiceBus;
using Azure.Provisioning;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using AzureProvisioning = Azure.Provisioning.ServiceBus;
namespace Aspire.Hosting;
/// <summary>
/// Provides extension methods for adding the Azure Service Bus resources to the application model.
/// </summary>
public static class AzureServiceBusExtensions
{
/// <summary>
/// Adds an Azure Service Bus Namespace resource to the application model. This resource can be used to create queue, topic, and subscription resources.
/// </summary>
/// <param name="builder">The builder for the distributed application.</param>
/// <param name="name">The name of the resource.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
public static IResourceBuilder<AzureServiceBusResource> AddAzureServiceBus(this IDistributedApplicationBuilder builder, [ResourceName] string name)
{
builder.AddAzureProvisioning();
var configureInfrastructure = static (AzureResourceInfrastructure infrastructure) =>
{
var skuParameter = new ProvisioningParameter("sku", typeof(string))
{
Value = "Standard"
};
infrastructure.Add(skuParameter);
var serviceBusNamespace = new AzureProvisioning.ServiceBusNamespace(infrastructure.AspireResource.GetBicepIdentifier())
{
Sku = new AzureProvisioning.ServiceBusSku()
{
Name = skuParameter
},
DisableLocalAuth = true,
Tags = { { "aspire-resource-name", infrastructure.AspireResource.Name } }
};
infrastructure.Add(serviceBusNamespace);
var principalTypeParameter = new ProvisioningParameter(AzureBicepResource.KnownParameters.PrincipalType, typeof(string));
infrastructure.Add(principalTypeParameter);
var principalIdParameter = new ProvisioningParameter(AzureBicepResource.KnownParameters.PrincipalId, typeof(string));
infrastructure.Add(principalIdParameter);
infrastructure.Add(serviceBusNamespace.CreateRoleAssignment(AzureProvisioning.ServiceBusBuiltInRole.AzureServiceBusDataOwner, principalTypeParameter, principalIdParameter));
infrastructure.Add(new ProvisioningOutput("serviceBusEndpoint", typeof(string)) { Value = serviceBusNamespace.ServiceBusEndpoint });
var azureResource = (AzureServiceBusResource)infrastructure.AspireResource;
foreach (var queue in azureResource.Queues)
{
var cdkQueue = queue.ToProvisioningEntity();
cdkQueue.Parent = serviceBusNamespace;
infrastructure.Add(cdkQueue);
}
foreach (var topic in azureResource.Topics)
{
var cdkTopic = topic.ToProvisioningEntity();
cdkTopic.Parent = serviceBusNamespace;
infrastructure.Add(cdkTopic);
foreach (var subscription in topic.Subscriptions)
{
var cdkSubscription = subscription.ToProvisioningEntity();
cdkSubscription.Parent = cdkTopic;
infrastructure.Add(cdkSubscription);
foreach (var rule in subscription.Rules)
{
var cdkRule = rule.ToProvisioningEntity();
cdkRule.Parent = cdkSubscription;
infrastructure.Add(cdkRule);
}
}
}
};
var resource = new AzureServiceBusResource(name, configureInfrastructure);
return builder.AddResource(resource)
.WithManifestPublishingCallback(resource.WriteToManifest);
}
/// <summary>
/// Adds an Azure Service Bus Queue resource to the application model. This resource requires an <see cref="AzureServiceBusResource"/> to be added to the application model.
/// </summary>
/// <param name="builder">The Azure Service Bus resource builder.</param>
/// <param name="name">The name of the queue.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
[Obsolete($"This method is obsolete and will be removed in a future version. Use {nameof(WithQueue)} instead to add an Azure Service Bus Queue.")]
public static IResourceBuilder<AzureServiceBusResource> AddQueue(this IResourceBuilder<AzureServiceBusResource> builder, [ResourceName] string name)
{
return builder.WithQueue(name);
}
/// <summary>
/// Adds an Azure Service Bus Queue resource to the application model. This resource requires an <see cref="AzureServiceBusResource"/> to be added to the application model.
/// </summary>
/// <param name="builder">The Azure Service Bus resource builder.</param>
/// <param name="name">The name of the queue.</param>
/// <param name="configure">An optional method that can be used for customizing the <see cref="ServiceBusQueue"/>.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
public static IResourceBuilder<AzureServiceBusResource> WithQueue(this IResourceBuilder<AzureServiceBusResource> builder, [ResourceName] string name, Action<ServiceBusQueue>? configure = null)
{
var queue = builder.Resource.Queues.FirstOrDefault(x => x.Name == name);
if (queue == null)
{
queue = new ServiceBusQueue(name);
builder.Resource.Queues.Add(queue);
}
configure?.Invoke(queue);
return builder;
}
/// <summary>
/// Adds an Azure Service Bus Topic resource to the application model. This resource requires an <see cref="AzureServiceBusResource"/> to be added to the application model.
/// </summary>
/// <param name="builder">The Azure Service Bus resource builder.</param>
/// <param name="name">The name of the topic.</param>
[Obsolete($"This method is obsolete and will be removed in a future version. Use {nameof(WithTopic)} instead to add an Azure Service Bus Topic.")]
public static IResourceBuilder<AzureServiceBusResource> AddTopic(this IResourceBuilder<AzureServiceBusResource> builder, [ResourceName] string name)
{
return builder.WithTopic(name);
}
/// <summary>
/// Adds an Azure Service Bus Topic resource to the application model. This resource requires an <see cref="AzureServiceBusResource"/> to be added to the application model.
/// </summary>
/// <param name="builder">The Azure Service Bus resource builder.</param>
/// <param name="name">The name of the topic.</param>
/// <param name="subscriptions">The name of the subscriptions.</param>
[Obsolete($"This method is obsolete and will be removed in a future version. Use {nameof(WithTopic)} instead to add an Azure Service Bus Topic and Subscriptions.")]
public static IResourceBuilder<AzureServiceBusResource> AddTopic(this IResourceBuilder<AzureServiceBusResource> builder, [ResourceName] string name, string[] subscriptions)
{
return builder.WithTopic(name, topic =>
{
foreach (var subscription in subscriptions)
{
if (!topic.Subscriptions.Any(x => x.Name == subscription))
{
topic.Subscriptions.Add(new ServiceBusSubscription(subscription));
}
}
});
}
/// <summary>
/// Adds an Azure Service Bus Topic resource to the application model. This resource requires an <see cref="AzureServiceBusResource"/> to be added to the application model.
/// </summary>
/// <param name="builder">The Azure Service Bus resource builder.</param>
/// <param name="name">The name of the topic.</param>
/// <param name="configure">An optional method that can be used for customizing the <see cref="ServiceBusTopic"/>.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
public static IResourceBuilder<AzureServiceBusResource> WithTopic(this IResourceBuilder<AzureServiceBusResource> builder, [ResourceName] string name, Action<ServiceBusTopic>? configure = null)
{
var topic = builder.Resource.Topics.FirstOrDefault(x => x.Name == name);
if (topic == null)
{
topic = new ServiceBusTopic(name);
builder.Resource.Topics.Add(topic);
}
configure?.Invoke(topic);
return builder;
}
/// <summary>
/// Adds an Azure Service Bus Subscription resource to the application model. This resource requires an <see cref="AzureServiceBusResource"/> to be added to the application model.
/// </summary>
/// <param name="builder">The Azure Service Bus resource builder.</param>
/// <param name="topicName">The name of the topic.</param>
/// <param name="subscriptionName">The name of the subscription.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
[Obsolete($"This method is obsolete and will be removed in a future version. Use {nameof(WithTopic)} instead to add an Azure Service Bus Subscription to a Topic.")]
public static IResourceBuilder<AzureServiceBusResource> AddSubscription(this IResourceBuilder<AzureServiceBusResource> builder, string topicName, string subscriptionName)
{
builder.WithTopic(topicName, topic =>
{
if (!topic.Subscriptions.Any(x => x.Name == subscriptionName))
{
topic.Subscriptions.Add(new ServiceBusSubscription(subscriptionName));
}
});
return builder;
}
/// <summary>
/// Configures an Azure Service Bus resource to be emulated. This resource requires an <see cref="AzureServiceBusResource"/> to be added to the application model.
/// </summary>
/// <remarks>
/// This version of the package defaults to the <inheritdoc cref="ServiceBusEmulatorContainerImageTags.Tag"/> tag of the <inheritdoc cref="ServiceBusEmulatorContainerImageTags.Registry"/>/<inheritdoc cref="ServiceBusEmulatorContainerImageTags.Image"/> container image.
/// </remarks>
/// <param name="builder">The Azure Service Bus resource builder.</param>
/// <param name="configureContainer">Callback that exposes underlying container used for emulation to allow for customization.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
/// <example>
/// The following example creates an Azure Service Bus resource that runs locally is an emulator and referencing that
/// resource in a .NET project.
/// <code lang="csharp">
/// var builder = DistributedApplication.CreateBuilder(args);
///
/// var serviceBus = builder.AddAzureServiceBus("myservicebus")
/// .RunAsEmulator()
/// .AddQueue("queue");
///
/// builder.AddProject<Projects.InventoryService>()
/// .WithReference(serviceBus);
///
/// builder.Build().Run();
/// </code>
/// </example>
public static IResourceBuilder<AzureServiceBusResource> RunAsEmulator(this IResourceBuilder<AzureServiceBusResource> builder, Action<IResourceBuilder<AzureServiceBusEmulatorResource>>? configureContainer = null)
{
if (builder.ApplicationBuilder.ExecutionContext.IsPublishMode)
{
return builder;
}
// Create a default file mount. This could be replaced by a user-provided file mount.
var configHostFile = Path.Combine(Directory.CreateTempSubdirectory("AspireServiceBusEmulator").FullName, "Config.json");
var defaultConfigFileMount = new ContainerMountAnnotation(
configHostFile,
AzureServiceBusEmulatorResource.EmulatorConfigJsonPath,
ContainerMountType.BindMount,
isReadOnly: true);
builder.WithAnnotation(defaultConfigFileMount);
// Add emulator container
var password = PasswordGenerator.Generate(16, true, true, true, true, 0, 0, 0, 0);
builder
.WithEndpoint(name: "emulator", targetPort: 5672)
.WithAnnotation(new ContainerImageAnnotation
{
Registry = ServiceBusEmulatorContainerImageTags.Registry,
Image = ServiceBusEmulatorContainerImageTags.Image,
Tag = ServiceBusEmulatorContainerImageTags.Tag
});
var sqlEdgeResource = builder.ApplicationBuilder
.AddContainer($"{builder.Resource.Name}-sqledge",
image: ServiceBusEmulatorContainerImageTags.AzureSqlEdgeImage,
tag: ServiceBusEmulatorContainerImageTags.AzureSqlEdgeTag)
.WithImageRegistry(ServiceBusEmulatorContainerImageTags.AzureSqlEdgeRegistry)
.WithEndpoint(targetPort: 1433, name: "tcp")
.WithEnvironment("ACCEPT_EULA", "Y")
.WithEnvironment("MSSQL_SA_PASSWORD", password);
builder.WithAnnotation(new EnvironmentCallbackAnnotation((EnvironmentCallbackContext context) =>
{
var sqlEndpoint = sqlEdgeResource.Resource.GetEndpoint("tcp");
context.EnvironmentVariables.Add("ACCEPT_EULA", "Y");
context.EnvironmentVariables.Add("SQL_SERVER", $"{sqlEndpoint.Resource.Name}:{sqlEndpoint.TargetPort}");
context.EnvironmentVariables.Add("MSSQL_SA_PASSWORD", password);
}));
ServiceBusClient? serviceBusClient = null;
string? queueOrTopicName = null;
builder.ApplicationBuilder.Eventing.Subscribe<BeforeResourceStartedEvent>(builder.Resource, async (@event, ct) =>
{
var serviceBusEmulatorResources = builder.ApplicationBuilder.Resources.OfType<AzureServiceBusResource>().Where(x => x is { } serviceBusResource && serviceBusResource.IsEmulator);
if (!serviceBusEmulatorResources.Any())
{
// No-op if there is no Azure Service Bus emulator resource.
return;
}
var connectionString = await builder.Resource.ConnectionStringExpression.GetValueAsync(ct).ConfigureAwait(false);
if (connectionString == null)
{
throw new DistributedApplicationException($"ConnectionStringAvailableEvent was published for the '{builder.Resource.Name}' resource but the connection string was null.");
}
// Retrieve a queue/topic name to configure the health check
var noRetryOptions = new ServiceBusClientOptions { RetryOptions = new ServiceBusRetryOptions { MaxRetries = 0 } };
serviceBusClient = new ServiceBusClient(connectionString, noRetryOptions);
queueOrTopicName =
serviceBusEmulatorResources.SelectMany(x => x.Queues).Select(x => x.Name).FirstOrDefault()
?? serviceBusEmulatorResources.SelectMany(x => x.Topics).Select(x => x.Name).FirstOrDefault();
// Create JSON configuration file
foreach (var emulatorResource in serviceBusEmulatorResources)
{
var configFileMount = emulatorResource.Annotations.OfType<ContainerMountAnnotation>().Single(v => v.Target == AzureServiceBusEmulatorResource.EmulatorConfigJsonPath);
// If there is a custom mount for EmulatorConfigJsonPath we don't need to create the Config.json file.
if (configFileMount != defaultConfigFileMount)
{
continue;
}
var fileStreamOptions = new FileStreamOptions() { Mode = FileMode.Create, Access = FileAccess.Write };
if (!OperatingSystem.IsWindows())
{
fileStreamOptions.UnixCreateMode =
UnixFileMode.UserRead | UnixFileMode.UserWrite
| UnixFileMode.GroupRead | UnixFileMode.GroupWrite
| UnixFileMode.OtherRead | UnixFileMode.OtherWrite;
}
using (var stream = new FileStream(configFileMount.Source!, fileStreamOptions))
{
using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
writer.WriteStartObject(); // {
writer.WriteStartObject("UserConfig"); // "UserConfig": {
writer.WriteStartArray("Namespaces"); // "Namespaces": [
writer.WriteStartObject(); // {
writer.WriteString("Name", emulatorResource.Name);
writer.WriteStartArray("Queues"); // "Queues": [
foreach (var queue in emulatorResource.Queues)
{
writer.WriteStartObject();
queue.WriteJsonObjectProperties(writer);
writer.WriteEndObject();
}
writer.WriteEndArray(); // ] (/Queues)
writer.WriteStartArray("Topics"); // "Topics": [
foreach (var topic in emulatorResource.Topics)
{
writer.WriteStartObject(); // "{ (Topic)"
topic.WriteJsonObjectProperties(writer);
writer.WriteStartArray("Subscriptions"); // "Subscriptions": [
foreach (var subscription in topic.Subscriptions)
{
writer.WriteStartObject(); // "{ (Subscription)"
subscription.WriteJsonObjectProperties(writer);
writer.WriteStartArray("Rules"); // "Rules": [
foreach (var rule in subscription.Rules)
{
writer.WriteStartObject();
rule.WriteJsonObjectProperties(writer);
writer.WriteEndObject();
}
writer.WriteEndArray(); // ] (/Rules)
writer.WriteEndObject(); // } (/Subscription)
}
writer.WriteEndArray(); // ] (/Subscriptions)
writer.WriteEndObject(); // } (/Topic)
}
writer.WriteEndArray(); // ] (/Topics)
writer.WriteEndObject(); // } (/Namespace)
writer.WriteEndArray(); // ], (/Namespaces)
writer.WriteStartObject("Logging"); // "Logging": {
writer.WriteString("Type", "File"); // "Type": "File"
writer.WriteEndObject(); // } (/LoggingConfig)
writer.WriteEndObject(); // } (/UserConfig)
writer.WriteEndObject(); // } (/Root)
}
// Apply ConfigJsonAnnotation modifications
var configJsonAnnotations = emulatorResource.Annotations.OfType<ConfigJsonAnnotation>();
foreach (var annotation in configJsonAnnotations)
{
using var readStream = new FileStream(configFileMount.Source!, FileMode.Open, FileAccess.Read);
var jsonObject = JsonNode.Parse(readStream);
readStream.Close();
using var writeStream = new FileStream(configFileMount.Source!, FileMode.Open, FileAccess.Write);
using var writer = new Utf8JsonWriter(writeStream, new JsonWriterOptions { Indented = true });
if (jsonObject == null)
{
throw new InvalidOperationException("The configuration file mount could not be parsed.");
}
annotation.Configure(jsonObject);
jsonObject.WriteTo(writer);
}
}
});
var healthCheckKey = $"{builder.Resource.Name}_check";
if (configureContainer != null)
{
var surrogate = new AzureServiceBusEmulatorResource(builder.Resource);
var surrogateBuilder = builder.ApplicationBuilder.CreateResourceBuilder(surrogate);
configureContainer(surrogateBuilder);
}
// To use the existing ServiceBus health check we would need to know if there is any queue or topic defined.
// We can register a health check for a queue and then no-op if there are no queues. Same for topics.
// If no queues or no topics are defined then the health check will be successful.
builder.ApplicationBuilder.Services.AddHealthChecks()
.Add(new HealthCheckRegistration(
healthCheckKey,
sp => new ServiceBusHealthCheck(
() => serviceBusClient ?? throw new DistributedApplicationException($"{nameof(serviceBusClient)} was not initialized."),
() => queueOrTopicName),
failureStatus: default,
tags: default,
timeout: default));
builder.WithHealthCheck(healthCheckKey);
return builder;
}
/// <summary>
/// Adds a bind mount for the configuration file of an Azure Service Bus emulator resource.
/// </summary>
/// <param name="builder">The builder for the <see cref="AzureServiceBusEmulatorResource"/>.</param>
/// <param name="path">Path to the file on the AppHost where the emulator configuration is located.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
public static IResourceBuilder<AzureServiceBusEmulatorResource> WithConfigurationFile(this IResourceBuilder<AzureServiceBusEmulatorResource> builder, string path)
{
// Update the existing mount
var configFileMount = builder.Resource.Annotations.OfType<ContainerMountAnnotation>().LastOrDefault(v => v.Target == AzureServiceBusEmulatorResource.EmulatorConfigJsonPath);
if (configFileMount != null)
{
builder.Resource.Annotations.Remove(configFileMount);
}
return builder.WithBindMount(path, AzureServiceBusEmulatorResource.EmulatorConfigJsonPath, isReadOnly: true);
}
/// <summary>
/// Alters the JSON configuration document used by the emulator.
/// </summary>
/// <param name="builder">The builder for the <see cref="AzureServiceBusEmulatorResource"/>.</param>
/// <param name="configJson">A callback to update the JSON object representation of the configuration.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
public static IResourceBuilder<AzureServiceBusEmulatorResource> ConfigureEmulator(this IResourceBuilder<AzureServiceBusEmulatorResource> builder, Action<JsonNode> configJson)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(configJson);
builder.WithAnnotation(new ConfigJsonAnnotation(configJson));
return builder;
}
/// <summary>
/// Configures the host port for the Azure Service Bus emulator is exposed on instead of using randomly assigned port.
/// </summary>
/// <param name="builder">Builder for the Azure Service Bus emulator container</param>
/// <param name="port">The port to bind on the host. If <see langword="null"/> is used, a random port will be assigned.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
public static IResourceBuilder<AzureServiceBusEmulatorResource> WithHostPort(this IResourceBuilder<AzureServiceBusEmulatorResource> builder, int? port)
{
return builder.WithEndpoint("emulator", endpoint =>
{
endpoint.Port = port;
});
}
}