-
-
Notifications
You must be signed in to change notification settings - Fork 372
Expand file tree
/
Copy pathAzureServiceBusTransport.cs
More file actions
375 lines (303 loc) · 12.7 KB
/
Copy pathAzureServiceBusTransport.cs
File metadata and controls
375 lines (303 loc) · 12.7 KB
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
using Azure;
using Azure.Core;
using Azure.Messaging.ServiceBus;
using Azure.Messaging.ServiceBus.Administration;
using JasperFx.Core;
using JasperFx.Descriptors;
using Microsoft.Extensions.Logging;
using Wolverine.AzureServiceBus.Internal;
using Wolverine.Configuration;
using Wolverine.Runtime;
using Wolverine.Transports;
using Wolverine.Transports.Sending;
namespace Wolverine.AzureServiceBus;
public partial class AzureServiceBusTransport : BrokerTransport<AzureServiceBusEndpoint>, IAsyncDisposable
{
public const string ProtocolName = "asb";
public const string ResponseEndpointName = "AzureServiceBusResponses";
public const string RetryEndpointName = "AzureServiceBusRetries";
private readonly Lazy<ServiceBusClient> _busClient;
private readonly Lazy<ServiceBusAdministrationClient> _managementClient;
public readonly List<AzureServiceBusSubscription> Subscriptions = new();
private string _hostName = null!;
public const string DeadLetterQueueName = DeadLetterQueueConstants.DefaultQueueName;
public AzureServiceBusTransport() : this(ProtocolName)
{
}
public AzureServiceBusTransport(string protocolName) : base(protocolName, "Azure Service Bus", ["azure", "azureservicebus"])
{
Queues = new(name => new AzureServiceBusQueue(this, name));
Topics = new(name => new AzureServiceBusTopic(this, name));
_managementClient =
new Lazy<ServiceBusAdministrationClient>(createServiceBusAdministrationClient);
_busClient = new Lazy<ServiceBusClient>(createServiceBusClient);
IdentifierDelimiter = ".";
}
public async Task DeleteAllObjectsAsync()
{
var topics = _managementClient.Value.GetTopicsAsync();
await foreach (var topic in topics)
{
await _managementClient.Value.DeleteTopicAsync(topic.Name);
}
var queues = _managementClient.Value.GetQueuesAsync();
await foreach (var queue in queues)
{
await _managementClient.Value.DeleteQueueAsync(queue.Name);
}
}
public override Uri ResourceUri
{
get
{
var uri = new Uri($"{ProtocolName}://");
if (FullyQualifiedNamespace.IsNotEmpty())
{
uri = new Uri(uri, FullyQualifiedNamespace);
}
return uri;
}
}
public override string SanitizeIdentifier(string identifier)
{
return identifier.ToLowerInvariant();
}
internal LightweightCache<string, AzureServiceBusTenant> Tenants { get; } = new(key => new AzureServiceBusTenant(key));
/// <summary>
/// Is this transport connection allowed to build and use response, retry, and control queues
/// for just this node?
/// </summary>
public bool SystemQueuesEnabled { get; set; } = true;
[IgnoreDescription]
public LightweightCache<string, AzureServiceBusQueue> Queues { get; }
[IgnoreDescription]
public LightweightCache<string, AzureServiceBusTopic> Topics { get; }
// Contains shared access key / password — raw value hidden to avoid
// leaking secrets in diagnostic views. Surfaced via ConnectionSummary below.
[IgnoreDescription]
public string? ConnectionString { get; set; }
/// <summary>
/// Optional separate connection string for the ServiceBusAdministrationClient.
/// When set, the management client uses this instead of ConnectionString.
/// Useful for the Azure Service Bus Emulator which exposes management on a different port.
/// </summary>
[IgnoreDescription]
public string? ManagementConnectionString { get; set; }
/// <summary>
/// The configured connection string with the <c>SharedAccessKey</c> value
/// masked. Safe to render in diagnostic output.
/// </summary>
public string? ConnectionSummary => ConnectionString == null
? null
: ConnectionStringRedactor.Redact(ConnectionString, "SharedAccessKey");
/// <summary>
/// The configured management connection string with the <c>SharedAccessKey</c>
/// value masked. Safe to render in diagnostic output.
/// </summary>
public string? ManagementConnectionSummary => ManagementConnectionString == null
? null
: ConnectionStringRedactor.Redact(ManagementConnectionString, "SharedAccessKey");
public string? FullyQualifiedNamespace { get; set; }
[IgnoreDescription]
public TokenCredential? TokenCredential { get; set; }
[IgnoreDescription]
public AzureNamedKeyCredential? NamedKeyCredential { get; set; }
[IgnoreDescription]
public AzureSasCredential? SasCredential { get; set; }
[ChildDescription]
public ServiceBusClientOptions ClientOptions { get; } = new()
{
TransportType = ServiceBusTransportType.AmqpTcp
};
public async Task WithManagementClientAsync(Func<ServiceBusAdministrationClient, Task> action)
{
await action(_managementClient.Value);
foreach (var tenant in Tenants)
{
tenant.Transport.NamedKeyCredential ??= NamedKeyCredential;
tenant.Transport.SasCredential ??= SasCredential;
tenant.Transport.TokenCredential ??= TokenCredential;
try
{
await tenant.Transport.WithManagementClientAsync(action);
}
catch (Exception)
{
// Tenant management failures should not block the default namespace.
// Tenant resources will be provisioned on demand or by their own hosts.
}
}
}
public async Task WithServiceBusClientAsync(Func<ServiceBusClient, Task> action)
{
await action(BusClient);
foreach (var tenant in Tenants)
{
tenant.Transport.NamedKeyCredential ??= NamedKeyCredential;
tenant.Transport.SasCredential ??= SasCredential;
tenant.Transport.TokenCredential ??= TokenCredential;
try
{
await tenant.Transport.WithServiceBusClientAsync(action);
}
catch (Exception)
{
// Tenant management failures should not block the default namespace.
// Tenant resources will be provisioned on demand or by their own hosts.
}
}
}
public ServiceBusClient BusClient => _busClient.Value;
public ServiceBusAdministrationClient ManagementClient => _managementClient.Value;
public async ValueTask DisposeAsync()
{
if (_busClient.IsValueCreated)
{
await _busClient.Value.DisposeAsync();
}
foreach (var tenant in Tenants)
{
await tenant.Transport.DisposeAsync();
}
}
protected override void tryBuildSystemEndpoints(IWolverineRuntime runtime)
{
if (!SystemQueuesEnabled) return;
// In Solo mode the assigned node number is always 1 (#3188) and the service name is not
// unique per host, so multiple Solo hosts on one namespace would share a response queue and
// cross-deliver replies — key on the always-unique UniqueNodeId instead. Balanced gets a
// unique AssignedNodeNumber via election. See #3189.
var responseNode = runtime.Options.Durability.Mode == DurabilityMode.Solo
? runtime.Options.UniqueNodeId.ToString("N")
: runtime.DurabilitySettings.AssignedNodeNumber.ToString();
var queueName = $"wolverine.response.{runtime.Options.ServiceName}.{responseNode}";
var queue = Queues[queueName];
queue.Options.AutoDeleteOnIdle = 5.Minutes();
queue.Mode = EndpointMode.BufferedInMemory;
queue.IsListener = true;
queue.EndpointName = ResponseEndpointName;
queue.IsUsedForReplies = true;
queue.Role = EndpointRole.System;
var retryName = SanitizeIdentifier($"wolverine.retries.{runtime.Options.ServiceName}".ToLower());
var retryQueue = Queues[retryName];
retryQueue.Mode = EndpointMode.BufferedInMemory;
retryQueue.IsListener = true;
retryQueue.EndpointName = RetryEndpointName;
retryQueue.Role = EndpointRole.System;
RetryQueue = retryQueue;
}
public override Endpoint? ReplyEndpoint()
{
var replies = base.ReplyEndpoint();
if (replies is AzureServiceBusQueue) return replies;
return null;
}
internal AzureServiceBusQueue? RetryQueue { get; set; }
public string HostName
{
get
{
if (_hostName == null)
{
var parts = ConnectionString!.Split(';');
foreach (var part in parts)
{
var split = part.Split('=');
if (split[0].EqualsIgnoreCase("Endpoint"))
{
_hostName = new Uri(split[1]).Host;
}
}
}
return _hostName!;
}
}
protected override IEnumerable<Endpoint> explicitEndpoints()
{
foreach (var queue in Queues) yield return queue;
foreach (var topic in Topics) yield return topic;
foreach (var subscription in Subscriptions) yield return subscription;
}
protected override IEnumerable<AzureServiceBusEndpoint> endpoints()
{
var dlqNames = Queues.Select(x => x.DeadLetterQueueName).Where(x => x.IsNotEmpty()).Distinct().ToArray();
foreach (var dlqName in dlqNames)
{
Queues.FillDefault(dlqName!);
}
foreach (var queue in Queues) yield return queue;
foreach (var topic in Topics) yield return topic;
foreach (var subscription in Subscriptions) yield return subscription;
}
protected override AzureServiceBusEndpoint findEndpointByUri(Uri uri)
{
switch (uri.Host)
{
case "queue":
return Queues[Uri.UnescapeDataString(uri.Segments[1])];
case "topic":
var topicName = Uri.UnescapeDataString(uri.Segments[1].TrimEnd('/'));
if (uri.Segments.Length == 3)
{
var subscription = Subscriptions.FirstOrDefault(x => x.Uri == uri);
if (subscription != null)
{
return subscription;
}
var subscriptionName = Uri.UnescapeDataString(uri.Segments.Last().TrimEnd('/'));
var topic = Topics[topicName];
subscription = new AzureServiceBusSubscription(this, topic, subscriptionName);
Subscriptions.Add(subscription);
return subscription;
}
return Topics[topicName];
}
throw new ArgumentOutOfRangeException(nameof(uri));
}
public override ValueTask ConnectAsync(IWolverineRuntime runtime)
{
// we're going to use a client per endpoint
return ValueTask.CompletedTask;
}
public WolverineTransportHealthCheck BuildHealthCheck(IWolverineRuntime runtime)
{
return new AzureServiceBusHealthCheck(this);
}
public override IEnumerable<PropertyColumn> DiagnosticColumns()
{
yield return new PropertyColumn("Queue", "Name");
yield return new PropertyColumn(nameof(QueueProperties.Status));
}
private ServiceBusClient createServiceBusClient()
{
if (FullyQualifiedNamespace.IsNotEmpty() && TokenCredential != null)
{
return new ServiceBusClient(FullyQualifiedNamespace, TokenCredential, ClientOptions);
}
if (FullyQualifiedNamespace.IsNotEmpty() && NamedKeyCredential != null)
{
return new ServiceBusClient(FullyQualifiedNamespace, NamedKeyCredential, ClientOptions);
}
if (FullyQualifiedNamespace.IsNotEmpty() && SasCredential != null)
{
return new ServiceBusClient(FullyQualifiedNamespace, SasCredential, ClientOptions);
}
return new ServiceBusClient(ConnectionString, ClientOptions);
}
private ServiceBusAdministrationClient createServiceBusAdministrationClient()
{
if (FullyQualifiedNamespace.IsNotEmpty() && TokenCredential != null)
{
return new ServiceBusAdministrationClient(FullyQualifiedNamespace, TokenCredential);
}
if (FullyQualifiedNamespace.IsNotEmpty() && NamedKeyCredential != null)
{
return new ServiceBusAdministrationClient(FullyQualifiedNamespace, NamedKeyCredential);
}
if (FullyQualifiedNamespace.IsNotEmpty() && SasCredential != null)
{
return new ServiceBusAdministrationClient(FullyQualifiedNamespace, SasCredential);
}
return new ServiceBusAdministrationClient(ManagementConnectionString ?? ConnectionString);
}
}