-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathAzureServiceBus.cs
More file actions
1529 lines (1410 loc) · 57.7 KB
/
AzureServiceBus.cs
File metadata and controls
1529 lines (1410 loc) · 57.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
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region Copyright
// // -----------------------------------------------------------------------
// // <copyright company="Chinchilla Software Limited">
// // Copyright Chinchilla Software Limited. All rights reserved.
// // </copyright>
// // -----------------------------------------------------------------------
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Chinchilla.Logging;
using Cqrs.Authentication;
using Cqrs.Bus;
using Cqrs.Configuration;
using Cqrs.Exceptions;
using Cqrs.Messages;
#if NETSTANDARD2_0 || NET48_OR_GREATER
using Azure.Messaging.ServiceBus;
using BrokeredMessage = Azure.Messaging.ServiceBus.ServiceBusReceivedMessage;
using IMessageReceiver = Azure.Messaging.ServiceBus.ServiceBusProcessor;
using Manager = Azure.Messaging.ServiceBus.Administration.ServiceBusAdministrationClient;
using TopicClient = Azure.Messaging.ServiceBus.ServiceBusSender;
using TopicDescription = Azure.Messaging.ServiceBus.Administration.CreateTopicOptions;
using Azure.Identity;
using Azure.Messaging.ServiceBus.Administration;
#else
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using Manager = Microsoft.ServiceBus.NamespaceManager;
using IMessageReceiver = Microsoft.ServiceBus.Messaging.SubscriptionClient;
#endif
#if NET472
using Microsoft.Identity.Client;
#endif
namespace Cqrs.Azure.ServiceBus
{
/// <summary>
/// An <see cref="AzureBus{TAuthenticationToken}"/> that uses Azure Service Bus.
/// </summary>
/// <typeparam name="TAuthenticationToken">The <see cref="Type"/> of the authentication token.</typeparam>
/// <remarks>
/// https://markheath.net/post/migrating-to-new-servicebus-sdk
/// https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-how-to-use-topics-subscriptions#receive-messages-from-the-subscription
/// https://stackoverflow.com/questions/47427361/azure-service-bus-read-messages-sent-by-net-core-2-with-brokeredmessage-getbo
/// https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-get-started-with-queues
/// </remarks>
public abstract class AzureServiceBus<TAuthenticationToken>
: AzureBus<TAuthenticationToken>
{
/// <summary>
/// Gets the private <see cref="TopicClient"/> publisher.
/// </summary>
protected TopicClient PrivateServiceBusPublisher { get; private set; }
/// <summary>
/// Gets the public <see cref="TopicClient"/> publisher.
/// </summary>
protected TopicClient PublicServiceBusPublisher { get; private set; }
/// <summary>
/// Gets the private <see cref="IMessageReceiver"/> receivers.
/// </summary>
protected IDictionary<int, IMessageReceiver> PrivateServiceBusReceivers { get; private set; }
/// <summary>
/// Gets the public <see cref="IMessageReceiver"/> receivers.
/// </summary>
protected IDictionary<int, IMessageReceiver> PublicServiceBusReceivers { get; private set; }
/// <summary>
/// The name of the private topic.
/// </summary>
protected string PrivateTopicName { get; set; }
/// <summary>
/// The name of the public topic.
/// </summary>
protected string PublicTopicName { get; set; }
/// <summary>
/// The name of the subscription in the private topic.
/// </summary>
protected string PrivateTopicSubscriptionName { get; set; }
/// <summary>
/// The name of the subscription in the public topic.
/// </summary>
protected string PublicTopicSubscriptionName { get; set; }
/// <summary>
/// The configuration key for the message bus connection string as used by <see cref="IConfigurationManager"/>.
/// </summary>
protected abstract string MessageBusConnectionStringConfigurationKey { get; }
/// <summary>
/// The configuration key for the message bus connection endpoint as used by <see cref="IConfigurationManager"/>, when using RBAC.
/// </summary>
protected abstract string MessageBusConnectionEndpointConfigurationKey { get; }
/// <summary>
/// The configuration key for the message bus connection Application Id as used by <see cref="IConfigurationManager"/>, when using RBAC.
/// </summary>
protected abstract string MessageBusConnectionApplicationIdConfigurationKey { get; }
/// <summary>
/// The configuration key for the message bus connection Client Key/Secret as used by <see cref="IConfigurationManager"/>, when using RBAC.
/// </summary>
protected abstract string MessageBusConnectionClientKeyConfigurationKey { get; }
/// <summary>
/// The configuration key for the message bus connection Tenant Id as used by <see cref="IConfigurationManager"/>, when using RBAC.
/// </summary>
protected abstract string MessageBusConnectionTenantIdConfigurationKey { get; }
/// <summary>
/// The configuration key for the signing token as used by <see cref="IConfigurationManager"/>.
/// </summary>
protected abstract string SigningTokenConfigurationKey { get; }
/// <summary>
/// The configuration key for the name of the private topic as used by <see cref="IConfigurationManager"/>.
/// </summary>
protected abstract string PrivateTopicNameConfigurationKey { get; }
/// <summary>
/// The configuration key for the name of the public topic as used by <see cref="IConfigurationManager"/>.
/// </summary>
protected abstract string PublicTopicNameConfigurationKey { get; }
/// <summary>
/// The default name of the private topic if no <see cref="IConfigurationManager"/> value is set.
/// </summary>
protected abstract string DefaultPrivateTopicName { get; }
/// <summary>
/// The default name of the public topic if no <see cref="IConfigurationManager"/> value is set.
/// </summary>
protected abstract string DefaultPublicTopicName { get; }
/// <summary>
/// The configuration key for the name of the subscription in the private topic as used by <see cref="IConfigurationManager"/>.
/// </summary>
protected abstract string PrivateTopicSubscriptionNameConfigurationKey { get; }
/// <summary>
/// The configuration key for the name of the subscription in the public topic as used by <see cref="IConfigurationManager"/>.
/// </summary>
protected abstract string PublicTopicSubscriptionNameConfigurationKey { get; }
/// <summary>
/// The configuration key that
/// specifies if an <see cref="Exception"/> is thrown if the network lock is lost
/// as used by <see cref="IConfigurationManager"/>.
/// </summary>
protected abstract string ThrowExceptionOnReceiverMessageLockLostExceptionDuringCompleteConfigurationKey { get; }
/// <summary>
/// Specifies if an <see cref="Exception"/> is thrown if the network lock is lost.
/// </summary>
protected bool ThrowExceptionOnReceiverMessageLockLostExceptionDuringComplete { get; set; }
/// <summary>
/// The default name of the subscription in the private topic if no <see cref="IConfigurationManager"/> value is set.
/// </summary>
protected const string DefaultPrivateTopicSubscriptionName = "Root";
/// <summary>
/// The default name of the subscription in the public topic if no <see cref="IConfigurationManager"/> value is set.
/// </summary>
protected const string DefaultPublicTopicSubscriptionName = "Root";
#if NETSTANDARD2_0 || NET48_OR_GREATER
/// <summary>
/// The <see cref="Func{ProcessMessageEventArgs}">handler</see> used for <see cref="ServiceBusProcessor.OnProcessMessageAsync(ProcessMessageEventArgs)"/> on each receiver.
/// </summary>
protected virtual Func<ProcessMessageEventArgs, Task> ReceiverMessageHandler { get; set; }
#else
/// <summary>
/// The <see cref="Action{TBrokeredMessage}">handler</see> used for <see cref="IMessageReceiver.OnMessage(System.Action{Microsoft.ServiceBus.Messaging.BrokeredMessage}, OnMessageOptions)"/> on each receiver.
/// </summary>
protected Action<IMessageReceiver, BrokeredMessage> ReceiverMessageHandler { get; set; }
#endif
#if NETSTANDARD2_0 || NET48_OR_GREATER
/// <summary>
/// The <see cref="ServiceBusProcessorOptions" /> used.
/// </summary>
protected virtual ServiceBusProcessorOptions ReceiverMessageHandlerOptions { get; set; }
#else
/// <summary>
/// The <see cref="OnMessageOptions" /> used for <see cref="IMessageReceiver.OnMessage(System.Action{Microsoft.ServiceBus.Messaging.BrokeredMessage}, OnMessageOptions)"/> on each receiver.
/// </summary>
protected OnMessageOptions ReceiverMessageHandlerOptions { get; set; }
#endif
/// <summary>
/// Gets the <see cref="IBusHelper"/>.
/// </summary>
protected IBusHelper BusHelper { get; private set; }
/// <summary>
/// Gets the <see cref="IAzureBusHelper{TAuthenticationToken}"/>.
/// </summary>
protected IAzureBusHelper<TAuthenticationToken> AzureBusHelper { get; private set; }
/// <summary>
/// Gets the <see cref="ITelemetryHelper"/>.
/// </summary>
protected ITelemetryHelper TelemetryHelper { get; set; }
/// <summary>
/// The maximum number of time a retry is tried if a <see cref="System.TimeoutException"/> is thrown while sending messages.
/// </summary>
protected short TimeoutOnSendRetryMaximumCount { get; private set; }
/// <summary>
/// Use WebSockets rather than AMQP on port 5671
/// </summary>
protected bool UseWebSockets { get; private set; }
/// <summary>
/// The <see cref="IHashAlgorithmFactory"/> to use to sign messages.
/// </summary>
protected IHashAlgorithmFactory Signer { get; private set; }
/// <summary>
/// A list of namespaces to exclude when trying to automatically determine the container.
/// </summary>
protected IList<string> ExclusionNamespaces { get; private set; }
private IList<string> TaskRelatedMethodNames { get; }
private Regex ContainerNameMatcher { get; }
#if NET472
/// <summary>
/// Gets an access token from Active Directory when using RBAC based connections.
/// </summary>
protected AzureActiveDirectoryTokenProvider.AuthenticationCallback GetActiveDirectoryToken { get; private set; }
#endif
/// <summary>
/// Instantiates a new instance of <see cref="AzureServiceBus{TAuthenticationToken}"/>
/// </summary>
protected AzureServiceBus(IConfigurationManager configurationManager, IMessageSerialiser<TAuthenticationToken> messageSerialiser, IAuthenticationTokenHelper<TAuthenticationToken> authenticationTokenHelper, ICorrelationIdHelper correlationIdHelper, ILogger logger, IAzureBusHelper<TAuthenticationToken> azureBusHelper, IBusHelper busHelper, IHashAlgorithmFactory hashAlgorithmFactory, bool isAPublisher)
: base(configurationManager, messageSerialiser, authenticationTokenHelper, correlationIdHelper, logger, isAPublisher)
{
AzureBusHelper = azureBusHelper;
BusHelper = busHelper;
Signer = hashAlgorithmFactory;
TelemetryHelper = new NullTelemetryHelper();
PrivateServiceBusReceivers = new Dictionary<int, IMessageReceiver>();
PublicServiceBusReceivers = new Dictionary<int, IMessageReceiver>();
TimeoutOnSendRetryMaximumCount = 1;
string timeoutOnSendRetryMaximumCountValue;
short timeoutOnSendRetryMaximumCount;
if (ConfigurationManager.TryGetSetting("Cqrs.Azure.Servicebus.TimeoutOnSendRetryMaximumCount", out timeoutOnSendRetryMaximumCountValue) && !string.IsNullOrWhiteSpace(timeoutOnSendRetryMaximumCountValue) && short.TryParse(timeoutOnSendRetryMaximumCountValue, out timeoutOnSendRetryMaximumCount))
TimeoutOnSendRetryMaximumCount = timeoutOnSendRetryMaximumCount;
if (ConfigurationManager.TryGetSetting("Cqrs.Azure.Servicebus.UseWebSockets", out bool useWebSockets))
UseWebSockets = useWebSockets;
else
UseWebSockets = false;
ExclusionNamespaces = new SynchronizedCollection<string> { "Cqrs", "System" };
TaskRelatedMethodNames = new List<string>
{
"MoveNext",
"Start"
};
ContainerNameMatcher = new Regex("^(.)+?>", RegexOptions.IgnoreCase);
#if NET472
InstantiateActiveDirectoryToken();
#endif
}
#if NET472
/// <summary>
/// Setup <see cref="GetActiveDirectoryToken"/>
/// </summary>
protected virtual void InstantiateActiveDirectoryToken()
{
GetActiveDirectoryToken = async (audience, authority, state) =>
{
string applicationId = ConfigurationManager.GetSetting(MessageBusConnectionApplicationIdConfigurationKey);
string clientKey = ConfigurationManager.GetSetting(MessageBusConnectionClientKeyConfigurationKey);
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(applicationId)
.WithAuthority(authority)
.WithClientSecret(clientKey)
.Build();
var authResult = await app
.AcquireTokenForClient(new string[] { "https://servicebus.azure.net/.default" })
.ExecuteAsync();
return authResult.AccessToken;
};
}
#endif
#if NETSTANDARD2_0 || NET48_OR_GREATER
/// <summary>
/// The underlaying <see cref="ServiceBusClient"/>.
/// Do not use this directly. Use <see cref="GetOrCreateClientAsync"/>
/// </summary>
private ServiceBusClient ServiceBusClient { get; set; }
private static SemaphoreSlim lockObject = new SemaphoreSlim(1, 1);
/// <summary>
/// Get the current <see cref="ServiceBusClient"/> or creates and returns one if it has not yet been created
/// </summary>
protected virtual async Task<ServiceBusClient> GetOrCreateClientAsync()
{
if (ServiceBusClient == null)
{
await lockObject.WaitAsync();
try
{
// now recheck as we've been locked
if (ServiceBusClient == null)
{
string connectionString = ConnectionString;
AzureBusRbacSettings rbacSettings = RbacConnectionSettings;
var clientOptions = new ServiceBusClientOptions
{
TransportType = UseWebSockets
? ServiceBusTransportType.AmqpWebSockets
: ServiceBusTransportType.AmqpTcp,
Identifier = Logger.LoggerSettings.ModuleName
};
if (!string.IsNullOrWhiteSpace(connectionString))
ServiceBusClient = new ServiceBusClient(connectionString, clientOptions);
else
{
var credentials = new ClientSecretCredential(rbacSettings.TenantId, rbacSettings.ApplicationId, rbacSettings.ClientKey);
ServiceBusClient = new ServiceBusClient(rbacSettings.Endpoint, credentials, clientOptions);
}
}
}
finally
{
//When the task is ready, release the semaphore. It is vital to ALWAYS release the semaphore when we are ready, or else we will end up with a Semaphore that is forever locked.
//This is why it is important to do the Release within a try...finally clause; program execution may crash or take a different path, this way you are guaranteed execution
lockObject.Release();
}
}
return await Task.FromResult(ServiceBusClient);
}
#endif
#region Overrides of AzureBus<TAuthenticationToken>
/// <summary>
/// Gets the connection string for the bus from <see cref="AzureBus{TAuthenticationToken}.ConfigurationManager"/>
/// </summary>
protected override
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task<string> GetConnectionStringAsync
#else
string GetConnectionString
#endif
()
{
if (!ConfigurationManager.TryGetSetting(MessageBusConnectionStringConfigurationKey, out string connectionString))
connectionString = null;
if (string.IsNullOrWhiteSpace(connectionString))
{
string connectionEndpoint = ConfigurationManager.GetSetting(MessageBusConnectionEndpointConfigurationKey);
// double check an endpoint isn't provided, if it is, then we're using endpoints, but if not, we'll assume a connection string is prefered as it's easier
if (string.IsNullOrWhiteSpace(connectionEndpoint))
throw new MissingApplicationSettingForConnectionStringException(MessageBusConnectionStringConfigurationKey);
}
#if NETSTANDARD2_0 || NET48_OR_GREATER
return await Task.FromResult(connectionString);
#else
return connectionString;
#endif
}
/// <summary>
/// Gets the RBAC connection settings for the bus from <see cref="AzureBus{TAuthenticationToken}.ConfigurationManager"/>
/// </summary>
protected override
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task<AzureBusRbacSettings> GetRbacConnectionSettingsAsync
#else
AzureBusRbacSettings GetRbacConnectionSettings
#endif
()
{
// double check an endpoint isn't provided, if it is, then we're using endpoints, but if not, we'll assume a connection string is prefered as it's easier
bool isUsingConnectionString;
if (!ConfigurationManager.TryGetSetting(MessageBusConnectionStringConfigurationKey, out string connectionString))
isUsingConnectionString = false;
else
isUsingConnectionString = !string.IsNullOrWhiteSpace(connectionString);
if (!ConfigurationManager.TryGetSetting(MessageBusConnectionEndpointConfigurationKey, out string endpoint))
endpoint = null;
if (!isUsingConnectionString && string.IsNullOrWhiteSpace(endpoint))
throw new MissingApplicationSettingForConnectionStringException(MessageBusConnectionEndpointConfigurationKey);
if (!ConfigurationManager.TryGetSetting(MessageBusConnectionApplicationIdConfigurationKey, out string applicationId))
applicationId = null;
if (!isUsingConnectionString && string.IsNullOrWhiteSpace(applicationId))
throw new MissingApplicationSettingForConnectionStringException(MessageBusConnectionApplicationIdConfigurationKey);
if (!ConfigurationManager.TryGetSetting(MessageBusConnectionClientKeyConfigurationKey, out string clientKey))
clientKey = null;
if (!isUsingConnectionString && string.IsNullOrWhiteSpace(clientKey))
throw new MissingApplicationSettingForConnectionStringException(MessageBusConnectionClientKeyConfigurationKey);
if (!ConfigurationManager.TryGetSetting(MessageBusConnectionTenantIdConfigurationKey, out string tenantId))
tenantId = null;
if (!isUsingConnectionString && string.IsNullOrWhiteSpace(tenantId))
throw new MissingApplicationSettingForConnectionStringException(MessageBusConnectionTenantIdConfigurationKey);
var result = new AzureBusRbacSettings
{
Endpoint = endpoint,
ApplicationId = applicationId,
ClientKey = clientKey,
TenantId = tenantId
};
#if NETSTANDARD2_0 || NET48_OR_GREATER
return await Task.FromResult(result);
#else
return result;
#endif
}
#endregion
#if NETSTANDARD2_0 || NET48_OR_GREATER
/// <summary>
/// Instantiate publishing on this bus by
/// calling <see cref="CheckPrivateTopicExistsAsync(Manager, bool)"/> and <see cref="CheckPublicTopicExistsAsync(Manager, bool)"/>
/// then calling <see cref="AzureBus{TAuthenticationToken}.StartSettingsChecking"/>
/// </summary>
#else
/// <summary>
/// Instantiate publishing on this bus by
/// calling <see cref="CheckPrivateTopicExists"/> and <see cref="CheckPublicTopicExists"/>
/// then calling <see cref="AzureBus{TAuthenticationToken}.StartSettingsChecking"/>
/// </summary>
#endif
protected override
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task InstantiatePublishingAsync
#else
void InstantiatePublishing
#endif
()
{
#if NET472
if (GetActiveDirectoryToken == null)
InstantiateActiveDirectoryToken();
#endif
Manager manager =
#if NETSTANDARD2_0 || NET48_OR_GREATER
await GetManagerAsync
#else
GetManager
#endif
();
#if NETSTANDARD2_0 || NET48_OR_GREATER
await CheckPrivateTopicExistsAsync(manager, false);
await CheckPublicTopicExistsAsync(manager, false);
#else
CheckPrivateTopicExists(manager, false);
CheckPublicTopicExists(manager, false);
#endif
#if NETSTANDARD2_0 || NET48_OR_GREATER
ServiceBusClient client = await GetOrCreateClientAsync();
PrivateServiceBusPublisher = client.CreateSender(PrivateTopicName, new ServiceBusSenderOptions { Identifier = $"{Logger.LoggerSettings.ModuleName} Private Bus" });
PublicServiceBusPublisher = client.CreateSender(PublicTopicName, new ServiceBusSenderOptions { Identifier = $"{Logger.LoggerSettings.ModuleName} Public Bus" });
#else
if (!string.IsNullOrWhiteSpace(ConnectionString))
{
PrivateServiceBusPublisher = TopicClient.CreateFromConnectionString(ConnectionString, PrivateTopicName);
PublicServiceBusPublisher = TopicClient.CreateFromConnectionString(ConnectionString, PublicTopicName);
}
else
{
PrivateServiceBusPublisher = TopicClient.CreateWithAzureActiveDirectory(new Uri(RbacConnectionSettings.Endpoint), PrivateTopicName, GetActiveDirectoryToken, RbacConnectionSettings.GetDefaultAuthority());
PublicServiceBusPublisher = TopicClient.CreateWithAzureActiveDirectory(new Uri(RbacConnectionSettings.Endpoint), PublicTopicName, GetActiveDirectoryToken, RbacConnectionSettings.GetDefaultAuthority());
}
#endif
StartSettingsChecking();
}
#if NETSTANDARD2_0 || NET48_OR_GREATER
/// <summary>
/// Instantiate receiving on this bus by
/// calling <see cref="CheckPrivateTopicExistsAsync(Manager, bool)"/> and <see cref="CheckPublicTopicExistsAsync(Manager, bool)"/>
/// then InstantiateReceiving for private and public topics,
/// calls <see cref="CleanUpDeadLettersAsync(string, string)"/> for the private and public topics,
/// then calling <see cref="AzureBus{TAuthenticationToken}.StartSettingsChecking"/>
/// </summary>
#else
/// <summary>
/// Instantiate receiving on this bus by
/// calling <see cref="CheckPrivateTopicExists"/> and <see cref="CheckPublicTopicExists"/>
/// then InstantiateReceiving for private and public topics,
/// calls <see cref="CleanUpDeadLetters"/> for the private and public topics,
/// then calling <see cref="AzureBus{TAuthenticationToken}.StartSettingsChecking"/>
/// </summary>
#endif
protected override
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task InstantiateReceivingAsync
#else
void InstantiateReceiving
#endif
()
{
Manager manager =
#if NETSTANDARD2_0 || NET48_OR_GREATER
await GetManagerAsync
#else
GetManager
#endif
();
string connectionString = ConnectionString;
AzureBusRbacSettings rbacSettings = RbacConnectionSettings;
#if NETSTANDARD2_0 || NET48_OR_GREATER
await CheckPrivateTopicExistsAsync(manager);
await CheckPublicTopicExistsAsync(manager);
#else
CheckPrivateTopicExists(manager);
CheckPublicTopicExists(manager);
#endif
try
{
#if NETSTANDARD2_0 || NET48_OR_GREATER
await InstantiateReceivingAsync
#else
InstantiateReceiving
#endif
(manager, PrivateServiceBusReceivers, PrivateTopicName, PrivateTopicSubscriptionName);
}
catch (UriFormatException exception)
{
throw new InvalidConfigurationException("The connection string for one of the private Service Bus receivers may be invalid.", exception);
}
try
{
#if NETSTANDARD2_0 || NET48_OR_GREATER
await InstantiateReceivingAsync
#else
InstantiateReceiving
#endif
(manager, PublicServiceBusReceivers, PublicTopicName, PublicTopicSubscriptionName);
}
catch (UriFormatException exception)
{
throw new InvalidConfigurationException("The connection string for one of the public Service Bus receivers may be invalid.", exception);
}
bool enableDeadLetterCleanUp;
string enableDeadLetterCleanUpValue = ConfigurationManager.GetSetting("Cqrs.Azure.Servicebus.EnableDeadLetterCleanUp");
if (bool.TryParse(enableDeadLetterCleanUpValue, out enableDeadLetterCleanUp) && enableDeadLetterCleanUp)
{
#if NETSTANDARD2_0 || NET48_OR_GREATER
await CleanUpDeadLettersAsync(PrivateTopicName, PrivateTopicSubscriptionName);
await CleanUpDeadLettersAsync(PublicTopicName, PublicTopicSubscriptionName);
#else
CleanUpDeadLetters(PrivateTopicName, PrivateTopicSubscriptionName);
CleanUpDeadLetters(PublicTopicName, PublicTopicSubscriptionName);
#endif
}
// If this is also a publisher, then it will the check over there and that will handle this
// we only need to check one of these
if (PublicServiceBusPublisher != null)
return;
StartSettingsChecking();
}
#if NETSTANDARD2_0 || NET48_OR_GREATER
/// <summary>
/// Creates a single <see cref="IMessageReceiver"/>.
/// If flushing is required, any flushed <see cref="IMessageReceiver"/> has <see cref="IMessageReceiver.CloseAsync(CancellationToken)"/> called on it first.
/// </summary>
/// <param name="manager">The <see cref="Manager"/>.</param>
/// <param name="serviceBusReceivers">The receivers collection to place <see cref="IMessageReceiver"/> instances into.</param>
/// <param name="topicName">The topic name.</param>
/// <param name="topicSubscriptionName">The topic subscription name.</param>
#else
/// <summary>
/// Creates <see cref="AzureBus{TAuthenticationToken}.NumberOfReceiversCount"/> <see cref="IMessageReceiver"/>.
/// If flushing is required, any flushed <see cref="IMessageReceiver"/> has <see cref="ClientEntity.Close()"/> called on it first.
/// </summary>
/// <param name="manager">The <see cref="Manager"/>.</param>
/// <param name="serviceBusReceivers">The receivers collection to place <see cref="IMessageReceiver"/> instances into.</param>
/// <param name="topicName">The topic name.</param>
/// <param name="topicSubscriptionName">The topic subscription name.</param>
#endif
protected virtual
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task InstantiateReceivingAsync
#else
void InstantiateReceiving
#endif
(Manager manager, IDictionary<int, IMessageReceiver> serviceBusReceivers, string topicName, string topicSubscriptionName)
{
#if NETSTANDARD2_0 || NET48_OR_GREATER
IMessageReceiver serviceBusReceiver = (await GetOrCreateClientAsync()).CreateProcessor(topicName, topicSubscriptionName, new ServiceBusProcessorOptions { ReceiveMode = ServiceBusReceiveMode.PeekLock, Identifier = $"{Logger.LoggerSettings.ModuleName} Receiver", AutoCompleteMessages = false, MaxConcurrentCalls = MaximumConcurrentReceiverProcessesCount, MaxAutoLockRenewalDuration = new TimeSpan(0, 5, 0) });
if (serviceBusReceivers.ContainsKey(0))
{
await serviceBusReceivers[0].CloseAsync();
await serviceBusReceivers[0].DisposeAsync();
serviceBusReceivers[0] = serviceBusReceiver;
}
else
serviceBusReceivers.Add(0, serviceBusReceiver);
await Task.CompletedTask;
#else
for (int i = 0; i < NumberOfReceiversCount; i++)
{
IMessageReceiver serviceBusReceiver;
string connectionString = ConnectionString;
AzureBusRbacSettings rbacSettings = RbacConnectionSettings;
if (!string.IsNullOrWhiteSpace(connectionString))
serviceBusReceiver = SubscriptionClient.CreateFromConnectionString(ConnectionString, topicName, topicSubscriptionName);
else
serviceBusReceiver = SubscriptionClient.CreateWithAzureActiveDirectory(new Uri(rbacSettings.Endpoint), topicName, topicSubscriptionName, GetActiveDirectoryToken, rbacSettings.GetDefaultAuthority());
if (serviceBusReceivers.ContainsKey(i))
serviceBusReceivers[i] = serviceBusReceiver;
else
serviceBusReceivers.Add(i, serviceBusReceiver);
}
// Remove any if the number has decreased
for (int i = NumberOfReceiversCount; i < serviceBusReceivers.Count; i++)
{
IMessageReceiver serviceBusReceiver;
if (serviceBusReceivers.TryGetValue(i, out serviceBusReceiver))
{
serviceBusReceiver.Close();
}
serviceBusReceivers.Remove(i);
}
#endif
}
/// <summary>
/// Checks if the private topic and subscription name exists as per <see cref="PrivateTopicName"/> and <see cref="PrivateTopicSubscriptionName"/>.
/// </summary>
/// <param name="manager">The <see cref="Manager"/>.</param>
/// <param name="createSubscriptionIfNotExists">Create a subscription if there isn't one</param>
protected virtual
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task CheckPrivateTopicExistsAsync
#else
void CheckPrivateTopicExists
#endif
(Manager manager, bool createSubscriptionIfNotExists = true)
{
#if NETSTANDARD2_0 || NET48_OR_GREATER
await CheckTopicExistsAsync
#else
CheckTopicExists
#endif
(manager, PrivateTopicName = ConfigurationManager.GetSetting(PrivateTopicNameConfigurationKey) ?? DefaultPrivateTopicName, PrivateTopicSubscriptionName = ConfigurationManager.GetSetting(PrivateTopicSubscriptionNameConfigurationKey) ?? DefaultPrivateTopicSubscriptionName, createSubscriptionIfNotExists);
Logger.LogSensitive($"Private topic settings set.", metaData: new Dictionary<string, object> {
{ "PrivateTopicName", PrivateTopicName },
{ "PrivateTopicSubscriptionName", PrivateTopicSubscriptionName }
});
}
/// <summary>
/// Checks if the public topic and subscription name exists as per <see cref="PublicTopicName"/> and <see cref="PublicTopicSubscriptionName"/>.
/// </summary>
/// <param name="manager">The <see cref="Manager"/>.</param>
/// <param name="createSubscriptionIfNotExists">Create a subscription if there isn't one</param>
protected virtual
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task CheckPublicTopicExistsAsync
#else
void CheckPublicTopicExists
#endif
(Manager manager, bool createSubscriptionIfNotExists = true)
{
#if NETSTANDARD2_0 || NET48_OR_GREATER
await CheckTopicExistsAsync
#else
CheckTopicExists
#endif
(manager, PublicTopicName = ConfigurationManager.GetSetting(PublicTopicNameConfigurationKey) ?? DefaultPublicTopicName, PublicTopicSubscriptionName = ConfigurationManager.GetSetting(PublicTopicSubscriptionNameConfigurationKey) ?? DefaultPublicTopicSubscriptionName, createSubscriptionIfNotExists);
Logger.LogSensitive($"Public topic settings set.", metaData: new Dictionary<string, object> {
{ "PublicTopicName", PublicTopicName },
{ "PublicTopicSubscriptionName", PublicTopicSubscriptionName }
});
}
/// <summary>
/// Checks if a topic by the provided <paramref name="topicName"/> exists and
/// Checks if a subscription name by the provided <paramref name="subscriptionName"/> exists.
/// </summary>
protected virtual
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task CheckTopicExistsAsync
#else
void CheckTopicExists
#endif
(Manager manager, string topicName, string subscriptionName, bool createSubscriptionIfNotExists = true)
{
// Configure Queue Settings
var eventTopicDescription = new TopicDescription(topicName)
{
MaxSizeInMegabytes = 5120,
DefaultMessageTimeToLive = new TimeSpan(0, 25, 0),
EnablePartitioning = true,
EnableBatchedOperations = true,
// forcing this requires an ability to set session ids which will need to be built into the framework
// SupportOrdering = true
};
#if NETSTANDARD2_0 || NET48_OR_GREATER
bool topicExists = await manager.TopicExistsAsync(topicName);
if (!topicExists)
{
TopicProperties createdTopic = await manager.CreateTopicAsync(eventTopicDescription);
Logger.LogInfo($"Created topic '{createdTopic.Name}'");
}
if (createSubscriptionIfNotExists)
{
bool subscriptionExists = await manager.SubscriptionExistsAsync(topicName, subscriptionName);
if (!subscriptionExists)
{
var subscriptionDescription = new CreateSubscriptionOptions(topicName, subscriptionName)
{
DefaultMessageTimeToLive = eventTopicDescription.DefaultMessageTimeToLive,
EnableBatchedOperations = eventTopicDescription.EnableBatchedOperations,
DeadLetteringOnMessageExpiration = true,
LockDuration = new TimeSpan(0, 5, 0)
};
SubscriptionProperties createdSubscription = await manager.CreateSubscriptionAsync(subscriptionDescription);
Logger.LogInfo($"Created subscription '{createdSubscription.SubscriptionName}' on topic '{createdSubscription.TopicName}'");
}
}
#else
// Create the topic if it does not exist already
if (!manager.TopicExists(eventTopicDescription.Path))
{
TopicDescription createdTopic = manager.CreateTopic(eventTopicDescription);
Logger.LogInfo($"Created topic '{createdTopic.Path}'");
}
if (createSubscriptionIfNotExists && !manager.SubscriptionExists(eventTopicDescription.Path, subscriptionName))
{
SubscriptionDescription createdSubscription = manager.CreateSubscription
(
new SubscriptionDescription(eventTopicDescription.Path, subscriptionName)
{
DefaultMessageTimeToLive = new TimeSpan(0, 25, 0),
EnableBatchedOperations = true,
EnableDeadLetteringOnFilterEvaluationExceptions = true,
LockDuration = new TimeSpan(0, 5, 0)
}
);
Logger.LogInfo($"Created subscription '{createdSubscription.Name}' on topic '{createdSubscription.TopicPath}'");
}
#endif
}
#if NETSTANDARD2_0 || NET48_OR_GREATER
/// <summary>
/// First runs <see cref="AzureBus{TAuthenticationToken}.ValidateSettingsHaveChangedAsync"/> then checks
/// <see cref="PublicTopicName"/>, <see cref="PublicTopicSubscriptionName"/>,
/// <see cref="PrivateTopicName"/> or <see cref="PrivateTopicSubscriptionName"/> have changed.
/// </summary>
#else
/// <summary>
/// First runs <see cref="AzureBus{TAuthenticationToken}.ValidateSettingsHaveChanged"/> then checks
/// <see cref="PublicTopicName"/>, <see cref="PublicTopicSubscriptionName"/>,
/// <see cref="PrivateTopicName"/> or <see cref="PrivateTopicSubscriptionName"/> have changed.
/// </summary>
#endif
protected override
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task<bool> ValidateSettingsHaveChangedAsync
#else
bool ValidateSettingsHaveChanged
#endif
()
{
if (
#if NETSTANDARD2_0 || NET48_OR_GREATER
await base.ValidateSettingsHaveChangedAsync
#else
base.ValidateSettingsHaveChanged
#endif
())
return true;
return PublicTopicName != (ConfigurationManager.GetSetting(PublicTopicNameConfigurationKey) ?? DefaultPublicTopicName)
||
PublicTopicSubscriptionName != (ConfigurationManager.GetSetting(PublicTopicSubscriptionNameConfigurationKey) ?? DefaultPublicTopicSubscriptionName)
||
PrivateTopicName != (ConfigurationManager.GetSetting(PrivateTopicNameConfigurationKey) ?? DefaultPrivateTopicName)
||
PrivateTopicSubscriptionName != (ConfigurationManager.GetSetting(PrivateTopicSubscriptionNameConfigurationKey) ?? DefaultPrivateTopicSubscriptionName);
}
#if NETSTANDARD2_0 || NET48_OR_GREATER
/// <summary>
/// Triggers settings checking on both public and private publishers and receivers,
/// then calls <see cref="InstantiatePublishingAsync"/> if <see cref="PublicServiceBusPublisher"/> is not null.
/// </summary>
#else
/// <summary>
/// Triggers settings checking on both public and private publishers and receivers,
/// then calls <see cref="InstantiatePublishing"/> if <see cref="PublicServiceBusPublisher"/> is not null.
/// </summary>
#endif
protected override
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task TriggerSettingsCheckingAsync
#else
void TriggerSettingsChecking
#endif
()
{
// First refresh the EventBlackListProcessing property
bool throwExceptionOnReceiverMessageLockLostExceptionDuringComplete;
if (!ConfigurationManager.TryGetSetting(ThrowExceptionOnReceiverMessageLockLostExceptionDuringCompleteConfigurationKey, out throwExceptionOnReceiverMessageLockLostExceptionDuringComplete))
throwExceptionOnReceiverMessageLockLostExceptionDuringComplete = true;
ThrowExceptionOnReceiverMessageLockLostExceptionDuringComplete = throwExceptionOnReceiverMessageLockLostExceptionDuringComplete;
#if NETSTANDARD2_0 || NET48_OR_GREATER
await TriggerSettingsCheckingAsync(PrivateServiceBusPublisher, PrivateServiceBusReceivers);
await TriggerSettingsCheckingAsync(PublicServiceBusPublisher, PublicServiceBusReceivers);
#else
TriggerSettingsChecking(PrivateServiceBusPublisher, PrivateServiceBusReceivers);
TriggerSettingsChecking(PublicServiceBusPublisher, PublicServiceBusReceivers);
#endif
// Restart configuration, we order this intentionally with the publisher second as if this triggers the cancellation there's nothing else to process here
// we also only need to check one of the publishers
if (PublicServiceBusPublisher != null)
{
Logger.LogDebug("Recursively calling into InstantiatePublishing.");
#if NETSTANDARD2_0 || NET48_OR_GREATER
await InstantiatePublishingAsync
#else
InstantiatePublishing
#endif
();
}
}
#if NETSTANDARD2_0 || NET48_OR_GREATER
/// <summary>
/// Triggers settings checking on the provided <paramref name="serviceBusPublisher"/> and <paramref name="serviceBusReceivers"/>,
/// then calls <see cref="InstantiateReceivingAsync()"/>.
/// </summary>
#else
/// <summary>
/// Triggers settings checking on the provided <paramref name="serviceBusPublisher"/> and <paramref name="serviceBusReceivers"/>,
/// then calls <see cref="InstantiateReceiving()"/>.
/// </summary>
#endif
protected virtual
#if NETSTANDARD2_0 || NET48_OR_GREATER
async Task TriggerSettingsCheckingAsync
#else
void TriggerSettingsChecking
#endif
(TopicClient serviceBusPublisher, IDictionary<int, IMessageReceiver> serviceBusReceivers)
{
// Let's wrap up using this message bus and start the switch
if (serviceBusPublisher != null)
{
#if NETSTANDARD2_0 || NET48_OR_GREATER
await serviceBusPublisher.CloseAsync();
#else
serviceBusPublisher.Close();
#endif
Logger.LogDebug("Publishing service bus closed.");
}
foreach (IMessageReceiver serviceBusReceiver in serviceBusReceivers.Values)
{
// Let's wrap up using this message bus and start the switch
if (serviceBusReceiver != null)
{
#if NETSTANDARD2_0 || NET48_OR_GREATER
await serviceBusReceiver.CloseAsync();
await serviceBusReceiver.DisposeAsync();
#else
serviceBusReceiver.Close();
#endif
Logger.LogDebug("Receiving service bus closed.");
}
// Restart configuration, we order this intentionally with the receiver first as if this triggers the cancellation we know this isn't a publisher as well
if (serviceBusReceiver != null)
{
Logger.LogDebug("Recursively calling into InstantiateReceiving.");
#if NETSTANDARD2_0 || NET48_OR_GREATER
await InstantiateReceivingAsync();
#else
InstantiateReceiving();
#endif
// This will be the case of a connection setting change re-connection
if (ReceiverMessageHandler != null && ReceiverMessageHandlerOptions != null)
{
// Callback to handle received messages
Logger.LogDebug("Re-registering onMessage handler.");
ApplyReceiverMessageHandler();
}
else
Logger.LogWarning("No onMessage handler was found to re-bind.");
}
}
}
/// <summary>
/// Registers the provided <paramref name="receiverMessageHandler"/> with the provided <paramref name="receiverMessageHandlerOptions"/>.
/// </summary>
#if NETSTANDARD2_0 || NET48_OR_GREATER
protected async virtual Task RegisterReceiverMessageHandlerAsync(Func<ProcessMessageEventArgs, Task> receiverMessageHandler, ServiceBusProcessorOptions receiverMessageHandlerOptions)
#else
protected virtual void RegisterReceiverMessageHandler(Action<IMessageReceiver, BrokeredMessage> receiverMessageHandler, OnMessageOptions receiverMessageHandlerOptions)
#endif
{
#if NETSTANDARD2_0 || NET48_OR_GREATER
await StoreReceiverMessageHandlerAsync
#else
StoreReceiverMessageHandler
#endif
(receiverMessageHandler, receiverMessageHandlerOptions);
ApplyReceiverMessageHandler();
#if NETSTANDARD2_0 || NET48_OR_GREATER
await Task.CompletedTask;
#endif
}
/// <summary>
/// Stores the provided <paramref name="receiverMessageHandler"/> and <paramref name="receiverMessageHandlerOptions"/>.
/// </summary>
#if NETSTANDARD2_0 || NET48_OR_GREATER
protected virtual async Task StoreReceiverMessageHandlerAsync(Func<ProcessMessageEventArgs, Task> receiverMessageHandler, ServiceBusProcessorOptions receiverMessageHandlerOptions)
#else
protected virtual void StoreReceiverMessageHandler(Action<IMessageReceiver, BrokeredMessage> receiverMessageHandler, OnMessageOptions receiverMessageHandlerOptions)
#endif
{
ReceiverMessageHandler = receiverMessageHandler;
ReceiverMessageHandlerOptions = receiverMessageHandlerOptions;
#if NETSTANDARD2_0 || NET48_OR_GREATER
await Task.CompletedTask;
#endif
}
/// <summary>
/// Applies the stored ReceiverMessageHandler and ReceiverMessageHandlerOptions to all receivers in
/// <see cref="PrivateServiceBusReceivers"/> and <see cref="PublicServiceBusReceivers"/>.
/// </summary>
protected override void ApplyReceiverMessageHandler()
{
foreach (IMessageReceiver serviceBusReceiver in PrivateServiceBusReceivers.Values)
{
#if NETSTANDARD2_0 || NET48_OR_GREATER
serviceBusReceiver.ProcessMessageAsync += async args =>
{
BusHelper.SetWasPrivateBusUsed(true);
await ReceiverMessageHandler(args);