/
EventProcessor.cs
2500 lines (2165 loc) · 148 KB
/
EventProcessor.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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Diagnostics;
using Azure.Core.Pipeline;
using Azure.Core.Shared;
using Azure.Messaging.EventHubs.Consumer;
using Azure.Messaging.EventHubs.Core;
using Azure.Messaging.EventHubs.Diagnostics;
using Azure.Messaging.EventHubs.Processor;
namespace Azure.Messaging.EventHubs.Primitives
{
/// <summary>
/// Provides a base for creating a custom processor which consumes events across all partitions of a given Event Hub
/// for a specific consumer group. The processor is capable of collaborating with other instances for the same Event
/// Hub and consumer group pairing to share work by using a common storage platform to communicate. Fault tolerance
/// is also built-in, allowing the processor to be resilient in the face of errors.
/// </summary>
///
/// <typeparam name="TPartition">The context of the partition for which an operation is being performed.</typeparam>
///
/// <remarks>
/// To enable coordination for sharing of partitions between <see cref="EventProcessor{TPartition}"/> instances, they will assert exclusive read access to partitions
/// for the consumer group. No other readers should be active in the consumer group other than processors intending to collaborate. Non-exclusive readers will
/// be denied access; exclusive readers, including processors using a different storage locations, will interfere with the processor's operation and performance.
///
/// The <see cref="EventProcessor{TPartition}" /> is safe to cache and use for the lifetime of an application, which is the recommended approach.
/// The processor is responsible for ensuring efficient network, CPU, and memory use. Calling either <see cref="StopProcessingAsync" /> or <see cref="StopProcessing" />
/// when all processing is complete or as the application is shutting down will ensure that network resources and other unmanaged objects are properly cleaned up.
/// </remarks>
///
/// <seealso href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/eventhub/Azure.Messaging.EventHubs/samples">Event Hubs samples and discussion</seealso>
/// <seealso href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/eventhub/Azure.Messaging.EventHubs.Processor/samples">Event Hubs event processor samples and discussion</seealso>
///
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public abstract class EventProcessor<TPartition> where TPartition : EventProcessorPartition, new()
{
/// <summary>The maximum number of failed consumers to allow when processing a partition; failed consumers are those which have been unable to receive and process events.</summary>
private const int MaximumFailedConsumerCount = 1;
/// <summary>Indicates whether or not the consumer should consider itself invalid when a partition is stolen by another consumer, as determined by the Event Hubs service.</summary>
private const bool InvalidateConsumerWhenPartitionIsStolen = true;
/// <summary>The minimum duration to allow for a delay between load balancing cycles.</summary>
private static readonly TimeSpan MinimumLoadBalancingDelay = TimeSpan.FromMilliseconds(15);
/// <summary>Defines the warning threshold for the upper limit percentage of total ownership interval spent on load balancing.</summary>
private static readonly double LoadBalancingDurationWarnThreshold = 0.70;
/// <summary>The primitive for synchronizing access when starting and stopping the processor.</summary>
private readonly SemaphoreSlim ProcessorRunningGuard = new SemaphoreSlim(1, 1);
/// <summary>The maximum number of seconds that a load balancing cycle can take before a warning is issued; this value is based on the <see cref="Options" /> for processor.</summary>
private readonly double LoadBalancingCycleMaximumExecutionSeconds;
/// <summary>The maximum number of advised partitions that this processor should own; if more are owned, a warning is issued; this value is based on the host environment.</summary>
private readonly int MaximumAdvisedOwnedPartitions;
/// <summary>Indicates whether or not this event processor is currently running. Used only for mocking purposes.</summary>
private bool? _isRunningOverride;
/// <summary>Indicates the current state of the processor; used for mocking and manual status updates.</summary>
private EventProcessorStatus? _statusOverride;
/// <summary>The task responsible for managing the operations of the processor when it is running.</summary>
private Task _runningProcessorTask;
/// <summary>A <see cref="CancellationTokenSource" /> instance to signal the request to cancel the current running task.</summary>
private CancellationTokenSource _runningProcessorCancellationSource;
/// <summary>
/// The fully qualified Event Hubs namespace that the processor is associated with. This is likely
/// to be similar to <c>{yournamespace}.servicebus.windows.net</c>.
/// </summary>
///
public string FullyQualifiedNamespace { get; }
/// <summary>
/// The name of the Event Hub that the processor is connected to, specific to the
/// Event Hubs namespace that contains it.
/// </summary>
///
public string EventHubName { get; }
/// <summary>
/// The name of the consumer group this event processor is associated with. Events will be
/// read only in the context of this group.
/// </summary>
///
public string ConsumerGroup { get; }
/// <summary>
/// A unique name used to identify this event processor.
/// </summary>
///
/// <remarks>
/// The identifier can be set using the <see cref="EventProcessorOptions.Identifier"/> property on the
/// <see cref="EventProcessorOptions"/> passed when constructing the processor. If not specified, a
/// random identifier will be generated.
///
/// It is recommended that you set a stable unique identifier for processor instances, as this allows
/// the processor to recover partition ownership when an application or host instance is restarted. It
/// also aids readability in Azure SDK logs and allows for more easily correlating logs to a specific
/// processor instance.
/// </remarks>
///
public string Identifier { get; }
/// <summary>
/// Indicates whether or not this event processor is currently running.
/// </summary>
///
public bool IsRunning
{
get
{
var running = _isRunningOverride;
if (running.HasValue)
{
return running.Value;
}
var status = Status;
return ((status == EventProcessorStatus.Running) || (status == EventProcessorStatus.Stopping));
}
protected set => _isRunningOverride = value;
}
/// <summary>
/// Indicates the current state of the processor.
/// </summary>
///
internal EventProcessorStatus Status
{
get
{
EventProcessorStatus? statusOverride;
// If there is no active processor task, ensure that it is not
// in the process of starting by attempting to acquire the semaphore.
//
// If the semaphore could not be acquired, then there is an active start/stop
// operation in progress indicating that the processor is not yet running or
// will not be running.
if (_runningProcessorTask == null)
{
if (!ProcessorRunningGuard.Wait(100))
{
return (_statusOverride ?? EventProcessorStatus.NotRunning);
}
// If we reach this point, the semaphore was acquired and should
// be released.
statusOverride = _statusOverride;
ProcessorRunningGuard.Release();
}
else
{
statusOverride = _statusOverride;
}
if (statusOverride.HasValue)
{
return statusOverride.Value;
}
if ((_runningProcessorTask?.IsFaulted) ?? (false))
{
return EventProcessorStatus.Faulted;
}
if ((!_runningProcessorTask?.IsCompleted) ?? (false))
{
return EventProcessorStatus.Running;
}
return EventProcessorStatus.NotRunning;
}
}
/// <summary>
/// The instance of <see cref="EventHubsEventSource" /> which can be mocked for testing.
/// </summary>
///
internal EventHubsEventSource Logger { get; set; } = EventHubsEventSource.Log;
/// <summary>
/// The active policy which governs retry attempts for the processor.
/// </summary>
///
protected EventHubsRetryPolicy RetryPolicy { get; }
/// <summary>
/// Indicates whether or not this event processor should instrument batch event processing calls with distributed tracing.
/// Implementations that instrument event processing themselves should set this to <c>false</c>.
/// </summary>
///
protected bool EnableBatchTracing { get; set; } = true;
/// <summary>
/// The set of currently active partition processing tasks issued by this event processor and their associated
/// token sources that can be used to cancel the operation. Partition identifiers are used as keys.
/// </summary>
///
private ConcurrentDictionary<string, PartitionProcessor> ActivePartitionProcessors { get; } = new ConcurrentDictionary<string, PartitionProcessor>();
/// <summary>
/// A factory used to create new <see cref="EventHubConnection" /> instances.
/// </summary>
///
private Func<EventHubConnection> ConnectionFactory { get; }
/// <summary>
/// Responsible for ownership claim for load balancing.
/// </summary>
///
private PartitionLoadBalancer LoadBalancer { get; }
/// <summary>
/// The set of options to use with the <see cref="EventProcessor{TPartition}" /> instance.
/// </summary>
///
private EventProcessorOptions Options { get; }
/// <summary>
/// The desired number of events to include in a batch to be processed. This size is the maximum count in a batch.
/// </summary>
///
private int EventBatchMaximumCount { get; }
/// <summary>
/// The client diagnostics for this processor.
/// </summary>
///
private MessagingClientDiagnostics ClientDiagnostics { get; }
/// <summary>
/// Initializes a new instance of the <see cref="EventProcessor{TPartition}"/> class.
/// </summary>
///
/// <param name="eventBatchMaximumCount">The desired number of events to include in a batch to be processed. This size is the maximum count in a batch; the actual count may be smaller, depending on whether events are available in the Event Hub.</param>
/// <param name="consumerGroup">The name of the consumer group this processor is associated with. The processor will assert exclusive read access to partitions for this group.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub to associate the processor with.</param>
/// <param name="credential">The Azure managed identity credential to use for authorization. Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
/// <param name="options">The set of options to use for the processor.</param>
/// <param name="loadBalancer">The load balancer to use for coordinating processing with other event processor instances. If <c>null</c>, the standard load balancer will be created.</param>
///
/// <exception cref="ArgumentOutOfRangeException">Occurs when the requested <paramref name="eventBatchMaximumCount"/> is less than 1.</exception>
///
internal EventProcessor(int eventBatchMaximumCount,
string consumerGroup,
string fullyQualifiedNamespace,
string eventHubName,
TokenCredential credential,
EventProcessorOptions options = default,
PartitionLoadBalancer loadBalancer = default) : this(eventBatchMaximumCount, consumerGroup, fullyQualifiedNamespace, eventHubName, (object)credential, options, loadBalancer)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventProcessor{TPartition}"/> class.
/// </summary>
///
/// <param name="eventBatchMaximumCount">The desired number of events to include in a batch to be processed. This size is the maximum count in a batch; the actual count may be smaller, depending on whether events are available in the Event Hub.</param>
/// <param name="consumerGroup">The name of the consumer group this processor is associated with. The processor will assert exclusive read access to partitions for this group.</param>
/// <param name="connectionString">The connection string to use for connecting to the Event Hubs namespace; it is expected that the Event Hub name and the shared key properties are contained in this connection string.</param>
/// <param name="options">The set of options to use for the processor.</param>
///
/// <remarks>
/// If the connection string is copied from the Event Hubs namespace, it will likely not contain the name of the desired Event Hub,
/// which is needed. In this case, the name can be added manually by adding ";EntityPath=[[ EVENT HUB NAME ]]" to the end of the
/// connection string. For example, ";EntityPath=telemetry-hub".
///
/// If you have defined a shared access policy directly on the Event Hub itself, then copying the connection string from that
/// Event Hub will result in a connection string that contains the name.
/// </remarks>
///
/// <exception cref="ArgumentOutOfRangeException">Occurs when the requested <paramref name="eventBatchMaximumCount"/> is less than 1.</exception>
///
/// <seealso href="https://docs.microsoft.com/azure/event-hubs/event-hubs-get-connection-string">How to get an Event Hubs connection string</seealso>
///
protected EventProcessor(int eventBatchMaximumCount,
string consumerGroup,
string connectionString,
EventProcessorOptions options = default) : this(eventBatchMaximumCount, consumerGroup, connectionString, null, options)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventProcessor{TPartition}"/> class.
/// </summary>
///
/// <param name="eventBatchMaximumCount">The desired number of events to include in a batch to be processed. This size is the maximum count in a batch; the actual count may be smaller, depending on whether events are available in the Event Hub.</param>
/// <param name="consumerGroup">The name of the consumer group this processor is associated with. The processor will assert exclusive read access to partitions for this group.</param>
/// <param name="connectionString">The connection string to use for connecting to the Event Hubs namespace; it is expected that the shared key properties are contained in this connection string, but not the Event Hub name.</param>
/// <param name="eventHubName">The name of the specific Event Hub to associate the processor with.</param>
/// <param name="options">The set of options to use for the processor.</param>
///
/// <remarks>
/// If the connection string is copied from the Event Hub itself, it will contain the name of the desired Event Hub,
/// and can be used directly without passing the <paramref name="eventHubName" />. The name of the Event Hub should be
/// passed only once, either as part of the connection string or separately.
/// </remarks>
///
/// <exception cref="ArgumentOutOfRangeException">Occurs when the requested <paramref name="eventBatchMaximumCount"/> is less than 1.</exception>
///
/// <seealso href="https://docs.microsoft.com/azure/event-hubs/event-hubs-get-connection-string">How to get an Event Hubs connection string</seealso>
///
protected EventProcessor(int eventBatchMaximumCount,
string consumerGroup,
string connectionString,
string eventHubName,
EventProcessorOptions options = default)
{
Argument.AssertInRange(eventBatchMaximumCount, 1, int.MaxValue, nameof(eventBatchMaximumCount));
Argument.AssertNotNullOrEmpty(consumerGroup, nameof(consumerGroup));
Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));
options = options?.Clone() ?? new EventProcessorOptions();
var connectionStringProperties = EventHubsConnectionStringProperties.Parse(connectionString);
connectionStringProperties.Validate(eventHubName, nameof(connectionString));
FullyQualifiedNamespace = connectionStringProperties.Endpoint.Host;
EventHubName = string.IsNullOrEmpty(eventHubName) ? connectionStringProperties.EventHubName : eventHubName;
ConsumerGroup = consumerGroup;
Identifier = string.IsNullOrEmpty(options.Identifier) ? Guid.NewGuid().ToString() : options.Identifier;
RetryPolicy = options.RetryOptions.ToRetryPolicy();
Options = options;
EventBatchMaximumCount = eventBatchMaximumCount;
LoadBalancingCycleMaximumExecutionSeconds = (options.PartitionOwnershipExpirationInterval.TotalSeconds * LoadBalancingDurationWarnThreshold);
MaximumAdvisedOwnedPartitions = CalculateMaximumAdvisedOwnedPartitions();
ConnectionFactory = () => new EventHubConnection(connectionString, eventHubName, options.ConnectionOptions);
LoadBalancer = new PartitionLoadBalancer(CreateCheckpointStore(this), Identifier, ConsumerGroup, FullyQualifiedNamespace, EventHubName, options.PartitionOwnershipExpirationInterval, options.LoadBalancingUpdateInterval);
ClientDiagnostics = new MessagingClientDiagnostics(
DiagnosticProperty.DiagnosticNamespace,
DiagnosticProperty.ResourceProviderNamespace,
DiagnosticProperty.EventHubsServiceContext,
FullyQualifiedNamespace,
EventHubName);
}
/// <summary>
/// Initializes a new instance of the <see cref="EventProcessor{TPartition}"/> class.
/// </summary>
///
/// <param name="eventBatchMaximumCount">The desired number of events to include in a batch to be processed. This size is the maximum count in a batch; the actual count may be smaller, depending on whether events are available in the Event Hub.</param>
/// <param name="consumerGroup">The name of the consumer group this processor is associated with. The processor will assert exclusive read access to partitions for this group.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub to associate the processor with.</param>
/// <param name="credential">The shared access key credential to use for authorization. Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
/// <param name="options">The set of options to use for the processor.</param>
///
/// <exception cref="ArgumentOutOfRangeException">Occurs when the requested <paramref name="eventBatchMaximumCount"/> is less than 1.</exception>
///
protected EventProcessor(int eventBatchMaximumCount,
string consumerGroup,
string fullyQualifiedNamespace,
string eventHubName,
AzureNamedKeyCredential credential,
EventProcessorOptions options = default) : this(eventBatchMaximumCount, consumerGroup, fullyQualifiedNamespace, eventHubName, (object)credential, options, default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventProcessor{TPartition}"/> class.
/// </summary>
///
/// <param name="eventBatchMaximumCount">The desired number of events to include in a batch to be processed. This size is the maximum count in a batch; the actual count may be smaller, depending on whether events are available in the Event Hub.</param>
/// <param name="consumerGroup">The name of the consumer group this processor is associated with. The processor will assert exclusive read access to partitions for this group.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub to associate the processor with.</param>
/// <param name="credential">The shared signature credential to use for authorization. Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
/// <param name="options">The set of options to use for the processor.</param>
///
/// <exception cref="ArgumentOutOfRangeException">Occurs when the requested <paramref name="eventBatchMaximumCount"/> is less than 1.</exception>
///
protected EventProcessor(int eventBatchMaximumCount,
string consumerGroup,
string fullyQualifiedNamespace,
string eventHubName,
AzureSasCredential credential,
EventProcessorOptions options = default) : this(eventBatchMaximumCount, consumerGroup, fullyQualifiedNamespace, eventHubName, (object)credential, options, default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventProcessor{TPartition}"/> class.
/// </summary>
///
/// <param name="eventBatchMaximumCount">The desired number of events to include in a batch to be processed. This size is the maximum count in a batch; the actual count may be smaller, depending on whether events are available in the Event Hub.</param>
/// <param name="consumerGroup">The name of the consumer group this processor is associated with. The processor will assert exclusive read access to partitions for this group.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub to associate the processor with.</param>
/// <param name="credential">The Azure managed identity credential to use for authorization. Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
/// <param name="options">The set of options to use for the processor.</param>
///
/// <exception cref="ArgumentOutOfRangeException">Occurs when the requested <paramref name="eventBatchMaximumCount"/> is less than 1.</exception>
///
protected EventProcessor(int eventBatchMaximumCount,
string consumerGroup,
string fullyQualifiedNamespace,
string eventHubName,
TokenCredential credential,
EventProcessorOptions options = default) : this(eventBatchMaximumCount, consumerGroup, fullyQualifiedNamespace, eventHubName, (object)credential, options, default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventProcessor{TPartition}"/> class.
/// </summary>
///
protected EventProcessor()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventProcessor{TPartition}"/> class.
/// </summary>
///
/// <param name="eventBatchMaximumCount">The desired number of events to include in a batch to be processed. This size is the maximum count in a batch; the actual count may be smaller, depending on whether events are available in the Event Hub.</param>
/// <param name="consumerGroup">The name of the consumer group this processor is associated with. The processor will assert exclusive read access to partitions for this group.</param>
/// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
/// <param name="eventHubName">The name of the specific Event Hub to associate the processor with.</param>
/// <param name="credential">The credential to use for authorization. This may be of any type supported by the protected constructors.</param>
/// <param name="options">The set of options to use for the processor.</param>
/// <param name="loadBalancer">The load balancer to use for coordinating processing with other event processor instances. If <c>null</c>, the standard load balancer will be created.</param>
///
/// <exception cref="ArgumentOutOfRangeException">Occurs when the requested <paramref name="eventBatchMaximumCount"/> is less than 1.</exception>
///
private EventProcessor(int eventBatchMaximumCount,
string consumerGroup,
string fullyQualifiedNamespace,
string eventHubName,
object credential,
EventProcessorOptions options = default,
PartitionLoadBalancer loadBalancer = default)
{
Argument.AssertInRange(eventBatchMaximumCount, 1, int.MaxValue, nameof(eventBatchMaximumCount));
Argument.AssertNotNullOrEmpty(consumerGroup, nameof(consumerGroup));
Argument.AssertNotNullOrEmpty(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
Argument.AssertNotNull(credential, nameof(credential));
options = options?.Clone() ?? new EventProcessorOptions();
if (Uri.TryCreate(fullyQualifiedNamespace, UriKind.Absolute, out var uri))
{
fullyQualifiedNamespace = uri.Host;
}
Argument.AssertWellFormedEventHubsNamespace(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
FullyQualifiedNamespace = fullyQualifiedNamespace;
EventHubName = eventHubName;
ConsumerGroup = consumerGroup;
Identifier = string.IsNullOrEmpty(options.Identifier) ? Guid.NewGuid().ToString() : options.Identifier;
RetryPolicy = options.RetryOptions.ToRetryPolicy();
Options = options;
EventBatchMaximumCount = eventBatchMaximumCount;
LoadBalancingCycleMaximumExecutionSeconds = (options.PartitionOwnershipExpirationInterval.TotalSeconds * LoadBalancingDurationWarnThreshold);
MaximumAdvisedOwnedPartitions = CalculateMaximumAdvisedOwnedPartitions();
ConnectionFactory = () => EventHubConnection.CreateWithCredential(fullyQualifiedNamespace, eventHubName, credential, options.ConnectionOptions);
LoadBalancer = loadBalancer ?? new PartitionLoadBalancer(CreateCheckpointStore(this), Identifier, ConsumerGroup, FullyQualifiedNamespace, EventHubName, Options.PartitionOwnershipExpirationInterval, Options.LoadBalancingUpdateInterval);
ClientDiagnostics = new MessagingClientDiagnostics(
DiagnosticProperty.DiagnosticNamespace,
DiagnosticProperty.ResourceProviderNamespace,
DiagnosticProperty.EventHubsServiceContext,
FullyQualifiedNamespace,
EventHubName);
}
/// <summary>
/// Signals the <see cref="EventProcessor{TPartition}" /> to begin processing events. Should this method be called while the processor
/// is running, no action is taken.
/// </summary>
///
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the start operation. This won't affect the <see cref="EventProcessor{TPartition}" /> once it starts running.</param>
///
/// <exception cref="AggregateException">
/// As the processor starts, it will attempt to detect configuration and permissions errors that would prevent it from
/// being able to recover without intervention. For example, an incorrect connection string or the inability to query the
/// Event Hub would be detected. These exceptions will be packaged as an <see cref="AggregateException"/>, and will cause
/// <see cref="StartProcessingAsync" /> to fail.
/// </exception>
///
public virtual async Task StartProcessingAsync(CancellationToken cancellationToken = default) =>
await StartProcessingInternalAsync(true, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Signals the <see cref="EventProcessor{TPartition}" /> to begin processing events. Should this method be called while the processor
/// is running, no action is taken.
/// </summary>
///
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the start operation. This won't affect the <see cref="EventProcessor{TPartition}" /> once it starts running.</param>
///
/// <exception cref="AggregateException">
/// As the processor starts, it will attempt to detect configuration and permissions errors that would prevent it from
/// being able to recover without intervention. For example, an incorrect connection string or the inability to query the
/// Event Hub would be detected. These exceptions will be packaged as an <see cref="AggregateException"/>, and will cause
/// <see cref="StartProcessing" /> to fail.
/// </exception>
///
public virtual void StartProcessing(CancellationToken cancellationToken = default) =>
StartProcessingInternalAsync(false, cancellationToken).EnsureCompleted();
/// <summary>
/// Signals the <see cref="EventProcessor{TPartition}" /> to stop processing events. Should this method be called while the processor
/// is not running, no action is taken.
/// </summary>
///
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the stop operation. If the operation is successfully canceled, the <see cref="EventProcessor{TPartition}" /> will keep running.</param>
///
/// <remarks>
/// When stopping, the processor will update the ownership of partitions that it was responsible for processing and clean up network resources used for communication with
/// the Event Hubs service. As a result, this method will perform network I/O and may need to wait for partition reads that were active to complete.
///
/// <para>Due to service calls and network latency, an invocation of this method may take slightly longer than the specified <see cref="EventProcessorOptions.MaximumWaitTime" /> or
/// if the wait time was not configured, the duration of the <see cref="EventHubsRetryOptions.TryTimeout" /> of the configured retry policy.</para>
/// </remarks>
///
public virtual async Task StopProcessingAsync(CancellationToken cancellationToken = default) =>
await StopProcessingInternalAsync(true, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Signals the <see cref="EventProcessor{TPartition}" /> to stop processing events. Should this method be called while the processor
/// is not running, no action is taken.
/// </summary>
///
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the stop operation. If the operation is successfully canceled, the <see cref="EventProcessor{TPartition}" /> will keep running.</param>
///
/// <remarks>
/// When stopping, the processor will update the ownership of partitions that it was responsible for processing and clean up network resources used for communication with
/// the Event Hubs service. As a result, this method will perform network I/O and may need to wait for partition reads that were active to complete.
///
/// <para>Due to service calls and network latency, an invocation of this method may take slightly longer than the specified <see cref="EventProcessorOptions.MaximumWaitTime" /> or
/// if the wait time was not configured, the duration of the <see cref="EventHubsRetryOptions.TryTimeout" /> of the configured retry policy.</para>
/// </remarks>
///
public virtual void StopProcessing(CancellationToken cancellationToken = default) =>
StopProcessingInternalAsync(false, cancellationToken).EnsureCompleted();
/// <summary>
/// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
/// </summary>
///
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
///
/// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => base.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
///
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => base.GetHashCode();
/// <summary>
/// Converts the instance to string representation.
/// </summary>
///
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
///
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString() => $"Event Processor<{ typeof(TPartition).Name }>: { Identifier }";
/// <summary>
/// Creates an <see cref="TransportConsumer" /> to use for processing.
/// </summary>
///
/// <param name="consumerGroup">The consumer group to associate with the consumer.</param>
/// <param name="partitionId">The partition to associated with the consumer.</param>
/// <param name="consumerIdentifier">The identifier to associate with the consumer; if <c>null</c> or <see cref="string.Empty" />, a random identifier will be generated.</param>
/// <param name="eventPosition">The position in the event stream where the consumer should begin reading.</param>
/// <param name="connection">The connection to use for the consumer.</param>
/// <param name="options">The options to use for configuring the consumer.</param>
/// <param name="exclusive"><c>true</c> if this should be an exclusive consumer; otherwise, <c>false</c>.</param>
///
/// <returns>An <see cref="TransportConsumer" /> with the requested configuration.</returns>
///
internal virtual TransportConsumer CreateConsumer(string consumerGroup,
string partitionId,
string consumerIdentifier,
EventPosition eventPosition,
EventHubConnection connection,
EventProcessorOptions options,
bool exclusive) =>
connection.CreateTransportConsumer(
consumerGroup,
partitionId,
consumerIdentifier,
eventPosition,
options.RetryOptions.ToRetryPolicy(),
options.TrackLastEnqueuedEventProperties,
InvalidateConsumerWhenPartitionIsStolen,
prefetchCount: (uint?)options.PrefetchCount,
prefetchSizeInBytes: options.PrefetchSizeInBytes,
ownerLevel: exclusive ? 0 : null);
/// <summary>
/// Performs the tasks needed to process a batch of events.
/// </summary>
///
/// <param name="partition">The Event Hub partition whose processing should be started.</param>
/// <param name="eventBatch">The batch of events to process.</param>
/// <param name="dispatchEmptyBatches"><c>true</c> if empty batches should be dispatched to the handler; otherwise, <c>false</c>.</param>
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the processing.</param>
///
internal virtual async Task ProcessEventBatchAsync(TPartition partition,
IReadOnlyList<EventData> eventBatch,
bool dispatchEmptyBatches,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// If there were no events in the batch and empty batches should not be emitted,
// take no further action.
if ((eventBatch == null) || ((eventBatch.Count <= 0) && (!dispatchEmptyBatches)))
{
return;
}
// Create the diagnostics scope used for distributed tracing and instrument the events in the batch.
using var diagnosticScope = StartProcessorScope(eventBatch);
// Dispatch the batch to the handler for processing. Exceptions in the handler code are intended to be
// unhandled by the processor; explicitly signal that the exception was observed in developer-provided
// code.
var operation = Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture);
var watch = ValueStopwatch.StartNew();
try
{
var startingSequenceNumber = default(string);
var endingSequenceNumber = default(string);
if (eventBatch.Count > 0)
{
startingSequenceNumber = eventBatch[0].SequenceNumber.ToString();
endingSequenceNumber = eventBatch[eventBatch.Count - 1].SequenceNumber.ToString();
}
Logger.EventProcessorProcessingHandlerStart(partition.PartitionId, Identifier, EventHubName, ConsumerGroup, operation, eventBatch.Count, startingSequenceNumber, endingSequenceNumber);
await OnProcessingEventBatchAsync(eventBatch, partition, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.EventProcessorProcessingHandlerError(partition.PartitionId, Identifier, EventHubName, ConsumerGroup, operation, ex.Message);
diagnosticScope?.Failed(ex);
throw new DeveloperCodeException(ex);
}
finally
{
Logger.EventProcessorProcessingHandlerComplete(partition.PartitionId, Identifier, EventHubName, ConsumerGroup, operation, watch.GetElapsedTime().TotalSeconds, eventBatch.Count);
}
}
/// <summary>
/// Creates the infrastructure for tracking the processing of a partition and begins processing the
/// partition in the background until cancellation is requested.
/// </summary>
///
/// <param name="partition">The Event Hub partition whose processing should be started.</param>
/// <param name="cancellationSource">A <see cref="CancellationTokenSource"/> instance to signal the request to cancel the operation.</param>
/// <param name="startingPositionOverride">Allows for skipping partition initialization and directly overriding the position within the event stream where processing will begin.</param>
///
/// <returns>The <see cref="PartitionProcessor" /> encapsulating the processing task, its cancellation token, and associated state.</returns>
///
/// <remarks>
/// This method makes liberal use of class methods and state in addition to the received parameters.
/// </remarks>
///
internal virtual PartitionProcessor CreatePartitionProcessor(TPartition partition,
CancellationTokenSource cancellationSource,
EventPosition? startingPositionOverride = null)
{
cancellationSource.Token.ThrowIfCancellationRequested<TaskCanceledException>();
var consumer = default(TransportConsumer);
// If the tracking of the last enqueued event properties was requested, then read the
// properties from the active consumer, which can change during processing in the event of
// error scenarios.
LastEnqueuedEventProperties readLastEnqueuedEventProperties()
{
// This is not an expected scenario; the guard exists to prevent a race condition that is
// unlikely, but possible, when partition processing is being stopped or consumer creation
// outright failed.
if ((consumer == null) || (consumer.IsClosed))
{
Argument.AssertNotClosed(true, Resources.ClientNeededForThisInformationNotAvailable);
}
return new LastEnqueuedEventProperties(consumer.LastReceivedEvent);
}
// Define the routine to handle processing for the partition.
async Task performProcessing()
{
cancellationSource.Token.ThrowIfCancellationRequested<TaskCanceledException>();
var connection = default(EventHubConnection);
var retryDelay = default(TimeSpan?);
var capturedException = default(Exception);
var eventBatch = default(IReadOnlyList<EventData>);
var lastEvent = default(EventData);
var failedAttemptCount = 0;
var failedConsumerCount = 0;
// Determine the position to start processing from; this will occur during
// partition initialization normally, but may be superseded if an override
// was passed. In the event that initialization is run and encounters an
// exception, it takes responsibility for firing the error handler.
var (startingPosition, checkpoint) = startingPositionOverride switch
{
_ when startingPositionOverride.HasValue => (startingPositionOverride.Value, null),
_ => await InitializePartitionForProcessingAsync(partition, cancellationSource.Token).ConfigureAwait(false)
};
var checkpointUsed = (checkpoint != null);
var checkpointLastModified = checkpointUsed ? checkpoint.LastModified : null;
var checkpointAuthor = checkpointUsed ? checkpoint.ClientIdentifier : null;
Logger.EventProcessorPartitionProcessingEventPositionDetermined(partition.PartitionId, Identifier, EventHubName, ConsumerGroup, startingPosition.ToString(), checkpointUsed, checkpointLastModified, checkpointAuthor);
// Create the connection to be used for spawning consumers; if the creation
// fails, then consider the processing task to be failed. The main processing
// loop will take responsibility for attempting to restart or relinquishing ownership.
try
{
connection = CreateConnection();
}
catch (Exception ex)
{
// The error handler is invoked as a fire-and-forget task; the processor does not assume responsibility
// for observing or surfacing exceptions that may occur in the handler.
_ = InvokeOnProcessingErrorAsync(ex, partition, Resources.OperationReadEvents, CancellationToken.None);
Logger.EventProcessorPartitionProcessingError(partition.PartitionId, Identifier, EventHubName, ConsumerGroup, ex.Message);
throw;
}
await using var connectionAwaiter = connection.ConfigureAwait(false);
// Continue processing the partition until cancellation is signaled or until the count of failed consumers is too great.
// Consumers which been consistently unable to receive and process events will be considered invalid and abandoned for a new consumer.
while ((!cancellationSource.IsCancellationRequested) && (failedConsumerCount <= MaximumFailedConsumerCount))
{
try
{
consumer = CreateConsumer(ConsumerGroup, partition.PartitionId, $"P{ partition.PartitionId }-{ Identifier }", startingPosition, connection, Options, true);
// Register for notification when the cancellation token is triggered. Attempt to close the consumer
// in response to force-close the link and short-circuit any receive operation that is blocked and
// awaiting timeout.
using var cancellationRegistration = cancellationSource.Token.Register(static state =>
{
// Because this is a best-effort attempt and exceptions are expected and not relevant to
// callers, use a fire-and-forget approach rather than awaiting.
_ = ((TransportConsumer)state).CloseAsync(CancellationToken.None);
}, consumer, useSynchronizationContext: false);
// Allow the core dispatching loop to apply an additional set of retries over any provided by the consumer
// itself, as a processor should be as resilient as possible and retain partition ownership if processing is
// able to make forward progress. If the retries are exhausted or a non-retriable exception occurs, the
// consumer will be considered invalid and potentially refreshed.
while (!cancellationSource.IsCancellationRequested)
{
var stopWatch = ValueStopwatch.StartNew();
var cycleStartTime = Logger.GetLogFormattedUtcNow();
try
{
eventBatch = await consumer.ReceiveAsync(EventBatchMaximumCount, Options.MaximumWaitTime, cancellationSource.Token).ConfigureAwait(false);
await ProcessEventBatchAsync(partition, eventBatch, Options.MaximumWaitTime.HasValue, cancellationSource.Token).ConfigureAwait(false);
// If the batch was successfully processed, capture the last event as the current starting position, in the
// event that the consumer becomes invalid and needs to be replaced.
lastEvent = (eventBatch != null && eventBatch.Count > 0) ? eventBatch[eventBatch.Count - 1] : null;
if ((lastEvent != null) && (lastEvent.Offset != long.MinValue))
{
startingPosition = EventPosition.FromOffset(lastEvent.Offset, false);
}
// If event batches are successfully processed, then the need for forward progress is
// satisfied, and the failure counts should reset.
failedAttemptCount = 0;
failedConsumerCount = 0;
}
catch (TaskCanceledException) when (cancellationSource.IsCancellationRequested)
{
// Do not log; this is an expected scenario when partition processing is asked to stop.
throw;
}
catch (EventHubsException ex) when (ex.Reason == EventHubsException.FailureReason.ConsumerDisconnected)
{
// This is an expected scenario that may occur when ownership changes; log the exception for tracking but
// do not surface it to the error handler.
Logger.EventProcessorPartitionProcessingError(partition.PartitionId, Identifier, EventHubName, ConsumerGroup, ex.Message);
throw;
}
catch (Exception ex) when ((cancellationSource.IsCancellationRequested)
&& (((ex is EventHubsException ehEx) && (ehEx.Reason == EventHubsException.FailureReason.ClientClosed)) || (ex is ObjectDisposedException)))
{
// Do not log as an exception; this is an expected scenario when partition processing is asked to stop.
Logger.EventProcessorPartitionProcessingStopConsumerClose(partition.PartitionId, Identifier, EventHubName, ConsumerGroup);
throw new TaskCanceledException();
}
catch (Exception ex) when (ex.IsNotType<DeveloperCodeException>())
{
// The error handler is invoked as a fire-and-forget task; the processor does not assume responsibility
// for observing or surfacing exceptions that may occur in the handler.
_ = InvokeOnProcessingErrorAsync(ex, partition, Resources.OperationReadEvents, CancellationToken.None);
Logger.EventProcessorPartitionProcessingError(partition.PartitionId, Identifier, EventHubName, ConsumerGroup, ex.Message);
retryDelay = RetryPolicy.CalculateRetryDelay(ex, ++failedAttemptCount);
if (!retryDelay.HasValue)
{
// If the exception should not be retried, then allow it to pass to the outer loop; this is intended
// to prevent being stuck in a corrupt state where the consumer is unable to read events.
throw;
}
await Task.Delay(retryDelay.Value, cancellationSource.Token).ConfigureAwait(false);
}
// Capture the end-to-end cycle information for the partition. This is intended to provide an
// all-up view for partition processing, showing when and how long it took for a batch be read and
// processed.
var startingSequence = default(string);
var endingSequence = default(string);
if (eventBatch != null && eventBatch.Count > 0)
{
startingSequence = eventBatch[0].SequenceNumber.ToString();
endingSequence = eventBatch[eventBatch.Count - 1].SequenceNumber.ToString();
}
Logger.EventProcessorPartitionProcessingCycleComplete(partition.PartitionId, Identifier, EventHubName, ConsumerGroup, eventBatch?.Count ?? 0, startingSequence, endingSequence, cycleStartTime, Logger.GetLogFormattedUtcNow(), stopWatch.GetElapsedTime().TotalSeconds);
}
}
catch (TaskCanceledException)
{
throw;
}
catch (OperationCanceledException ex)
{
throw new TaskCanceledException(ex.Message, ex);
}
catch (DeveloperCodeException ex)
{
// If an exception leaked from developer-provided code, the processor lacks the proper level of context and
// insight to understand if it is safe to ignore and continue. Instead, this will be thrown and allowed to
// fault the partition processing task. To ensure visibility, log the error with an explicit call-out to identify
// it as originating in developer code.
var message = string.Format(CultureInfo.InvariantCulture, Resources.DeveloperCodeExceptionMessageMask, ex.InnerException.Message);
Logger.EventProcessorPartitionProcessingError(partition.PartitionId, Identifier, EventHubName, ConsumerGroup, message);
// Because this can be non-obvious to developers who are not capturing logs, also surface an exception to the error handler
// which offers guidance for error handling in developer code.
var handlerException = new EventHubsException(false, EventHubName, Resources.DeveloperCodeEventProcessingError, EventHubsException.FailureReason.GeneralError, ex.InnerException);
_ = InvokeOnProcessingErrorAsync(handlerException, partition, Resources.OperationEventProcessingDeveloperCode, CancellationToken.None);
// Discard the wrapper and propagate just the source exception from developer code.
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
}
catch (EventHubsException ex) when (ex.Reason == EventHubsException.FailureReason.ConsumerDisconnected)
{
// If the partition was stolen, the consumer should not be recreated as that would reassert ownership
// and potentially interfere with the new owner. Instead, the exception should be surfaced to fault
// the processor task and allow the next load balancing cycle to make the decision on whether processing
// should be restarted or the new owner acknowledged.
ReportPartitionStolen(partition.PartitionId);
throw;
}
catch (Exception ex) when (ex.IsFatalException())
{
throw;
}
catch (Exception ex)
{
++failedConsumerCount;
capturedException = ex;
}
finally
{
try
{
if (consumer != null)
{
await consumer.CloseAsync(CancellationToken.None).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Logger.EventProcessorPartitionProcessingError(partition.PartitionId, Identifier, EventHubName, ConsumerGroup, ex.Message);
// Do not bubble the exception, as the consumer is being refreshed; failure to close this consumer is non-fatal.
}
}
}
// If there was an exception captured, then surface it. Otherwise signal that cancellation took place.
if (capturedException != null)
{
ExceptionDispatchInfo.Capture(capturedException).Throw();
}
throw new TaskCanceledException();
}
// Start processing in the background and return the processor metadata. Since the task is
// expected to run continually until the processor is stopped or ownership changes, mark it as
// long-running. Other than the long-running designation, the options used intentionally match
// the recommended defaults used by Task.Run.
//
// For more context, see: https://devblogs.microsoft.com/pfxteam/task-run-vs-task-factory-startnew/
return new PartitionProcessor
(
Task.Factory.StartNew(performProcessing, cancellationSource.Token, TaskCreationOptions.LongRunning | TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Unwrap(),
partition,
readLastEnqueuedEventProperties,
cancellationSource
);
}
/// <summary>
/// Creates an <see cref="EventHubConnection" /> to use for communicating with the Event Hubs service.
/// </summary>
///
/// <returns>The requested <see cref="EventHubConnection" />.</returns>
///
protected internal virtual EventHubConnection CreateConnection() => ConnectionFactory();
/// <summary>
/// Performs the tasks needed to validate basic configuration and permissions of the dependencies needed for
/// the processor to function.
/// </summary>
///
/// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the validation.</param>
///
/// <exception cref="AggregateException">Any validation failures will result in an aggregate exception.</exception>
///
protected internal virtual async Task ValidateProcessingPreconditions(CancellationToken cancellationToken)
{
var validationTask = Task.WhenAll
(
ValidateEventHubsConnectionAsync(cancellationToken),