-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
EventHubBufferedProducerClient.cs
2542 lines (2194 loc) · 134 KB
/
EventHubBufferedProducerClient.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.CodeAnalysis;
using System.Globalization;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Diagnostics;
using Azure.Core.Pipeline;
using Azure.Core.Shared;
using Azure.Messaging.EventHubs.Amqp;
using Azure.Messaging.EventHubs.Core;
using Azure.Messaging.EventHubs.Diagnostics;
namespace Azure.Messaging.EventHubs.Producer
{
/// <summary>
/// A client responsible for publishing instances of <see cref="EventData"/> to a specific
/// Event Hub. Depending on the options specified when events are enqueued, they may be
/// automatically assigned to a partition, grouped according to the specified partition
/// key, or assigned a specifically requested partition.
///
/// The <see cref="EventHubBufferedProducerClient" /> does not publish immediately, instead using
/// a deferred model where events are collected into a buffer so that they may be efficiently batched
/// and published when the batch is full or the <see cref="EventHubBufferedProducerClientOptions.MaximumWaitTime" />
/// has elapsed with no new events enqueued.
///
/// This model is intended to shift the burden of batch management from callers, at the cost of non-deterministic
/// timing, for when events will be published. There are additional trade-offs to consider, as well:
/// <list type="bullet">
/// <item><description>If the application crashes, events in the buffer will not have been published. To prevent data loss, callers are encouraged to track publishing progress using the <see cref="SendEventBatchSucceededAsync" /> and <see cref="SendEventBatchFailedAsync" /> handlers.</description></item>
/// <item><description>Events specifying a partition key may be assigned a different partition than those using the same key with other producers.</description></item>
/// <item><description>In the unlikely event that a partition becomes temporarily unavailable, the <see cref="EventHubBufferedProducerClient" /> may take longer to recover than other producers.</description></item>
/// </list>
///
/// In scenarios where it is important to have events published immediately with a deterministic outcome, ensure
/// that partition keys are assigned to a partition consistent with other publishers, or where maximizing availability
/// is a requirement, using the <see cref="EventHubProducerClient" /> is recommended.
/// </summary>
///
/// <remarks>
/// The <see cref="EventHubBufferedProducerClient"/> is safe to cache and use as a singleton for the lifetime of an
/// application, which is the recommended approach. The producer is responsible for ensuring efficient network,
/// CPU, and memory use. Calling either <see cref="CloseAsync(bool, CancellationToken)"/> or <see cref="DisposeAsync"/>
/// when no more events will be enqueued or as the application is shutting down is required so that the buffer can be flushed
/// and resources cleaned up properly.
/// </remarks>
///
/// <seealso cref="EventHubProducerClient" />
/// <seealso href="https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/eventhub/Azure.Messaging.EventHubs/samples">Event Hubs samples and discussion</seealso>
///
[SuppressMessage("Usage", "AZC0007:DO provide a minimal constructor that takes only the parameters required to connect to the service.", Justification = "Event Hubs are AMQP-based services and don't use ClientOptions functionality")]
public class EventHubBufferedProducerClient : IAsyncDisposable
{
/// <summary>The maximum amount of time, in milliseconds, to allow for acquiring the semaphore guarding a partition's publishing eligibility.</summary>
private const int PartitionPublishingGuardAcquireLimitMilliseconds = 100;
/// <summary>The base interval to delay when publishing is throttled and an operation needs to back-off before retrying. Four seconds is recommended by the service.</summary>
private static readonly TimeSpan ThrottleBackoffInterval = TimeSpan.FromSeconds(4);
/// <summary>The minimum interval to allow for waiting when building a batch to publish.</summary>
private static readonly TimeSpan MinimumPublishingWaitInterval = TimeSpan.FromMilliseconds(5);
/// <summary>The default interval to delay for events to be available when building a batch to publish.</summary>
private static readonly TimeSpan PublishingDelayInterval = TimeSpan.FromMilliseconds(100);
/// <summary>The set of client options to use when options were not passed when the producer was instantiated.</summary>
private static readonly EventHubBufferedProducerClientOptions DefaultOptions = new();
/// <summary>The random number generator to use for a specific thread.</summary>
private static readonly ThreadLocal<Random> RandomNumberGenerator = new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref s_randomSeed)), false);
/// <summary>The seed to use for initializing random number generated for a given thread-specific instance.</summary>
private static int s_randomSeed = Environment.TickCount;
/// <summary>The set of currently active partition publishing tasks. Partition identifiers are used as keys.</summary>
private readonly ConcurrentDictionary<string, PartitionPublishingState> _activePartitionStateMap = new();
/// <summary>The set of options to use with the <see cref="EventHubBufferedProducerClient" /> instance.</summary>
private readonly EventHubBufferedProducerClientOptions _options;
/// <summary>The primitive for synchronizing access when class-wide state is changing.</summary>
[SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "The AvailableWaitHandle property is not accessed; resources requiring dispose will not have been allocated.")]
private readonly SemaphoreSlim _stateGuard = new SemaphoreSlim(1, 1);
/// <summary>The producer to use to send events to the Event Hub.</summary>
[SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "It is being disposed via delegation to CloseAsync.")]
private readonly EventHubProducerClient _producer;
/// <summary>A <see cref="CancellationTokenSource"/> instance to signal the request to cancel the background tasks responsible for publishing and management after any in-process batches are complete.</summary>
[SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "It is being disposed via delegation to StopPublishingAsync, which is called by CloseAsync.")]
private CancellationTokenSource _backgroundTasksCancellationSource;
/// <summary>A <see cref="CancellationTokenSource"/> instance to signal that any active publishing operations, including those in-flight, should terminate immediately.</summary>
private CancellationTokenSource _activeSendOperationsCancellationSource;
/// <summary>A completion source that be awaited when publishing would like to pause and wait for an event to be enqueued.</summary>
private TaskCompletionSource<bool> _eventEnqueuedCompletionSource;
/// <summary>The task responsible for managing the operations of the producer when it is running.</summary>
private Task _producerManagementTask;
/// <summary>The task responsible for publishing events.</summary>
private Task _publishingTask;
/// <summary>The set of partitions identifiers for the configured Event Hub, intended to be used for partition assignment.</summary>
private string[] _partitions;
/// <summary>A hash representing the set of partitions identifiers for the configured Event Hub, intended to be used for partition validation.</summary>
private HashSet<string> _partitionHash;
/// <summary>The count of total events that have been buffered across all partitions.</summary>
private int _totalBufferedEventCount;
/// <summary>The handler to be called once a batch has successfully published.</summary>
private Func<SendEventBatchSucceededEventArgs, Task> _sendSucceededHandler;
/// <summary>The handler to be called once a batch has failed to publish.</summary>
private Func<SendEventBatchFailedEventArgs, Task> _sendFailedHandler;
/// <summary>Indicates whether or not registration for handlers is locked; if so, no changes are permitted.</summary>
private volatile bool _areHandlersLocked;
/// <summary>Indicates whether or not this instance has been closed.</summary>
private volatile bool _isClosed;
/// <summary>The client diagnostics instance used to instrument events when enqueueing.</summary>
private readonly MessagingClientDiagnostics _clientDiagnostics;
/// <summary>
/// The fully qualified Event Hubs namespace that this producer is currently associated with, which will likely be similar
/// to <c>{yournamespace}.servicebus.windows.net</c>.
/// </summary>
///
public string FullyQualifiedNamespace => _producer.FullyQualifiedNamespace;
/// <summary>
/// The name of the Event Hub that this producer is connected to, specific to the Event Hubs namespace that contains it.
/// </summary>
///
public string EventHubName => _producer.EventHubName;
/// <summary>
/// A unique name to identify the buffered producer.
/// </summary>
///
public string Identifier => _producer.Identifier;
/// <summary>
/// Indicates whether or not this <see cref="EventHubBufferedProducerClient" /> is currently
/// active and publishing queued events.
/// </summary>
///
/// <value>
/// <c>true</c> if the client is publishing; otherwise, <c>false</c>.
/// </value>
///
/// <remarks>
/// The producer will begin publishing when an event is enqueued and should remain active until
/// either <see cref="CloseAsync" /> or <see cref="DisposeAsync" /> is called.
///
/// If any events were enqueued, <see cref="IsClosed" /> is <c>false</c>, and <see cref="IsPublishing" />
/// is <c>false</c>, this likely indicates an unrecoverable state for the client. It is recommended to
/// close the <see cref="EventHubBufferedProducerClient" /> and create a new instance.
///
/// In this state, exceptions will be reported by the Event Hubs client library logs, which can be captured
/// using the <see cref="Azure.Core.Diagnostics.AzureEventSourceListener" />.
/// </remarks>
///
/// <seealso href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/eventhub/Azure.Messaging.EventHubs/samples/Sample10_AzureEventSourceListener.md">Capturing Event Hubs logs</seealso>
///
public virtual bool IsPublishing => _producerManagementTask != null;
/// <summary>
/// Indicates whether or not this <see cref="EventHubBufferedProducerClient" /> has been closed.
/// </summary>
///
/// <value>
/// <c>true</c> if the client is closed; otherwise, <c>false</c>.
/// </value>
///
public virtual bool IsClosed
{
get => _isClosed;
internal set => _isClosed = value;
}
/// <summary>
/// The total number of events that are currently buffered and waiting to be published, across all partitions.
/// </summary>
///
public virtual int TotalBufferedEventCount => _totalBufferedEventCount;
/// <summary>
/// The instance of <see cref="EventHubsEventSource" /> which can be mocked for testing.
/// </summary>
///
/// <remarks>
/// This member is exposed internally to support testing only; it is not intended
/// for other use.
/// </remarks>
///
internal EventHubsEventSource Logger { get; set; } = EventHubsEventSource.Log;
/// <summary>
/// The resolver to use for assigning partitions for automatic routing and partition keys.
/// </summary>
///
/// <remarks>
/// This member is exposed internally to support testing only; it is not intended
/// for other use.
/// </remarks>
///
internal PartitionResolver PartitionResolver { get; set; } = new();
/// <summary>
/// The interval at which the background management operations should run.
/// </summary>
///
/// <remarks>
/// This member is exposed internally to support testing only; it is not intended
/// for other use.
/// </remarks>
///
internal TimeSpan BackgroundManagementInterval { get; set; } = TimeSpan.FromSeconds(10);
/// <summary>
/// The set of state for the partitions which are actively being published to. Partition identifiers are used as keys.
/// </summary>
///
/// <remarks>
/// This member is exposed internally to support testing only; it is not intended
/// for other use.
/// </remarks>
///
internal ConcurrentDictionary<string, PartitionPublishingState> ActivePartitionStateMap => _activePartitionStateMap;
/// <summary>
/// Invoked after each batch of events has been successfully published to the Event Hub, this handler is optional
/// and is intended to provide notifications for interested listeners. If this producer was configured with
/// <see cref="EventHubBufferedProducerClientOptions.MaximumConcurrentSends" /> or <see cref="EventHubBufferedProducerClientOptions.MaximumConcurrentSendsPerPartition" />
/// set greater than 1, the handler will be invoked concurrently.
///
/// This handler will be awaited after publishing the batch; the publishing operation will not be considered complete until the handler
/// call returns. It is advised that no long-running operations be performed in the handler to avoid negatively impacting throughput.
///
/// It is not recommended to invoke <see cref="CloseAsync" /> or <see cref="DisposeAsync" /> from this handler; doing so may result
/// in a deadlock scenario if those calls are awaited.
/// </summary>
///
/// <remarks>
/// It is not necessary to explicitly unregister this handler; it will be automatically unregistered when
/// <see cref="CloseAsync" /> or <see cref="DisposeAsync" /> is invoked.
/// </remarks>
///
/// <exception cref="ArgumentException">If an attempt is made to remove a handler that doesn't match the current handler registered.</exception>
/// <exception cref="NotSupportedException">If an attempt is made to add or remove a handler while the processor is running.</exception>
/// <exception cref="NotSupportedException">If an attempt is made to add a handler when one is currently registered.</exception>
///
[SuppressMessage("Usage", "AZC0003:DO make service methods virtual.", Justification = "This member follows the standard .NET event pattern; override via the associated On<<EVENT>> method.")]
public event Func<SendEventBatchSucceededEventArgs, Task> SendEventBatchSucceededAsync
{
add
{
Argument.AssertNotNull(value, nameof(SendEventBatchSucceededAsync));
if (_sendSucceededHandler != default)
{
throw new NotSupportedException(Resources.HandlerHasAlreadyBeenAssigned);
}
if (_areHandlersLocked)
{
throw new InvalidOperationException(Resources.CannotChangeHandlersWhenPublishing);
}
_sendSucceededHandler = value;
}
remove
{
Argument.AssertNotNull(value, nameof(SendEventBatchSucceededAsync));
if (_sendSucceededHandler != value)
{
throw new ArgumentException(Resources.HandlerHasNotBeenAssigned);
}
if (_areHandlersLocked)
{
throw new InvalidOperationException(Resources.CannotChangeHandlersWhenPublishing);
}
_sendSucceededHandler = default;
}
}
/// <summary>
/// Invoked for any batch of events that failed to be published to the Event Hub, this handler must be
/// provided before events may be enqueued. If this producer was not configured with <see cref="EventHubBufferedProducerClientOptions.MaximumConcurrentSends" />
/// and <see cref="EventHubBufferedProducerClientOptions.MaximumConcurrentSendsPerPartition" /> both set to 1, the handler will be invoked
/// concurrently.
///
/// It is safe to attempt resending the events by calling <see cref="EnqueueEventAsync(EventData, EnqueueEventOptions, CancellationToken)" /> or
/// <see cref="EnqueueEventsAsync(IEnumerable{EventData}, EnqueueEventOptions, CancellationToken)" /> from within this handler. It is important
/// to note that doing so will place them at the end of the buffer; the original order will not be maintained.
///
/// This handler will be awaited after failure to publish the batch; the publishing operation is not considered complete until the
/// handler call returns. It is advised that no long-running operations be performed in the handler to avoid negatively impacting throughput.
///
/// It is not recommended to invoke <see cref="CloseAsync" /> or <see cref="DisposeAsync" /> from this handler; doing so may result
/// in a deadlock scenario if those calls are awaited.
/// </summary>
///
/// <remarks>
/// Should a transient failure occur during publishing, this handler will not be invoked immediately; it is only
/// invoked after applying the retry policy and all eligible retries have been exhausted. Should publishing succeed
/// during a retry attempt, this handler is not invoked.
///
/// Since applications do not have deterministic control over failed batches, it is recommended that the application
/// set a generous number of retries and try timeout interval in the <see cref="EventHubProducerClientOptions.RetryOptions"/>.
/// Doing so will allow the <see cref="EventHubBufferedProducerClient" /> a higher chance to recover from transient failures. This is
/// especially important when ensuring the order of events is needed.
///
/// It is not necessary to explicitly unregister this handler; it will be automatically unregistered when
/// <see cref="CloseAsync" /> or <see cref="DisposeAsync" /> is invoked.
/// </remarks>
///
/// <exception cref="ArgumentException">If an attempt is made to remove a handler that doesn't match the current handler registered.</exception>
/// <exception cref="NotSupportedException">If an attempt is made to add or remove a handler while the processor is running.</exception>
/// <exception cref="NotSupportedException">If an attempt is made to add a handler when one is currently registered.</exception>
///
/// <seealso cref="EventHubsRetryOptions" />
///
[SuppressMessage("Usage", "AZC0003:DO make service methods virtual.", Justification = "This member follows the standard .NET event pattern; override via the associated On<<EVENT>> method.")]
public event Func<SendEventBatchFailedEventArgs, Task> SendEventBatchFailedAsync
{
add
{
Argument.AssertNotNull(value, nameof(SendEventBatchFailedAsync));
if (_sendFailedHandler != default)
{
throw new NotSupportedException(Resources.HandlerHasAlreadyBeenAssigned);
}
if (_areHandlersLocked)
{
throw new InvalidOperationException(Resources.CannotChangeHandlersWhenPublishing);
}
_sendFailedHandler = value;
}
remove
{
Argument.AssertNotNull(value, nameof(SendEventBatchFailedAsync));
if (_sendFailedHandler != value)
{
throw new ArgumentException(Resources.HandlerHasNotBeenAssigned);
}
if (_areHandlersLocked)
{
throw new InvalidOperationException(Resources.CannotChangeHandlersWhenPublishing);
}
_sendFailedHandler = default;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <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>
///
/// <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>
///
/// <seealso href="https://docs.microsoft.com/azure/event-hubs/event-hubs-get-connection-string">How to get an Event Hubs connection string</seealso>
///
public EventHubBufferedProducerClient(string connectionString) : this(connectionString, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <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="clientOptions">A set of <see cref="EventHubBufferedProducerClientOptions"/> to apply when configuring the buffered producer.</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>
///
/// <seealso href="https://docs.microsoft.com/azure/event-hubs/event-hubs-get-connection-string">How to get an Event Hubs connection string</seealso>
///
public EventHubBufferedProducerClient(string connectionString,
EventHubBufferedProducerClientOptions clientOptions) : this(connectionString, null, clientOptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <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="eventHubName">The name of the specific Event Hub to associate the producer with.</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>
///
/// <seealso href="https://docs.microsoft.com/azure/event-hubs/event-hubs-get-connection-string">How to get an Event Hubs connection string</seealso>
///
public EventHubBufferedProducerClient(string connectionString,
string eventHubName) : this(connectionString, eventHubName, default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <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="eventHubName">The name of the specific Event Hub to associate the producer with.</param>
/// <param name="clientOptions">A set of <see cref="EventHubBufferedProducerClientOptions"/> to apply when configuring the buffered producer.</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>
///
/// <seealso href="https://docs.microsoft.com/azure/event-hubs/event-hubs-get-connection-string">How to get an Event Hubs connection string</seealso>
///
public EventHubBufferedProducerClient(string connectionString,
string eventHubName,
EventHubBufferedProducerClientOptions clientOptions) : this(clientOptions)
{
Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));
_producer = new EventHubProducerClient(connectionString, eventHubName, (clientOptions ?? DefaultOptions).ToEventHubProducerClientOptions());
_clientDiagnostics = new MessagingClientDiagnostics(
DiagnosticProperty.DiagnosticNamespace,
DiagnosticProperty.ResourceProviderNamespace,
DiagnosticProperty.EventHubsServiceContext,
_producer.FullyQualifiedNamespace,
_producer.EventHubName);
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <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 producer 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="clientOptions">A set of <see cref="EventHubBufferedProducerClientOptions"/> to apply when configuring the producer.</param>
///
public EventHubBufferedProducerClient(string fullyQualifiedNamespace,
string eventHubName,
AzureNamedKeyCredential credential,
EventHubBufferedProducerClientOptions clientOptions = default) : this(fullyQualifiedNamespace, eventHubName, (object)credential, clientOptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <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 producer 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="clientOptions">A set of <see cref="EventHubBufferedProducerClientOptions"/> to apply when configuring the producer.</param>
///
public EventHubBufferedProducerClient(string fullyQualifiedNamespace,
string eventHubName,
AzureSasCredential credential,
EventHubBufferedProducerClientOptions clientOptions = default) : this(fullyQualifiedNamespace, eventHubName, (object)credential, clientOptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <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 producer 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="clientOptions">A set of <see cref="EventHubBufferedProducerClientOptions"/> to apply when configuring the producer.</param>
///
public EventHubBufferedProducerClient(string fullyQualifiedNamespace,
string eventHubName,
TokenCredential credential,
EventHubBufferedProducerClientOptions clientOptions = default) : this(fullyQualifiedNamespace, eventHubName, (object)credential, clientOptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <param name="connection">The <see cref="EventHubConnection" /> connection to use for communication with the Event Hubs service.</param>
/// <param name="clientOptions">A set of <see cref="EventHubBufferedProducerClientOptions"/> to apply when configuring the producer.</param>
///
public EventHubBufferedProducerClient(EventHubConnection connection,
EventHubBufferedProducerClientOptions clientOptions = default) : this(clientOptions)
{
_producer = new EventHubProducerClient(connection, (clientOptions ?? DefaultOptions).ToEventHubProducerClientOptions());
_clientDiagnostics = new MessagingClientDiagnostics(
DiagnosticProperty.DiagnosticNamespace,
DiagnosticProperty.ResourceProviderNamespace,
DiagnosticProperty.EventHubsServiceContext,
_producer.FullyQualifiedNamespace,
_producer.EventHubName);
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <param name="producer">The <see cref="EventHubProducerClient" /> to use for delegating Event Hubs service operations to.</param>
/// <param name="clientOptions">A set of <see cref="EventHubBufferedProducerClientOptions"/> to apply when configuring the producer.</param>
///
/// <remarks>
/// This constructor is intended to be used internally for functional
/// testing only.
/// </remarks>
///
internal EventHubBufferedProducerClient(EventHubProducerClient producer,
EventHubBufferedProducerClientOptions clientOptions = default) : this(clientOptions)
{
_producer = producer;
_clientDiagnostics = new MessagingClientDiagnostics(
DiagnosticProperty.DiagnosticNamespace,
DiagnosticProperty.ResourceProviderNamespace,
DiagnosticProperty.EventHubsServiceContext,
_producer.FullyQualifiedNamespace,
_producer.EventHubName);
}
/// <summary>
/// Used for mocking the producer for testing purposes.
/// </summary>
///
protected EventHubBufferedProducerClient()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <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 producer with.</param>
/// <param name="credential">The credential to use for authorization. This may be of type <see cref="TokenCredential" />, <see cref="AzureSasCredential" />, or <see cref="AzureNamedKeyCredential" />.</param>
/// <param name="clientOptions">A set of <see cref="EventHubBufferedProducerClientOptions"/> to apply when configuring the producer.</param>
///
private EventHubBufferedProducerClient(string fullyQualifiedNamespace,
string eventHubName,
object credential,
EventHubBufferedProducerClientOptions clientOptions = default) : this(clientOptions)
{
Argument.AssertNotNullOrEmpty(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
Argument.AssertNotNull(credential, nameof(credential));
var options = (clientOptions ?? DefaultOptions).ToEventHubProducerClientOptions();
if (Uri.TryCreate(fullyQualifiedNamespace, UriKind.Absolute, out var uri))
{
fullyQualifiedNamespace = uri.Host;
}
Argument.AssertWellFormedEventHubsNamespace(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
_producer = credential switch
{
TokenCredential tokenCred => new EventHubProducerClient(fullyQualifiedNamespace, eventHubName, tokenCred, options),
AzureSasCredential sasCred => new EventHubProducerClient(fullyQualifiedNamespace, eventHubName, sasCred, options),
AzureNamedKeyCredential keyCred => new EventHubProducerClient(fullyQualifiedNamespace, eventHubName, keyCred, options),
_ => throw new ArgumentException(Resources.UnsupportedCredential, nameof(credential))
};
_clientDiagnostics = new MessagingClientDiagnostics(
DiagnosticProperty.DiagnosticNamespace,
DiagnosticProperty.ResourceProviderNamespace,
DiagnosticProperty.EventHubsServiceContext,
_producer.FullyQualifiedNamespace,
_producer.EventHubName);
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubBufferedProducerClient" /> class.
/// </summary>
///
/// <param name="options">>A set of <see cref="EventHubBufferedProducerClientOptions"/> to apply when configuring the producer.</param>
///
private EventHubBufferedProducerClient(EventHubBufferedProducerClientOptions options)
{
_options = options?.Clone() ?? DefaultOptions;
}
/// <summary>
/// The number of events that are buffered and waiting to be published for a given partition.
/// </summary>
///
/// <param name="partitionId">The identifier of the partition.</param>
///
public virtual int GetBufferedEventCount(string partitionId)
{
Argument.AssertNotClosed(_isClosed, nameof(EventHubBufferedProducerClient));
Argument.AssertNotNullOrEmpty(partitionId, nameof(partitionId));
if (_activePartitionStateMap.TryGetValue(partitionId, out var publisher))
{
return publisher.BufferedEventCount;
}
return 0;
}
/// <summary>
/// Retrieves information about the Event Hub that the connection is associated with, including
/// the number of partitions present and their identifiers.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>The set of information for the Event Hub that this client is associated with.</returns>
///
public virtual async Task<EventHubProperties> GetEventHubPropertiesAsync(CancellationToken cancellationToken = default)
{
Argument.AssertNotClosed(_isClosed, nameof(EventHubBufferedProducerClient));
return await _producer.GetEventHubPropertiesAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves the set of identifiers for the partitions of an Event Hub.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>The set of identifiers for the partitions within the Event Hub that this client is associated with.</returns>
///
/// <remarks>
/// This method is synonymous with invoking <see cref="GetEventHubPropertiesAsync(CancellationToken)" /> and reading the <see cref="EventHubProperties.PartitionIds" />
/// property that is returned. It is offered as a convenience for quick access to the set of partition identifiers for the associated Event Hub.
/// No new or extended information is presented.
/// </remarks>
///
public virtual async Task<string[]> GetPartitionIdsAsync(CancellationToken cancellationToken = default)
{
Argument.AssertNotClosed(_isClosed, nameof(EventHubBufferedProducerClient));
return await _producer.GetPartitionIdsAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Retrieves information about a specific partition for an Event Hub, including elements that describe the available
/// events in the partition event stream.
/// </summary>
///
/// <param name="partitionId">The unique identifier of a partition associated with the Event Hub.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>The set of information for the requested partition under the Event Hub this client is associated with.</returns>
///
public virtual async Task<PartitionProperties> GetPartitionPropertiesAsync(string partitionId,
CancellationToken cancellationToken = default)
{
Argument.AssertNotClosed(_isClosed, nameof(EventHubBufferedProducerClient));
return await _producer.GetPartitionPropertiesAsync(partitionId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Enqueues an <see cref="EventData"/> into the buffer to be published to the Event Hub. If there is no capacity in
/// the buffer when this method is invoked, it will wait for space to become available and ensure that the <paramref name="eventData"/>
/// has been enqueued.
///
/// When this call returns, the <paramref name="eventData" /> has been accepted into the buffer, but it may not have been published yet.
/// Publishing will take place at a nondeterministic point in the future as the buffer is processed.
/// </summary>
///
/// <param name="eventData">The event to be enqueued into the buffer and, later, published.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>The total number of events that are currently buffered and waiting to be published, across all partitions.</returns>
///
/// <exception cref="InvalidOperationException">Occurs when no <see cref="SendEventBatchFailedAsync" /> handler is currently registered.</exception>
/// <exception cref="EventHubsException">Occurs when querying Event Hub metadata took longer than expected.</exception>
///
/// <remarks>
/// Upon the first attempt to enqueue an event, the <see cref="SendEventBatchSucceededAsync" /> and <see cref="SendEventBatchFailedAsync" /> handlers
/// can no longer be changed.
/// </remarks>
///
public virtual Task<int> EnqueueEventAsync(EventData eventData,
CancellationToken cancellationToken = default) => EnqueueEventAsync(eventData, default, cancellationToken);
/// <summary>
/// Enqueues an <see cref="EventData"/> into the buffer to be published to the Event Hub. If there is no capacity in
/// the buffer when this method is invoked, it will wait for space to become available and ensure that the <paramref name="eventData"/>
/// has been enqueued.
///
/// When this call returns, the <paramref name="eventData" /> has been accepted into the buffer, but it may not have been published yet.
/// Publishing will take place at a nondeterministic point in the future as the buffer is processed.
/// </summary>
///
/// <param name="eventData">The event to be enqueued into the buffer and, later, published.</param>
/// <param name="options">The set of options to apply when publishing this event.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>The total number of events that are currently buffered and waiting to be published, across all partitions.</returns>
///
/// <exception cref="InvalidOperationException">Occurs when no <see cref="SendEventBatchFailedAsync" /> handler is currently registered.</exception>
/// <exception cref="InvalidOperationException">Occurs when both a partition identifier and partition key have been specified in the <paramref name="options"/>.</exception>
/// <exception cref="InvalidOperationException">Occurs when an invalid partition identifier has been specified in the <paramref name="options"/>.</exception>
/// <exception cref="EventHubsException">Occurs when querying Event Hub metadata took longer than expected.</exception>
///
/// <remarks>
/// Upon the first attempt to enqueue an event, the <see cref="SendEventBatchSucceededAsync" /> and <see cref="SendEventBatchFailedAsync" /> handlers
/// can no longer be changed.
/// </remarks>
///
public virtual async Task<int> EnqueueEventAsync(EventData eventData,
EnqueueEventOptions options,
CancellationToken cancellationToken = default)
{
(var partitionId, var partitionKey) = EnqueueEventOptions.DeconstructOrUseDefaultAttributes(options);
Argument.AssertNotClosed(_isClosed, nameof(EventHubBufferedProducerClient));
Argument.AssertNotNull(eventData, nameof(eventData));
AssertSinglePartitionReference(partitionId, partitionKey);
AssertRequiredHandlerSetForEnqueue(_sendFailedHandler, nameof(SendEventBatchFailedAsync));
_areHandlersLocked = true;
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var logPartition = partitionKey ?? partitionId ?? string.Empty;
var operationId = GenerateOperationId();
Logger.BufferedProducerEventEnqueueStart(Identifier, EventHubName, logPartition, operationId);
try
{
// If publishing has not been started or is not healthy, attempt to restart it.
if ((!IsPublishing) || (_producerManagementTask?.IsCompleted ?? false))
{
try
{
if (!_stateGuard.Wait(0, cancellationToken))
{
await _stateGuard.WaitAsync(cancellationToken).ConfigureAwait(false);
}
Argument.AssertNotClosed(_isClosed, nameof(EventHubBufferedProducerClient));
// StartPublishingAsync will verify that publishing is not already taking
// place and act appropriately if nothing needs to be restarted; there's no need
// to perform a double-check of the conditions here after acquiring the semaphore.
// If this call takes too long to complete, an EventHubsException will be thrown.
await StartPublishingAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
if (_stateGuard.CurrentCount == 0)
{
_stateGuard.Release();
}
}
}
// If there was a partition identifier requested, validate that it is part of
// the known set, now that publishing has been started.
if (!string.IsNullOrEmpty(partitionId))
{
AssertValidPartition(partitionId, _partitionHash);
}
// If there was a partition key requested, calculate the assigned partition and
// annotate the event so that it is preserved by the Event Hubs broker.
if (!string.IsNullOrEmpty(partitionKey))
{
partitionId = PartitionResolver.AssignForPartitionKey(partitionKey, _partitions);
eventData.GetRawAmqpMessage().SetPartitionKey(partitionKey);
}
// If no partition was assigned, assign one for automatic routing.
if (string.IsNullOrEmpty(partitionId))
{
partitionId = PartitionResolver.AssignRoundRobin(_partitions);
}
// Enqueue the event into the channel for the assigned partition. Note that this call will wait
// if there is no room in the channel and may take some time to complete.
var partitionState = _activePartitionStateMap.GetOrAdd(partitionId, partitionId => new PartitionPublishingState(partitionId, _options));
var writer = partitionState.PendingEventsWriter;
_clientDiagnostics.InstrumentMessage(eventData.Properties, DiagnosticProperty.EventActivityName, out _, out _);
await writer.WriteAsync(eventData, cancellationToken).ConfigureAwait(false);
var count = Interlocked.Increment(ref _totalBufferedEventCount);
Interlocked.Increment(ref partitionState.BufferedEventCount);
_eventEnqueuedCompletionSource?.TrySetResult(true);
Logger.BufferedProducerEventEnqueued(Identifier, EventHubName, logPartition, partitionId, operationId, count);
}
catch (Exception ex)
{
Logger.BufferedProducerEventEnqueueError(Identifier, EventHubName, logPartition, operationId, ex.Message);
throw;
}
finally
{
Logger.BufferedProducerEventEnqueueComplete(Identifier, EventHubName, logPartition, operationId);
}
return _totalBufferedEventCount;
}
/// <summary>
/// Enqueues a set of <see cref="EventData"/> into the buffer to be published to the Event Hub. If there is insufficient capacity in
/// the buffer when this method is invoked, it will wait for space to become available and ensure that all <paramref name="events"/>
/// in the <paramref name="events"/> set have been enqueued.
///
/// When this call returns, the <paramref name="events" /> have been accepted into the buffer, but it may not have been published yet.
/// Publishing will take place at a nondeterministic point in the future as the buffer is processed.
/// </summary>
///
/// <param name="events">The set of events to be enqueued into the buffer and, later, published.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>The total number of events that are currently buffered and waiting to be published, across all partitions.</returns>
///
/// <exception cref="InvalidOperationException">Occurs when no <see cref="SendEventBatchFailedAsync" /> handler is currently registered.</exception>
/// <exception cref="EventHubsException">Occurs when querying Event Hub metadata took longer than expected.</exception>
///
/// <remarks>
/// Should cancellation or an unexpected exception occur, it is possible for calls to this method to result in a partial failure where some, but not all,
/// of the <paramref name="events" /> have enqueued. For scenarios where it is important to understand whether each individual event has been
/// enqueued, it is recommended to call the see <see cref="EnqueueEventAsync(EventData, EnqueueEventOptions, CancellationToken)" /> or
/// <see cref="EnqueueEventAsync(EventData, CancellationToken)" /> overloads instead of this method.
///
/// Upon the first attempt to enqueue events, the <see cref="SendEventBatchSucceededAsync" /> and <see cref="SendEventBatchFailedAsync" /> handlers
/// can no longer be changed.
/// </remarks>
///
public virtual Task<int> EnqueueEventsAsync(IEnumerable<EventData> events,
CancellationToken cancellationToken = default) => EnqueueEventsAsync(events, default, cancellationToken);
/// <summary>
/// Enqueues a set of <see cref="EventData"/> into the buffer to be published to the Event Hub. If there is insufficient capacity in
/// the buffer when this method is invoked, it will wait for space to become available and ensure that all <paramref name="events"/>
/// in the <paramref name="events"/> set have been enqueued.
///
/// When this call returns, the <paramref name="events"/> have been accepted into the buffer, but it may not have been published yet.
/// Publishing will take place at a nondeterministic point in the future as the buffer is processed.
/// </summary>
///
/// <param name="events">The set of events to be enqueued into the buffer and, later, published.</param>
/// <param name="options">The set of options to apply when publishing these events.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>The total number of events that are currently buffered and waiting to be published, across all partitions.</returns>
///
/// <exception cref="InvalidOperationException">Occurs when no <see cref="SendEventBatchFailedAsync" /> handler is currently registered.</exception>
/// <exception cref="InvalidOperationException">Occurs when both a partition identifier and partition key have been specified in the <paramref name="options"/>.</exception>
/// <exception cref="InvalidOperationException">Occurs when an invalid partition identifier has been specified in the <paramref name="options"/>.</exception>
/// <exception cref="EventHubsException">Occurs when the <see cref="EventHubBufferedProducerClient" /> was unable to start within the configured timeout period.</exception>
///
/// <remarks>
/// Should cancellation or an unexpected exception occur, it is possible for calls to this method to result in a partial failure where some, but not all,
/// of the <paramref name="events" /> have enqueued. For scenarios where it is important to understand whether each individual event has been
/// enqueued, it is recommended to call the see <see cref="EnqueueEventAsync(EventData, EnqueueEventOptions, CancellationToken)" /> or
/// <see cref="EnqueueEventAsync(EventData, CancellationToken)" /> overloads instead of this method.
///
/// Upon the first attempt to enqueue events, the <see cref="SendEventBatchSucceededAsync" /> and <see cref="SendEventBatchFailedAsync" /> handlers
/// can no longer be changed.
/// </remarks>
///
public virtual async Task<int> EnqueueEventsAsync(IEnumerable<EventData> events,
EnqueueEventOptions options,
CancellationToken cancellationToken = default)
{
(var partitionId, var partitionKey) = EnqueueEventOptions.DeconstructOrUseDefaultAttributes(options);
Argument.AssertNotClosed(_isClosed, nameof(EventHubBufferedProducerClient));
Argument.AssertNotNull(events, nameof(events));
AssertSinglePartitionReference(partitionId, partitionKey);
AssertRequiredHandlerSetForEnqueue(_sendFailedHandler, nameof(SendEventBatchFailedAsync));
_areHandlersLocked = true;
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var logPartition = (partitionKey ?? partitionId ?? string.Empty);
var operationId = GenerateOperationId();
Logger.BufferedProducerEventEnqueueStart(Identifier, EventHubName, logPartition, operationId);
try
{
// If publishing has not been started or is not healthy, attempt to restart it.
if ((!IsPublishing) || (_producerManagementTask?.IsCompleted ?? false))
{
try
{
if (!_stateGuard.Wait(0, cancellationToken))
{
await _stateGuard.WaitAsync(cancellationToken).ConfigureAwait(false);
}
Argument.AssertNotClosed(_isClosed, nameof(EventHubBufferedProducerClient));
// StartPublishingAsync will verify that publishing is not already taking
// place and act appropriately if nothing needs to be restarted; there's no need
// to perform a double-check of the conditions here after acquiring the semaphore.
// If this call takes too long to complete, an EventHubsException will be thrown.
await StartPublishingAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
if (_stateGuard.CurrentCount == 0)
{
_stateGuard.Release();
}
}
}
// If there was a partition identifier requested, validate that it is part of
// the known set, now that publishing has been started.
if (!string.IsNullOrEmpty(partitionId))
{
AssertValidPartition(partitionId, _partitionHash);
}
// If there was a partition key requested, calculate the assigned partition.
if (!string.IsNullOrEmpty(partitionKey))
{
partitionId = PartitionResolver.AssignForPartitionKey(partitionKey, _partitions);
}
// If there is a stable partition identifier for all events in the batch, acquire the publisher for it.
var partitionState = string.IsNullOrEmpty(partitionId)
? null
: _activePartitionStateMap.GetOrAdd(partitionId, partitionId => new PartitionPublishingState(partitionId, _options));
// Enumerate the events and enqueue them.
foreach (var eventData in events)
{
var eventPartitionId = partitionId;
// If there is an associated partition key, annotate the event so that it is
// preserved by the Event Hubs broker.
if (!string.IsNullOrEmpty(partitionKey))
{
eventData.GetRawAmqpMessage().SetPartitionKey(partitionKey);
}
// If no partition was assigned, assign one for automatic routing.