-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathEventHubProducerClient.cs
1322 lines (1165 loc) · 65.4 KB
/
EventHubProducerClient.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.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Messaging.EventHubs.Core;
using Azure.Messaging.EventHubs.Diagnostics;
namespace Azure.Messaging.EventHubs.Producer
{
/// <summary>
/// A client responsible for publishing <see cref="EventData" /> to a specific Event Hub,
/// grouped together in batches. Depending on the options specified when sending, events data
/// may be automatically routed to an available partition or sent to a specifically requested partition.
/// </summary>
///
/// <remarks>
/// <para>
/// Allowing automatic routing of partitions is recommended when:
/// <para>- The sending of events needs to be highly available.</para>
/// <para>- The event data should be evenly distributed among all available partitions.</para>
/// </para>
///
/// <para>
/// If no partition is specified, the following rules are used for automatically selecting one:
/// <para>1) Distribute the events equally amongst all available partitions using a round-robin approach.</para>
/// <para>2) If a partition becomes unavailable, the Event Hubs service will automatically detect it and forward the message to another available partition.</para>
/// </para>
///
/// <para>
/// The <see cref="EventHubProducerClient" /> is safe to cache and use for the lifetime of an application, and that is best practice when the application
/// publishes events regularly or semi-regularly. The producer holds responsibility for efficient resource management, working to keep resource usage low during
/// periods of inactivity and manage health during periods of higher use. Calling either the <see cref="CloseAsync" /> or <see cref="DisposeAsync" />
/// method as the application is shutting down will ensure that network resources and other unmanaged objects are properly cleaned up.
/// </para>
/// </remarks>
///
public class EventHubProducerClient : IAsyncDisposable
{
/// <summary>The maximum number of attempts that may be made to get a <see cref="TransportProducer" /> from the pool.</summary>
internal const int MaximumCreateProducerAttempts = 3;
/// <summary>The minimum allowable size, in bytes, for a batch to be sent.</summary>
internal const int MinimumBatchSizeLimit = 24;
/// <summary>The set of default publishing options to use when no specific options are requested.</summary>
private static readonly SendEventOptions DefaultSendOptions = new SendEventOptions();
/// <summary>Sets how long a dedicated <see cref="TransportProducer" /> would sit in memory before its <see cref="TransportProducerPool" /> would remove and close it.</summary>
private static readonly TimeSpan PartitionProducerLifespan = TimeSpan.FromMinutes(5);
/// <summary>Indicates whether or not this instance has been closed.</summary>
private volatile bool _closed;
/// <summary>
/// The fully qualified Event Hubs namespace that the producer is associated with. This is likely
/// to be similar to <c>{yournamespace}.servicebus.windows.net</c>.
/// </summary>
///
public string FullyQualifiedNamespace => Connection.FullyQualifiedNamespace;
/// <summary>
/// The name of the Event Hub that the producer is connected to, specific to the
/// Event Hubs namespace that contains it.
/// </summary>
///
public string EventHubName => Connection.EventHubName;
/// <summary>
/// Indicates whether or not this <see cref="EventHubProducerClient" /> has been closed.
/// </summary>
///
/// <value>
/// <c>true</c> if the client is closed; otherwise, <c>false</c>.
/// </value>
///
public bool IsClosed
{
get => _closed;
protected set => _closed = value;
}
/// <summary>
/// Indicates whether the client has ownership of the associated <see cref="EventHubConnection" />
/// and should take responsibility for managing its lifespan.
/// </summary>
///
private bool OwnsConnection { get; } = true;
/// <summary>
/// The policy to use for determining retry behavior for when an operation fails.
/// </summary>
///
private EventHubsRetryPolicy RetryPolicy { get; }
/// <summary>
/// The set of options to use with the <see cref="EventHubProducerClient" /> instance.
/// </summary>
///
private EventHubProducerClientOptions Options { get; }
/// <summary>
/// The active connection to the Azure Event Hubs service, enabling client communications for metadata
/// about the associated Event Hub and access to a transport-aware producer.
/// </summary>
///
private EventHubConnection Connection { get; }
/// <summary>
/// A <see cref="TransportProducerPool" /> used to manage a set of partition specific <see cref="TransportProducer" />.
/// </summary>
///
private TransportProducerPool PartitionProducerPool { get; }
/// <summary>
/// The publishing-related state associated with partitions.
/// </summary>
///
/// <value>
/// Created if the producer has been configured with one or more features which requires
/// publishing to partitions in a stateful manner; otherwise, <c>null</c>.
/// </value>
///
private ConcurrentDictionary<string, PartitionPublishingState> PartitionState { get; }
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> 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/en-us/azure/event-hubs/event-hubs-get-connection-string"/>
///
public EventHubProducerClient(string connectionString) : this(connectionString, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> 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">The set of options to use for this consumer.</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/en-us/azure/event-hubs/event-hubs-get-connection-string"/>
///
public EventHubProducerClient(string connectionString,
EventHubProducerClientOptions clientOptions) : this(connectionString, null, clientOptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
/// <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 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/en-us/azure/event-hubs/event-hubs-get-connection-string"/>
///
public EventHubProducerClient(string connectionString,
string eventHubName) : this(connectionString, eventHubName, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
/// <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 producer with.</param>
/// <param name="clientOptions">A set of options to apply when configuring the 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/en-us/azure/event-hubs/event-hubs-get-connection-string"/>
///
public EventHubProducerClient(string connectionString,
string eventHubName,
EventHubProducerClientOptions clientOptions)
{
Argument.AssertNotNullOrEmpty(connectionString, nameof(connectionString));
clientOptions = clientOptions?.Clone() ?? new EventHubProducerClientOptions();
OwnsConnection = true;
Connection = new EventHubConnection(connectionString, eventHubName, clientOptions.ConnectionOptions);
RetryPolicy = clientOptions.RetryOptions.ToRetryPolicy();
Options = clientOptions;
PartitionProducerPool = new TransportProducerPool(partitionId =>
Connection.CreateTransportProducer(
partitionId,
clientOptions.CreateFeatureFlags(),
Options.GetPublishingOptionsOrDefaultForPartition(partitionId),
RetryPolicy));
if (RequiresStatefulPartitions(clientOptions))
{
PartitionState = new ConcurrentDictionary<string, PartitionPublishingState>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> 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 Event Hubs 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 options to apply when configuring the producer.</param>
///
internal EventHubProducerClient(string fullyQualifiedNamespace,
string eventHubName,
EventHubsSharedAccessKeyCredential credential,
EventHubProducerClientOptions clientOptions = default)
{
Argument.AssertWellFormedEventHubsNamespace(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
Argument.AssertNotNull(credential, nameof(credential));
clientOptions = clientOptions?.Clone() ?? new EventHubProducerClientOptions();
OwnsConnection = true;
Connection = new EventHubConnection(fullyQualifiedNamespace, eventHubName, credential, clientOptions.ConnectionOptions);
Options = clientOptions;
RetryPolicy = clientOptions.RetryOptions.ToRetryPolicy();
PartitionProducerPool = new TransportProducerPool(partitionId =>
Connection.CreateTransportProducer(
partitionId,
clientOptions.CreateFeatureFlags(),
Options.GetPublishingOptionsOrDefaultForPartition(partitionId),
RetryPolicy));
if (RequiresStatefulPartitions(clientOptions))
{
PartitionState = new ConcurrentDictionary<string, PartitionPublishingState>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> 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 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="clientOptions">A set of options to apply when configuring the producer.</param>
///
public EventHubProducerClient(string fullyQualifiedNamespace,
string eventHubName,
TokenCredential credential,
EventHubProducerClientOptions clientOptions = default)
{
Argument.AssertWellFormedEventHubsNamespace(fullyQualifiedNamespace, nameof(fullyQualifiedNamespace));
Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
Argument.AssertNotNull(credential, nameof(credential));
clientOptions = clientOptions?.Clone() ?? new EventHubProducerClientOptions();
OwnsConnection = true;
Connection = new EventHubConnection(fullyQualifiedNamespace, eventHubName, credential, clientOptions.ConnectionOptions);
Options = clientOptions;
RetryPolicy = clientOptions.RetryOptions.ToRetryPolicy();
PartitionProducerPool = new TransportProducerPool(partitionId =>
Connection.CreateTransportProducer(
partitionId,
clientOptions.CreateFeatureFlags(),
Options.GetPublishingOptionsOrDefaultForPartition(partitionId),
RetryPolicy));
if (RequiresStatefulPartitions(clientOptions))
{
PartitionState = new ConcurrentDictionary<string, PartitionPublishingState>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> 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 options to apply when configuring the producer.</param>
///
public EventHubProducerClient(EventHubConnection connection,
EventHubProducerClientOptions clientOptions = default)
{
Argument.AssertNotNull(connection, nameof(connection));
clientOptions = clientOptions?.Clone() ?? new EventHubProducerClientOptions();
OwnsConnection = false;
Connection = connection;
RetryPolicy = clientOptions.RetryOptions.ToRetryPolicy();
Options = clientOptions;
PartitionProducerPool = new TransportProducerPool(partitionId =>
Connection.CreateTransportProducer(
partitionId,
clientOptions.CreateFeatureFlags(),
Options.GetPublishingOptionsOrDefaultForPartition(partitionId),
RetryPolicy));
if (RequiresStatefulPartitions(clientOptions))
{
PartitionState = new ConcurrentDictionary<string, PartitionPublishingState>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
/// <param name="connection">The connection to use as the basis for delegation of client-type operations.</param>
/// <param name="transportProducer">The transport producer instance to use as the basis for service communication.</param>
/// <param name="partitionProducerPool">A <see cref="TransportProducerPool" /> used to manage a set of partition specific <see cref="TransportProducer" />.</param>
///
/// <remarks>
/// This constructor is intended to be used internally for functional
/// testing only.
/// </remarks>
///
internal EventHubProducerClient(EventHubConnection connection,
TransportProducer transportProducer,
TransportProducerPool partitionProducerPool = default)
{
Argument.AssertNotNull(connection, nameof(connection));
Argument.AssertNotNull(transportProducer, nameof(transportProducer));
OwnsConnection = false;
Connection = connection;
RetryPolicy = new EventHubsRetryOptions().ToRetryPolicy();
Options = new EventHubProducerClientOptions();
PartitionProducerPool = partitionProducerPool ?? new TransportProducerPool(partitionId => transportProducer);
if (RequiresStatefulPartitions(Options))
{
PartitionState = new ConcurrentDictionary<string, PartitionPublishingState>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EventHubProducerClient" /> class.
/// </summary>
///
protected EventHubProducerClient()
{
OwnsConnection = false;
}
/// <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(EventHubProducerClient));
return await Connection.GetPropertiesAsync(RetryPolicy, 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(EventHubProducerClient));
return await Connection.GetPartitionIdsAsync(RetryPolicy, 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(EventHubProducerClient));
return await Connection.GetPartitionPropertiesAsync(partitionId, RetryPolicy, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// A set of information about the state of publishing for a partition, as observed by the <see cref="EventHubProducerClient" />. This
/// data can always be read, but will only be populated with information relevant to the active features for the producer client.
/// </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 about the publishing state of the requested partition, within the context of this producer.</returns>
///
/// <remarks>
/// The state of a partition is only understood by the <see cref="EventHubProducerClient" /> after events have been published to that
/// partition; calling this method for a partition before events have been published to it will return an empty set of properties.
/// </remarks>
///
internal virtual async Task<PartitionPublishingProperties> GetPartitionPublishingPropertiesAsync(string partitionId,
CancellationToken cancellationToken = default)
{
Argument.AssertNotClosed(IsClosed, nameof(EventHubProducerClient));
Argument.AssertNotNullOrEmpty(partitionId, nameof(partitionId));
// If the producer does not require stateful partitions, return an empty
// instance.
if (!RequiresStatefulPartitions(Options))
{
return PartitionPublishingProperties.Empty;
}
// If the state has not yet been initialized, then do so now.
var partitionState = PartitionState.GetOrAdd(partitionId, new PartitionPublishingState(partitionId));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
try
{
await partitionState.PublishingGuard.WaitAsync(cancellationToken).ConfigureAwait(false);
if (!partitionState.IsInitialized)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
await InitializePartitionStateAsync(partitionState, cancellationToken).ConfigureAwait(false);
}
return CreatePublishingPropertiesFromPartitionState(Options, partitionState);
}
finally
{
partitionState.PublishingGuard.Release();
}
}
/// <summary>
/// Sends a set of events to the associated Event Hub as a single operation. To avoid the
/// overhead associated with measuring and validating the size in the client, validation will
/// be delegated to the Event Hubs service and is deferred until the operation is invoked.
/// The call will fail if the size of the specified set of events exceeds the maximum allowable
/// size of a single batch.
/// </summary>
///
/// <param name="eventBatch">The set of event data to send.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>
/// A task to be resolved on when the operation has completed; if no exception is thrown when awaited, the
/// Event Hubs service has acknowledge receipt and assumed responsibility for delivery of the set of events.
/// </returns>
///
/// <exception cref="EventHubsException">
/// Occurs when the set of events exceeds the maximum size allowed in a single batch, as determined by the Event Hubs service. The <see cref="EventHubsException.Reason" /> will be set to
/// <see cref="EventHubsException.FailureReason.MessageSizeExceeded"/> in this case.
/// </exception>
///
/// <remarks>
/// When published, the result is atomic; either all events that belong to the set were successful or all
/// have failed. Partial success is not possible.
/// </remarks>
///
/// <seealso cref="SendAsync(IEnumerable{EventData}, SendEventOptions, CancellationToken)" />
/// <seealso cref="SendAsync(EventDataBatch, CancellationToken)" />
/// <seealso cref="CreateBatchAsync(CancellationToken)" />
///
public virtual async Task SendAsync(IEnumerable<EventData> eventBatch,
CancellationToken cancellationToken = default) => await SendAsync(eventBatch, null, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Sends a set of events to the associated Event Hub as a single operation. To avoid the
/// overhead associated with measuring and validating the size in the client, validation will
/// be delegated to the Event Hubs service and is deferred until the operation is invoked.
/// The call will fail if the size of the specified set of events exceeds the maximum allowable
/// size of a single batch.
/// </summary>
///
/// <param name="eventBatch">The set of event data to send.</param>
/// <param name="options">The set of options to consider when sending this batch.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>
/// A task to be resolved on when the operation has completed; if no exception is thrown when awaited, the
/// Event Hubs service has acknowledge receipt and assumed responsibility for delivery of the set of events.
/// </returns>
///
/// <exception cref="EventHubsException">
/// Occurs when the set of events exceeds the maximum size allowed in a single batch, as determined by the Event Hubs service. The <see cref="EventHubsException.Reason" /> will be set to
/// <see cref="EventHubsException.FailureReason.MessageSizeExceeded"/> in this case.
/// </exception>
///
/// <remarks>
/// When published, the result is atomic; either all events that belong to the set were successful or all
/// have failed. Partial success is not possible.
/// </remarks>
///
/// <seealso cref="SendAsync(IEnumerable{EventData}, CancellationToken)" />
/// <seealso cref="SendAsync(EventDataBatch, CancellationToken)" />
/// <seealso cref="CreateBatchAsync(CreateBatchOptions, CancellationToken)" />
///
public virtual async Task SendAsync(IEnumerable<EventData> eventBatch,
SendEventOptions options,
CancellationToken cancellationToken = default)
{
options = options?.Clone() ?? DefaultSendOptions;
Argument.AssertNotNull(eventBatch, nameof(eventBatch));
AssertSinglePartitionReference(options.PartitionId, options.PartitionKey);
var events = eventBatch switch
{
IReadOnlyList<EventData> eventList => eventList,
_ => eventBatch.ToList()
};
if (events.Count == 0)
{
return;
}
var sendTask = (Options.EnableIdempotentPartitions)
? SendIdempotentAsync(events, options, cancellationToken)
: SendInternalAsync(events, options, cancellationToken);
await sendTask.ConfigureAwait(false);
}
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach.
/// </summary>
///
/// <param name="eventBatch">The set of event data to send. A batch may be created using <see cref="CreateBatchAsync(CancellationToken)" />.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>
/// A task to be resolved on when the operation has completed; if no exception is thrown when awaited, the
/// Event Hubs service has acknowledge receipt and assumed responsibility for delivery of the batch.
/// </returns>
///
/// <remarks>
/// When published, the result is atomic; either all events that belong to the batch were successful or all
/// have failed. Partial success is not possible.
/// </remarks>
///
/// <seealso cref="CreateBatchAsync(CancellationToken)" />
///
public virtual async Task SendAsync(EventDataBatch eventBatch,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(eventBatch, nameof(eventBatch));
AssertSinglePartitionReference(eventBatch.SendOptions.PartitionId, eventBatch.SendOptions.PartitionKey);
if (eventBatch.Count == 0)
{
return;
}
var sendTask = (Options.EnableIdempotentPartitions)
? SendIdempotentAsync(eventBatch, cancellationToken)
: SendInternalAsync(eventBatch, cancellationToken);
await sendTask.ConfigureAwait(false);
}
/// <summary>
/// Creates a size-constraint batch to which <see cref="EventData" /> may be added using a try-based pattern. If an event would
/// exceed the maximum allowable size of the batch, the batch will not allow adding the event and signal that scenario using its
/// return value.
///
/// Because events that would violate the size constraint cannot be added, publishing a batch will not trigger an exception when
/// attempting to send the events to the Event Hubs service.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>An <see cref="EventDataBatch" /> with the default batch options.</returns>
///
/// <seealso cref="CreateBatchAsync(CreateBatchOptions, CancellationToken)" />
/// <seealso cref="SendAsync(EventDataBatch, CancellationToken)" />
///
public virtual async ValueTask<EventDataBatch> CreateBatchAsync(CancellationToken cancellationToken = default) => await CreateBatchAsync(null, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Creates a size-constraint batch to which <see cref="EventData" /> may be added using a try-based pattern. If an event would
/// exceed the maximum allowable size of the batch, the batch will not allow adding the event and signal that scenario using its
/// return value.
///
/// Because events that would violate the size constraint cannot be added, publishing a batch will not trigger an exception when
/// attempting to send the events to the Event Hubs service.
/// </summary>
///
/// <param name="options">The set of options to consider when creating this batch.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>An <see cref="EventDataBatch" /> with the requested <paramref name="options"/>.</returns>
///
/// <seealso cref="CreateBatchAsync(CancellationToken)" />
/// <seealso cref="SendAsync(EventDataBatch, CancellationToken)" />
///
public virtual async ValueTask<EventDataBatch> CreateBatchAsync(CreateBatchOptions options,
CancellationToken cancellationToken = default)
{
options = options?.Clone() ?? new CreateBatchOptions();
AssertSinglePartitionReference(options.PartitionId, options.PartitionKey);
TransportEventBatch transportBatch = await PartitionProducerPool.EventHubProducer.CreateBatchAsync(options, cancellationToken).ConfigureAwait(false);
return new EventDataBatch(transportBatch, FullyQualifiedNamespace, EventHubName, options);
}
/// <summary>
/// Closes the producer.
/// </summary>
///
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
///
public virtual async Task CloseAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
if (IsClosed)
{
return;
}
IsClosed = true;
var identifier = GetHashCode().ToString(CultureInfo.InvariantCulture);
EventHubsEventSource.Log.ClientCloseStart(nameof(EventHubProducerClient), EventHubName, identifier);
// Attempt to close the pool of producers. In the event that an exception is encountered,
// it should not impact the attempt to close the connection, assuming ownership.
var transportProducerPoolException = default(Exception);
try
{
await PartitionProducerPool.CloseAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
EventHubsEventSource.Log.ClientCloseError(nameof(EventHubProducerClient), EventHubName, identifier, ex.Message);
transportProducerPoolException = ex;
}
// An exception when closing the connection supersedes one observed when closing the
// individual transport clients.
try
{
if (OwnsConnection)
{
await Connection.CloseAsync(CancellationToken.None).ConfigureAwait(false);
}
}
catch (Exception ex)
{
EventHubsEventSource.Log.ClientCloseError(nameof(EventHubProducerClient), EventHubName, identifier, ex.Message);
throw;
}
finally
{
EventHubsEventSource.Log.ClientCloseComplete(nameof(EventHubProducerClient), EventHubName, identifier);
}
// If there was an active exception pending from closing the
// transport producer pool, surface it now.
if (transportProducerPoolException != default)
{
ExceptionDispatchInfo.Capture(transportProducerPoolException).Throw();
}
}
/// <summary>
/// Performs the task needed to clean up resources used by the <see cref="EventHubProducerClient" />,
/// including ensuring that the client itself has been closed.
/// </summary>
///
/// <returns>A task to be resolved on when the operation has completed.</returns>
///
[SuppressMessage("Usage", "AZC0002:Ensure all service methods take an optional CancellationToken parameter.", Justification = "This signature must match the IAsyncDisposable interface.")]
public virtual async ValueTask DisposeAsync()
{
await CloseAsync().ConfigureAwait(false);
GC.SuppressFinalize(this);
}
/// <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() => base.ToString();
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach. Because the batch is implicitly created, the size of the event set is not
/// validated until this method is invoked. The call will fail if the size of the specified set of events exceeds the maximum allowable size of a single batch.
/// </summary>
///
/// <param name="events">The set of event data to send.</param>
/// <param name="options">The set of options to consider when sending this batch.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
private async Task SendInternalAsync(IReadOnlyList<EventData> events,
SendEventOptions options,
CancellationToken cancellationToken = default)
{
var attempts = 0;
var diagnosticIdentifiers = new List<string>();
InstrumentMessages(events);
foreach (var eventData in events)
{
if (EventDataInstrumentation.TryExtractDiagnosticId(eventData, out var identifier))
{
diagnosticIdentifiers.Add(identifier);
}
}
using DiagnosticScope scope = CreateDiagnosticScope(diagnosticIdentifiers);
var pooledProducer = PartitionProducerPool.GetPooledProducer(options.PartitionId, PartitionProducerLifespan);
while (!cancellationToken.IsCancellationRequested)
{
try
{
await using var _ = pooledProducer.ConfigureAwait(false);
await pooledProducer.TransportProducer.SendAsync(events, options, cancellationToken).ConfigureAwait(false);
return;
}
catch (EventHubsException eventHubException)
when (eventHubException.Reason == EventHubsException.FailureReason.ClientClosed && ShouldRecreateProducer(pooledProducer.TransportProducer, options.PartitionId))
{
if (++attempts >= MaximumCreateProducerAttempts)
{
scope.Failed(eventHubException);
throw;
}
pooledProducer = PartitionProducerPool.GetPooledProducer(options.PartitionId, PartitionProducerLifespan);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
throw new TaskCanceledException();
}
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach.
/// </summary>
///
/// <param name="eventBatch">The set of event data to send. A batch may be created using <see cref="CreateBatchAsync(CancellationToken)" />.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
private async Task SendInternalAsync(EventDataBatch eventBatch,
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = CreateDiagnosticScope(eventBatch.GetEventDiagnosticIdentifiers());
var attempts = 0;
var pooledProducer = PartitionProducerPool.GetPooledProducer(eventBatch.SendOptions.PartitionId, PartitionProducerLifespan);
try
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
await using var _ = pooledProducer.ConfigureAwait(false);
eventBatch.Lock();
await pooledProducer.TransportProducer.SendAsync(eventBatch, cancellationToken).ConfigureAwait(false);
return;
}
catch (EventHubsException eventHubException)
when (eventHubException.Reason == EventHubsException.FailureReason.ClientClosed && ShouldRecreateProducer(pooledProducer.TransportProducer, eventBatch.SendOptions.PartitionId))
{
if (++attempts >= MaximumCreateProducerAttempts)
{
scope.Failed(eventHubException);
throw;
}
pooledProducer = PartitionProducerPool.GetPooledProducer(eventBatch.SendOptions.PartitionId, PartitionProducerLifespan);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
}
finally
{
eventBatch.Unlock();
}
throw new TaskCanceledException();
}
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach. Because the batch is implicitly created, the size of the event set is not
/// validated until this method is invoked. The call will fail if the size of the specified set of events exceeds the maximum allowable size of a single batch.
/// </summary>
///
/// <param name="eventSet">The set of event data to send.</param>
/// <param name="options">The set of options to consider when sending this batch.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
private async Task SendIdempotentAsync(IReadOnlyList<EventData> eventSet,
SendEventOptions options,
CancellationToken cancellationToken = default)
{
AssertPartitionIsReferenced(options.PartitionId);
AssertIdempotentEventsNotPublished(eventSet);
try
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
EventHubsEventSource.Log.IdempotentPublishStart(EventHubName, options.PartitionId);
var partitionState = PartitionState.GetOrAdd(options.PartitionId, new PartitionPublishingState(options.PartitionId));
try
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
await partitionState.PublishingGuard.WaitAsync(cancellationToken).ConfigureAwait(false);
EventHubsEventSource.Log.IdempotentSynchronizationAcquire(EventHubName, options.PartitionId);
// Ensure that the partition state has been initialized.
if (!partitionState.IsInitialized)
{
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
await InitializePartitionStateAsync(partitionState, cancellationToken).ConfigureAwait(false);
}
// Sequence the events for publishing.
var lastSequence = partitionState.LastPublishedSequenceNumber.Value;
var firstSequence = lastSequence;
foreach (var eventData in eventSet)
{
lastSequence = NextSequence(lastSequence);
eventData.PendingPublishSequenceNumber = lastSequence;
eventData.PendingProducerGroupId = partitionState.ProducerGroupId;
eventData.PendingProducerOwnerLevel = partitionState.OwnerLevel;
}
// Publish the events.
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
EventHubsEventSource.Log.IdempotentSequencePublish(EventHubName, options.PartitionId, firstSequence, lastSequence);
await SendInternalAsync(eventSet, options, cancellationToken).ConfigureAwait(false);
// Update state and commit the state.
EventHubsEventSource.Log.IdempotentSequenceUpdate(EventHubName, options.PartitionId, partitionState.LastPublishedSequenceNumber.Value, lastSequence);
partitionState.LastPublishedSequenceNumber = lastSequence;
foreach (var eventData in eventSet)
{
eventData.CommitPublishingState();
}
}
catch
{
// Clear the pending state in the face of an exception.
foreach (var eventData in eventSet)
{
eventData.ClearPublishingState();
}
throw;
}
finally
{
partitionState.PublishingGuard.Release();
EventHubsEventSource.Log.IdempotentSynchronizationRelease(EventHubName, options.PartitionId);
}
}
catch (Exception ex)
{
EventHubsEventSource.Log.IdempotentPublishError(EventHubName, options.PartitionId, ex.Message);
throw;
}
finally
{
EventHubsEventSource.Log.IdempotentPublishComplete(EventHubName, options.PartitionId);
}
}
/// <summary>
/// Sends a set of events to the associated Event Hub using a batched approach.
/// </summary>
///
/// <param name="eventBatch">The set of event data to send. A batch may be created using <see cref="CreateBatchAsync(CancellationToken)" />.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken" /> instance to signal the request to cancel the operation.</param>
///
private async Task SendIdempotentAsync(EventDataBatch eventBatch,
CancellationToken cancellationToken = default)
{
var options = eventBatch.SendOptions;
AssertPartitionIsReferenced(options.PartitionId);
AssertIdempotentBatchNotPublished(eventBatch);