-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
AmqpConnectionScope.cs
1365 lines (1182 loc) · 69.8 KB
/
AmqpConnectionScope.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.Globalization;
using System.Net;
using System.Net.Security;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Diagnostics;
using Azure.Messaging.EventHubs.Authorization;
using Azure.Messaging.EventHubs.Consumer;
using Azure.Messaging.EventHubs.Core;
using Azure.Messaging.EventHubs.Diagnostics;
using Azure.Messaging.EventHubs.Producer;
using Microsoft.Azure.Amqp;
using Microsoft.Azure.Amqp.Encoding;
using Microsoft.Azure.Amqp.Framing;
using Microsoft.Azure.Amqp.Sasl;
using Microsoft.Azure.Amqp.Transport;
namespace Azure.Messaging.EventHubs.Amqp
{
/// <summary>
/// Defines a context for AMQP operations which can be shared amongst the different
/// client types within a given scope.
/// </summary>
///
internal class AmqpConnectionScope : IDisposable
{
/// <summary>The name to assign to the SASL handler to specify that CBS tokens are in use.</summary>
private const string CbsSaslHandlerName = "MSSBCBS";
/// <summary>The suffix to attach to the resource path when using web sockets for service communication.</summary>
private const string WebSocketsPathSuffix = "/$servicebus/websocket/";
/// <summary>The URI scheme to apply when using web sockets for service communication.</summary>
private const string WebSocketsSecureUriScheme = "wss";
/// <summary>The URI scheme to apply when using web sockets for service communication.</summary>
private const string WebSocketsInsecureUriScheme = "ws";
/// <summary>The string formatting mask to apply to the service endpoint to consume events for a given consumer group and partition.</summary>
private const string ConsumerPathSuffixMask = "{0}/ConsumerGroups/{1}/Partitions/{2}";
/// <summary>The string formatting mask to apply to the service endpoint to publish events for a given partition.</summary>
private const string PartitionProducerPathSuffixMask = "{0}/Partitions/{1}";
/// <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 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>Indicates whether or not this instance has been disposed.</summary>
private volatile bool _disposed;
/// <summary>
/// The version of AMQP to use within the scope.
/// </summary>
///
private static Version AmqpVersion { get; } = new Version(1, 0, 0, 0);
/// <summary>
/// The amount of buffer to apply to account for clock skew when
/// refreshing authorization. Authorization will be refreshed earlier
/// than the expected expiration by this amount.
/// </summary>
///
private static TimeSpan AuthorizationRefreshBuffer { get; } = TimeSpan.FromMinutes(7);
/// <summary>
/// The amount of seconds to use as the basis for calculating a random jitter amount
/// when refreshing token authorization. This is intended to ensure that multiple
/// resources using the authorization do not all attempt to refresh at the same moment.
/// </summary>
///
private static int AuthorizationBaseJitterSeconds { get; } = 30;
/// <summary>
/// The minimum amount of time for authorization to be refreshed; any calculations that
/// call for refreshing more frequently will be substituted with this value.
/// </summary>
///
private static TimeSpan MinimumAuthorizationRefresh { get; } = TimeSpan.FromMinutes(3);
/// <summary>
/// The maximum amount of time to allow before authorization is refreshed; any calculations
/// that call for refreshing less frequently will be substituted with this value.
/// </summary>
///
/// <remarks>
/// This value must be less than 49 days, 17 hours, 2 minutes, 47 seconds, 294 milliseconds
/// in order to not overflow the Timer used to track authorization refresh.
/// </remarks>
///
private static TimeSpan MaximumAuthorizationRefresh { get; } = TimeSpan.FromDays(49);
/// <summary>
/// The amount time to allow to refresh authorization of an AMQP link.
/// </summary>
///
private static TimeSpan AuthorizationRefreshTimeout { get; } = TimeSpan.FromMinutes(3);
/// <summary>
/// The amount of buffer to apply when considering an authorization token
/// to be expired. The token's actual expiration will be decreased by this
/// amount, ensuring that it is renewed before it has expired.
/// </summary>
///
private static TimeSpan AuthorizationTokenExpirationBuffer { get; } = AuthorizationRefreshBuffer.Add(TimeSpan.FromMinutes(2));
/// <summary>
/// The amount of time to allow a connection to have no observed traffic before considering it idle.
/// </summary>
///
public uint ConnectionIdleTimeoutMilliseconds { get; }
/// <summary>
/// Indicates whether this <see cref="AmqpConnectionScope"/> has been disposed.
/// </summary>
///
/// <value><c>true</c> if disposed; otherwise, <c>false</c>.</value>
///
public bool IsDisposed
{
get => _disposed;
private set => _disposed = value;
}
/// <summary>
/// The cancellation token to use with operations initiated by the scope.
/// </summary>
///
private CancellationTokenSource OperationCancellationSource { get; } = new CancellationTokenSource();
/// <summary>
/// The set of active AMQP links associated with the connection scope. These are considered children
/// of the active connection and should be managed as such.
/// </summary>
///
private ConcurrentDictionary<AmqpObject, Timer> ActiveLinks { get; } = new ConcurrentDictionary<AmqpObject, Timer>();
/// <summary>
/// The unique identifier of the scope.
/// </summary>
///
private string Id { get; }
/// <summary>
/// The endpoint for the Event Hubs service to which the scope is associated.
/// </summary>
///
private Uri ServiceEndpoint { get; }
/// <summary>
/// The endpoint to used establishing a connection to the Event Hubs service to which the scope is associated.
/// </summary>
///
private Uri ConnectionEndpoint { get; }
/// <summary>
/// The name of the Event Hub to which the scope is associated.
/// </summary>
///
private string EventHubName { get; }
/// <summary>
/// The provider to use for obtaining a token for authorization with the Event Hubs service.
/// </summary>
///
private CbsTokenProvider TokenProvider { get; }
/// <summary>
/// The type of transport to use for communication.
/// </summary>
///
private EventHubsTransportType Transport { get; }
/// <summary>
/// The proxy, if any, which should be used for communication.
/// </summary>
///
private IWebProxy Proxy { get; }
/// <summary>
/// The size of the buffer used for sending information via the active transport.
/// </summary>
///
private int SendBufferSizeInBytes { get; }
/// <summary>
/// The size of the buffer used for receiving information via the active transport.
/// </summary>
///
private int ReceiveBufferSizeInBytes { get; }
/// <summary>
/// A <see cref="RemoteCertificateValidationCallback" /> delegate allowing custom logic to be considered for
/// validation of the remote certificate responsible for encrypting communication.
/// </summary>
///
private RemoteCertificateValidationCallback CertificateValidationCallback { get; }
/// <summary>
/// The AMQP connection that is active for the current scope.
/// </summary>
///
private FaultTolerantAmqpObject<AmqpConnection> ActiveConnection { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AmqpConnectionScope"/> class.
/// </summary>
///
/// <param name="serviceEndpoint">The endpoint for the Event Hubs service to which the scope is associated.</param>
/// <param name="connectionEndpoint">The endpoint to used establishing a connection to the Event Hubs service to which the scope is associated.</param>
/// <param name="eventHubName"> The name of the Event Hub to which the scope is associated.</param>
/// <param name="credential">The credential to use for authorization with the Event Hubs service.</param>
/// <param name="transport">The transport to use for communication.</param>
/// <param name="proxy">The proxy, if any, to use for communication.</param>
/// <param name="idleTimeout">The amount of time to allow a connection to have no observed traffic before considering it idle.</param>
/// <param name="identifier">The identifier to assign this scope; if not provided, one will be generated.</param>
/// <param name="sendBufferSizeBytes">The size, in bytes, of the buffer to use for sending via the transport.</param>
/// <param name="receiveBufferSizeBytes">The size, in bytes, of the buffer to use for receiving from the transport.</param>
/// <param name="certificateValidationCallback">The validation callback to register for participation in the SSL handshake.</param>
///
public AmqpConnectionScope(Uri serviceEndpoint,
Uri connectionEndpoint,
string eventHubName,
EventHubTokenCredential credential,
EventHubsTransportType transport,
IWebProxy proxy,
TimeSpan idleTimeout,
string identifier = default,
int sendBufferSizeBytes = -1,
int receiveBufferSizeBytes = -1,
RemoteCertificateValidationCallback certificateValidationCallback = default)
{
Argument.AssertNotNull(serviceEndpoint, nameof(serviceEndpoint));
Argument.AssertNotNull(connectionEndpoint, nameof(connectionEndpoint));
Argument.AssertNotNullOrEmpty(eventHubName, nameof(eventHubName));
Argument.AssertNotNull(credential, nameof(credential));
Argument.AssertNotNegative(idleTimeout, nameof(idleTimeout));
ValidateTransport(transport);
ServiceEndpoint = serviceEndpoint;
ConnectionEndpoint = connectionEndpoint;
EventHubName = eventHubName;
Transport = transport;
Proxy = proxy;
ConnectionIdleTimeoutMilliseconds = (uint)idleTimeout.TotalMilliseconds;
SendBufferSizeInBytes = sendBufferSizeBytes;
ReceiveBufferSizeInBytes = receiveBufferSizeBytes;
CertificateValidationCallback = certificateValidationCallback;
Id = identifier ?? $"{ eventHubName }-{ Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture).Substring(0, 8) }";
TokenProvider = new CbsTokenProvider(new EventHubTokenCredential(credential), AuthorizationTokenExpirationBuffer, OperationCancellationSource.Token);
Task<AmqpConnection> connectionFactory(TimeSpan timeout) => CreateAndOpenConnectionAsync(AmqpVersion, ServiceEndpoint, ConnectionEndpoint, Transport, Proxy, SendBufferSizeInBytes, ReceiveBufferSizeInBytes, CertificateValidationCallback, Id, timeout);
ActiveConnection = new FaultTolerantAmqpObject<AmqpConnection>(connectionFactory, CloseConnection);
}
/// <summary>
/// Initializes a new instance of the <see cref="AmqpConnectionScope"/> class.
/// </summary>
///
protected AmqpConnectionScope()
{
}
/// <summary>
/// Opens an AMQP link for use with management operations.
/// </summary>
///
/// <param name="operationTimeout">The amount of time to allow for an AMQP operation using the link to complete before attempting to cancel it.</param>
/// <param name="linkTimeout">The timeout to apply for creating the link.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>A link for use with management operations.</returns>
///
/// <remarks>
/// The authorization for this link does not require periodic refreshing.
/// </remarks>
///
public virtual async Task<RequestResponseAmqpLink> OpenManagementLinkAsync(TimeSpan operationTimeout,
TimeSpan linkTimeout,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(_disposed, nameof(AmqpConnectionScope));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
try
{
EventHubsEventSource.Log.AmqpManagementLinkCreateStart(EventHubName);
var stopWatch = ValueStopwatch.StartNew();
if (!ActiveConnection.TryGetOpenedObject(out var connection))
{
connection = await ActiveConnection.GetOrCreateAsync(linkTimeout, cancellationToken).ConfigureAwait(false);
}
var link = await CreateManagementLinkAsync(connection, operationTimeout, linkTimeout.CalculateRemaining(stopWatch.GetElapsedTime()), cancellationToken).ConfigureAwait(false);
await OpenAmqpObjectAsync(link, cancellationToken: cancellationToken).ConfigureAwait(false);
return link;
}
catch (Exception ex)
{
EventHubsEventSource.Log.AmqpManagementLinkCreateError(EventHubName, ex.Message);
throw;
}
finally
{
EventHubsEventSource.Log.AmqpManagementLinkCreateComplete(EventHubName);
}
}
/// <summary>
/// Opens an AMQP link for use with consumer operations.
/// </summary>
///
/// <param name="consumerGroup">The name of the consumer group in the context of which events should be received.</param>
/// <param name="partitionId">The identifier of the Event Hub partition from which events should be received.</param>
/// <param name="eventPosition">The position of the event in the partition where the link should be filtered to.</param>
/// <param name="operationTimeout">The amount of time to allow for an AMQP operation using the link to complete before attempting to cancel it.</param>
/// <param name="linkTimeout">The timeout to apply for creating the link.</param>
/// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested.</param>
/// <param name="prefetchSizeInBytes">The cache size of the prefetch queue. When set, the link makes a best effort to ensure prefetched messages fit into the specified size.</param>
/// <param name="ownerLevel">The relative priority to associate with the link; for a non-exclusive link, this value should be <c>null</c>.</param>
/// <param name="trackLastEnqueuedEventProperties">Indicates whether information on the last enqueued event on the partition is sent as events are received.</param>
/// <param name="linkIdentifier">The identifier to assign to the link; if <c>null</c> or <see cref="string.Empty" />, a random identifier will be generated.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>A link for use with consumer operations.</returns>
///
public virtual async Task<ReceivingAmqpLink> OpenConsumerLinkAsync(string consumerGroup,
string partitionId,
EventPosition eventPosition,
TimeSpan operationTimeout,
TimeSpan linkTimeout,
uint prefetchCount,
long? prefetchSizeInBytes,
long? ownerLevel,
bool trackLastEnqueuedEventProperties,
string linkIdentifier,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(_disposed, nameof(AmqpConnectionScope));
Argument.AssertNotNullOrEmpty(consumerGroup, nameof(consumerGroup));
Argument.AssertNotNullOrEmpty(partitionId, nameof(partitionId));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var ownerLevelLog = ownerLevel?.ToString(CultureInfo.InvariantCulture);
var eventPositionLog = eventPosition.ToString();
try
{
EventHubsEventSource.Log.AmqpConsumerLinkCreateStart(EventHubName, consumerGroup, partitionId, ownerLevelLog, eventPositionLog, linkIdentifier);
var stopWatch = ValueStopwatch.StartNew();
var consumerEndpoint = new Uri(ServiceEndpoint, string.Format(CultureInfo.InvariantCulture, ConsumerPathSuffixMask, EventHubName, consumerGroup, partitionId));
if (!ActiveConnection.TryGetOpenedObject(out var connection))
{
connection = await ActiveConnection.GetOrCreateAsync(linkTimeout, cancellationToken).ConfigureAwait(false);
}
if (string.IsNullOrEmpty(linkIdentifier))
{
linkIdentifier = Guid.NewGuid().ToString();
}
var link = await CreateReceivingLinkAsync(
connection,
consumerEndpoint,
eventPosition,
operationTimeout,
linkTimeout.CalculateRemaining(stopWatch.GetElapsedTime()),
prefetchCount,
prefetchSizeInBytes,
ownerLevel,
trackLastEnqueuedEventProperties,
linkIdentifier,
cancellationToken
).ConfigureAwait(false);
await OpenAmqpObjectAsync(link, cancellationToken: cancellationToken).ConfigureAwait(false);
return link;
}
catch (Exception ex)
{
EventHubsEventSource.Log.AmqpConsumerLinkCreateError(EventHubName, consumerGroup, partitionId, ownerLevelLog, eventPositionLog, ex.Message, linkIdentifier);
throw;
}
finally
{
EventHubsEventSource.Log.AmqpConsumerLinkCreateComplete(EventHubName, consumerGroup, partitionId, ownerLevelLog, eventPositionLog, linkIdentifier);
}
}
/// <summary>
/// Opens an AMQP link for use with producer operations.
/// </summary>
///
/// <param name="partitionId">The identifier of the Event Hub partition to which the link should be bound; if unbound, <c>null</c>.</param>
/// <param name="features">The set of features which are active for the producer requesting the link.</param>
/// <param name="options">The set of options to consider when creating the link.</param>
/// <param name="operationTimeout">The amount of time to allow for an AMQP operation using the link to complete before attempting to cancel it.</param>
/// <param name="linkTimeout">The timeout to apply for creating the link.</param>
/// <param name="linkIdentifier">The identifier to assign to the link; if <c>null</c> or <see cref="string.Empty" />, a random identifier will be generated.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>A link for use with producer operations.</returns>
///
public virtual async Task<SendingAmqpLink> OpenProducerLinkAsync(string partitionId,
TransportProducerFeatures features,
PartitionPublishingOptions options,
TimeSpan operationTimeout,
TimeSpan linkTimeout,
string linkIdentifier,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(_disposed, nameof(AmqpConnectionScope));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var featuresLog = features.ToString();
try
{
EventHubsEventSource.Log.AmqpProducerLinkCreateStart(EventHubName, partitionId, featuresLog, linkIdentifier);
var stopWatch = ValueStopwatch.StartNew();
var path = (string.IsNullOrEmpty(partitionId)) ? EventHubName : string.Format(CultureInfo.InvariantCulture, PartitionProducerPathSuffixMask, EventHubName, partitionId);
var producerEndpoint = new Uri(ServiceEndpoint, path);
if (!ActiveConnection.TryGetOpenedObject(out var connection))
{
connection = await ActiveConnection.GetOrCreateAsync(linkTimeout, cancellationToken).ConfigureAwait(false);
}
if (string.IsNullOrEmpty(linkIdentifier))
{
linkIdentifier = Guid.NewGuid().ToString();
}
var link = await CreateSendingLinkAsync(connection, producerEndpoint, features, options, operationTimeout, linkTimeout.CalculateRemaining(stopWatch.GetElapsedTime()), linkIdentifier, cancellationToken).ConfigureAwait(false);
await OpenAmqpObjectAsync(link, cancellationToken: cancellationToken).ConfigureAwait(false);
return link;
}
catch (Exception ex)
{
EventHubsEventSource.Log.AmqpProducerLinkCreateError(EventHubName, partitionId, featuresLog, ex.Message, linkIdentifier);
throw;
}
finally
{
EventHubsEventSource.Log.AmqpProducerLinkCreateComplete(EventHubName, partitionId, featuresLog, linkIdentifier);
}
}
/// <summary>
/// Performs the task needed to clean up resources used by the <see cref="AmqpConnectionScope" />,
/// including ensuring that the client itself has been closed.
/// </summary>
///
public void Dispose()
{
if (IsDisposed)
{
return;
}
ActiveConnection?.Dispose();
OperationCancellationSource.Cancel();
OperationCancellationSource.Dispose();
IsDisposed = true;
}
/// <summary>
/// Creates an AMQP connection for a given scope.
/// </summary>
///
/// <param name="amqpVersion">The version of AMQP to use for the connection.</param>
/// <param name="serviceEndpoint">The endpoint for the Event Hubs service to which the scope is associated.</param>
/// <param name="connectionEndpoint">The endpoint to used establishing a connection to the Event Hubs service to which the scope is associated.</param>
/// <param name="transportType">The type of transport to use for communication.</param>
/// <param name="proxy">The proxy, if any, to use for communication.</param>
/// <param name="sendBufferSizeBytes">The size, in bytes, of the buffer to use for sending via the transport.</param>
/// <param name="receiveBufferSizeBytes">The size, in bytes, of the buffer to use for receiving from the transport.</param>
/// <param name="certificateValidationCallback">The validation callback to register for participation in the SSL handshake.</param>
/// <param name="scopeIdentifier">The unique identifier for the associated scope.</param>
/// <param name="timeout">The timeout to consider when creating the connection.</param>
///
/// <returns>An AMQP connection that may be used for communicating with the Event Hubs service.</returns>
///
protected virtual async Task<AmqpConnection> CreateAndOpenConnectionAsync(Version amqpVersion,
Uri serviceEndpoint,
Uri connectionEndpoint,
EventHubsTransportType transportType,
IWebProxy proxy,
int sendBufferSizeBytes,
int receiveBufferSizeBytes,
RemoteCertificateValidationCallback certificateValidationCallback,
string scopeIdentifier,
TimeSpan timeout)
{
var serviceEndpointLog = serviceEndpoint.AbsoluteUri;
var transportTypeLog = transportType.ToString();
EventHubsEventSource.Log.AmqpConnectionCreateStart(serviceEndpointLog, transportTypeLog);
try
{
var amqpSettings = CreateAmpqSettings(AmqpVersion);
var connectionSetings = CreateAmqpConnectionSettings(serviceEndpoint.Host, scopeIdentifier, ConnectionIdleTimeoutMilliseconds);
var transportSettings = transportType.IsWebSocketTransport()
? CreateTransportSettingsForWebSockets(connectionEndpoint, proxy, sendBufferSizeBytes, receiveBufferSizeBytes)
: CreateTransportSettingsforTcp(connectionEndpoint, sendBufferSizeBytes, receiveBufferSizeBytes, certificateValidationCallback);
// Create and open the connection, respecting the timeout constraint
// that was received.
var stopWatch = ValueStopwatch.StartNew();
var initiator = new AmqpTransportInitiator(amqpSettings, transportSettings);
var transport = await initiator.ConnectTaskAsync(timeout).ConfigureAwait(false);
var connection = new AmqpConnection(transport, amqpSettings, connectionSetings);
await OpenAmqpObjectAsync(connection, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);
// Create the CBS link that will be used for authorization. The act of creating the link will associate
// it with the connection.
_ = new AmqpCbsLink(connection);
// When the connection is closed, close each of the links associated with it.
EventHandler closeHandler = null;
closeHandler = (snd, args) =>
{
foreach (var link in ActiveLinks.Keys)
{
link.SafeClose();
}
connection.Closed -= closeHandler;
};
connection.Closed += closeHandler;
return connection;
}
catch (Exception ex)
{
EventHubsEventSource.Log.AmqpConnectionCreateStartError(serviceEndpointLog, transportTypeLog, ex.Message);
throw;
}
finally
{
EventHubsEventSource.Log.AmqpConnectionCreateComplete(serviceEndpointLog, transportTypeLog);
}
}
/// <summary>
/// Creates an AMQP link for use with management operations.
/// </summary>
///
/// <param name="connection">The active and opened AMQP connection to use for this link.</param>
/// <param name="operationTimeout">The amount of time to allow for an AMQP operation using the link to complete before attempting to cancel it.</param>
/// <param name="linkTimeout">The timeout to apply for creating the link.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>A link for use with management operations.</returns>
///
protected virtual async Task<RequestResponseAmqpLink> CreateManagementLinkAsync(AmqpConnection connection,
TimeSpan operationTimeout,
TimeSpan linkTimeout,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope));;
var session = default(AmqpSession);
var link = default(RequestResponseAmqpLink);
try
{
// Create and open the AMQP session associated with the link.
var sessionSettings = new AmqpSessionSettings { Properties = new Fields() };
session = connection.CreateSession(sessionSettings);
await OpenAmqpObjectAsync(session, cancellationToken: cancellationToken).ConfigureAwait(false);
// Create and open the link.
var linkSettings = new AmqpLinkSettings { OperationTimeout = operationTimeout };
linkSettings.AddProperty(AmqpProperty.Timeout, (uint)linkTimeout.TotalMilliseconds);
link = new RequestResponseAmqpLink(AmqpManagement.LinkType, session, AmqpManagement.Address, linkSettings.Properties);
// Track the link before returning it, so that it can be managed with the scope.
StartTrackingLinkAsActive(link);
return link;
}
catch
{
// Closing the session will perform any necessary cleanup of
// the associated link as well.
StopTrackingLinkAsActive(link);
session?.SafeClose();
throw;
}
}
/// <summary>
/// Creates an AMQP link for use with receiving operations.
/// </summary>
///
/// <param name="connection">The active and opened AMQP connection to use for this link.</param>
/// <param name="endpoint">The fully qualified endpoint to open the link for.</param>
/// <param name="operationTimeout">The amount of time to allow for an AMQP operation using the link to complete before attempting to cancel it.</param>
/// <param name="linkTimeout">The timeout to apply for creating the link.</param>
/// <param name="eventPosition">The position of the event in the partition where the link should be filtered to.</param>
/// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whether an operation was requested.</param>
/// <param name="prefetchSizeInBytes">The cache size of the prefetch queue. When set, the link makes a best effort to ensure prefetched messages fit into the specified size.</param>
/// <param name="ownerLevel">The relative priority to associate with the link; for a non-exclusive link, this value should be <c>null</c>.</param>
/// <param name="trackLastEnqueuedEventProperties">Indicates whether information on the last enqueued event on the partition is sent as events are received.</param>
/// <param name="linkIdentifier">The identifier to assign to the link; this is assumed to be a non-null value.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>A link for use for operations related to receiving events.</returns>
///
protected virtual async Task<ReceivingAmqpLink> CreateReceivingLinkAsync(AmqpConnection connection,
Uri endpoint,
EventPosition eventPosition,
TimeSpan operationTimeout,
TimeSpan linkTimeout,
uint prefetchCount,
long? prefetchSizeInBytes,
long? ownerLevel,
bool trackLastEnqueuedEventProperties,
string linkIdentifier,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var session = default(AmqpSession);
var link = default(ReceivingAmqpLink);
var refreshTimer = default(Timer);
try
{
// Perform the initial authorization for the link.
var authClaims = new[] { EventHubsClaim.Listen };
var authExpirationUtc = await RequestAuthorizationUsingCbsAsync(connection, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, linkTimeout).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// Create and open the AMQP session associated with the link.
var sessionSettings = new AmqpSessionSettings { Properties = new Fields() };
session = connection.CreateSession(sessionSettings);
await OpenAmqpObjectAsync(session, cancellationToken: cancellationToken).ConfigureAwait(false);
// Create and open the link.
var filters = new FilterSet();
filters.Add(AmqpFilter.ConsumerFilterName, AmqpFilter.CreateConsumerFilter(AmqpFilter.BuildFilterExpression(eventPosition)));
var linkSettings = new AmqpLinkSettings
{
Role = true,
TotalLinkCredit = prefetchCount,
AutoSendFlow = prefetchCount > 0,
SettleType = SettleMode.SettleOnSend,
Source = new Source { Address = endpoint.AbsolutePath, FilterSet = filters },
Target = new Target { Address = linkIdentifier },
TotalCacheSizeInBytes = prefetchSizeInBytes,
OperationTimeout = operationTimeout
};
linkSettings.AddProperty(AmqpProperty.EntityType, (int)AmqpProperty.Entity.ConsumerGroup);
if (ownerLevel.HasValue)
{
linkSettings.AddProperty(AmqpProperty.ConsumerOwnerLevel, ownerLevel.Value);
}
if (linkIdentifier != null)
{
linkSettings.AddProperty(AmqpProperty.ConsumerIdentifier, linkIdentifier);
}
linkSettings.DesiredCapabilities ??= new Multiple<AmqpSymbol>();
linkSettings.DesiredCapabilities.Add(AmqpProperty.GeoReplication);
if (trackLastEnqueuedEventProperties)
{
linkSettings.DesiredCapabilities ??= new Multiple<AmqpSymbol>();
linkSettings.DesiredCapabilities.Add(AmqpProperty.TrackLastEnqueuedEventProperties);
}
link = new ReceivingAmqpLink(linkSettings);
linkSettings.LinkName = $"{ Id };{ connection.Identifier }:{ session.Identifier }:{ link.Identifier }";
link.AttachTo(session);
// Configure refresh for authorization of the link.
var refreshHandler = CreateAuthorizationRefreshHandler
(
connection,
link,
TokenProvider,
endpoint,
endpoint.AbsoluteUri,
endpoint.AbsoluteUri,
authClaims,
AuthorizationRefreshTimeout,
() => (ActiveLinks.ContainsKey(link) ? refreshTimer : null)
);
refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.InfiniteTimeSpan);
// Track the link before returning it, so that it can be managed with the scope.
StartTrackingLinkAsActive(link, refreshTimer);
return link;
}
catch
{
// Closing the session will perform any necessary cleanup of
// the associated link as well.
StopTrackingLinkAsActive(link, refreshTimer);
session?.SafeClose();
throw;
}
}
/// <summary>
/// Creates an AMQP link for use with publishing operations.
/// </summary>
///
/// <param name="connection">The active and opened AMQP connection to use for this link.</param>
/// <param name="endpoint">The fully qualified endpoint to open the link for.</param>
/// <param name="features">The set of features which are active for the producer for which the link is being created.</param>
/// <param name="options">The set of options to consider when creating the link.</param>
/// <param name="operationTimeout">The amount of time to allow for an AMQP operation using the link to complete before attempting to cancel it.</param>
/// <param name="linkTimeout">The timeout to apply for creating the link.</param>
/// <param name="linkIdentifier">The identifier to assign to the link; this is assumed to be a non-null value.</param>
/// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
///
/// <returns>A link for use for operations related to receiving events.</returns>
///
protected virtual async Task<SendingAmqpLink> CreateSendingLinkAsync(AmqpConnection connection,
Uri endpoint,
TransportProducerFeatures features,
PartitionPublishingOptions options,
TimeSpan operationTimeout,
TimeSpan linkTimeout,
string linkIdentifier,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var session = default(AmqpSession);
var link = default(SendingAmqpLink);
var refreshTimer = default(Timer);
try
{
var stopWatch = ValueStopwatch.StartNew();
// Perform the initial authorization for the link.
var authClaims = new[] { EventHubsClaim.Send };
var authExpirationUtc = await RequestAuthorizationUsingCbsAsync(connection, TokenProvider, endpoint, endpoint.AbsoluteUri, endpoint.AbsoluteUri, authClaims, linkTimeout).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// Create and open the AMQP session associated with the link.
var sessionSettings = new AmqpSessionSettings { Properties = new Fields() };
session = connection.CreateSession(sessionSettings);
await OpenAmqpObjectAsync(session, cancellationToken: cancellationToken).ConfigureAwait(false);
// Create and open the link.
var linkSettings = new AmqpLinkSettings
{
Role = false,
InitialDeliveryCount = 0,
Source = new Source { Address = linkIdentifier },
Target = new Target { Address = endpoint.AbsolutePath },
OperationTimeout = operationTimeout
};
linkSettings.AddProperty(AmqpProperty.Timeout, (uint)linkTimeout.CalculateRemaining(stopWatch.GetElapsedTime()).TotalMilliseconds);
linkSettings.AddProperty(AmqpProperty.EntityType, (int)AmqpProperty.Entity.EventHub);
linkSettings.DesiredCapabilities ??= new Multiple<AmqpSymbol>();
linkSettings.DesiredCapabilities.Add(AmqpProperty.GeoReplication);
if ((features & TransportProducerFeatures.IdempotentPublishing) != 0)
{
linkSettings.DesiredCapabilities ??= new Multiple<AmqpSymbol>();
linkSettings.DesiredCapabilities.Add(AmqpProperty.EnableIdempotentPublishing);
}
// If any of the options have a value, the entire set must be specified for the link settings. For any options that did not have a
// value, specifying null will signal the service to generate the value.
if ((options.ProducerGroupId.HasValue) || (options.OwnerLevel.HasValue) || (options.StartingSequenceNumber.HasValue))
{
linkSettings.AddProperty(AmqpProperty.ProducerGroupId, options.ProducerGroupId);
linkSettings.AddProperty(AmqpProperty.ProducerOwnerLevel, options.OwnerLevel);
linkSettings.AddProperty(AmqpProperty.ProducerSequenceNumber, options.StartingSequenceNumber);
}
link = new SendingAmqpLink(linkSettings);
linkSettings.LinkName = $"{ Id };{ connection.Identifier }:{ session.Identifier }:{ link.Identifier }";
link.AttachTo(session);
// Configure refresh for authorization of the link.
var refreshHandler = CreateAuthorizationRefreshHandler
(
connection,
link,
TokenProvider,
endpoint,
endpoint.AbsoluteUri,
endpoint.AbsoluteUri,
authClaims,
AuthorizationRefreshTimeout,
() => refreshTimer
);
refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.InfiniteTimeSpan);
// Track the link before returning it, so that it can be managed with the scope.
StartTrackingLinkAsActive(link, refreshTimer);
return link;
}
catch
{
// Closing the session will perform any necessary cleanup of
// the associated link as well.
StopTrackingLinkAsActive(link, refreshTimer);
session?.SafeClose();
throw;
}
}
/// <summary>
/// Performs the actions needed to configure and begin tracking the specified AMQP
/// link as an active link bound to this scope.
/// </summary>
///
/// <param name="link">The link to begin tracking.</param>
/// <param name="authorizationRefreshTimer">The timer used to manage refreshing authorization, if the link requires it.</param>
///
/// <remarks>
/// This method operates on the specified <paramref name="link"/> in order to configure it
/// for active tracking; no assumptions are made about the open/connected state of the link nor are
/// its communication properties modified.
/// </remarks>
///
protected virtual void StartTrackingLinkAsActive(AmqpObject link,
Timer authorizationRefreshTimer = null)
{
// Register the link as active and having authorization automatically refreshed, so that it can be
// managed with the scope.
if (!ActiveLinks.TryAdd(link, authorizationRefreshTimer))
{
throw new EventHubsException(true, EventHubName, Resources.CouldNotCreateLink);
}
// When the link is closed, stop refreshing authorization and remove it from the
// set of associated links.
var closeHandler = default(EventHandler);
closeHandler = (snd, args) =>
{
StopTrackingLinkAsActive(link);
link.Closed -= closeHandler;
};
link.Closed += closeHandler;
}
/// <summary>
/// Performs the actions needed to stop tracking the specified AMQP
/// link as an active link bound to this scope.
/// </summary>
///
/// <param name="link">The link to stop tracking.</param>
/// <param name="authorizationRefreshTimer">The timer used to manage refreshing authorization, if the link requires it.</param>
///
/// <remarks>
/// This method operates on the specified <paramref name="link"/> in order to remove it
/// from active tracking; no assumptions are made about the open/connected state of the link nor are
/// its communication properties modified.
/// </remarks>
///
protected virtual void StopTrackingLinkAsActive(AmqpObject link,
Timer authorizationRefreshTimer = null)
{
var activeTimer = default(Timer);
if (link != null)
{
ActiveLinks.TryRemove(link, out activeTimer);
if (activeTimer != null)
{
try
{
activeTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
activeTimer.Dispose();
}
catch (ObjectDisposedException)
{
}
}
}
// If the refresh timer was created but not associated with the link, then it will need
// to be cleaned up.
if ((authorizationRefreshTimer != null) && (!ReferenceEquals(authorizationRefreshTimer, activeTimer)))
{
try
{
authorizationRefreshTimer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
authorizationRefreshTimer.Dispose();
}
catch (ObjectDisposedException)
{
}
}
}
/// <summary>
/// Performs the tasks needed to close a connection.
/// </summary>
///
/// <param name="connection">The connection to close.</param>
///
protected virtual void CloseConnection(AmqpConnection connection)
{
connection.SafeClose();
EventHubsEventSource.Log.FaultTolerantAmqpObjectClose(nameof(AmqpConnection), "", EventHubName, "", "", connection.TerminalException?.Message);
}
/// <summary>
/// Calculates the interval after which authorization for an AMQP link should be
/// refreshed.
/// </summary>
///
/// <param name="expirationTimeUtc">The date/time, in UTC, that the current authorization is expected to expire.</param>
/// <param name="currentTimeUtc">The current date/time, in UTC. If not specified, the system time will be used.</param>
///
/// <returns>The interval after which authorization should be refreshed.</returns>
///
protected virtual TimeSpan CalculateLinkAuthorizationRefreshInterval(DateTime expirationTimeUtc,
DateTime? currentTimeUtc = null)
{
currentTimeUtc ??= DateTime.UtcNow;
// Calculate the interval for when refreshing authorization should take place;
// the refresh is based on the time that the credential expires, less a buffer to
// allow for clock skew. A random number of seconds is added as jitter, to prevent
// multiple resources using the same token from all requesting a refresh at the same moment.
var refreshDueInterval = expirationTimeUtc
.Subtract(AuthorizationRefreshBuffer)
.Subtract(currentTimeUtc.Value)
.Subtract(TimeSpan.FromSeconds(RandomNumberGenerator.Value.NextDouble() * AuthorizationBaseJitterSeconds));
return refreshDueInterval switch
{
_ when (refreshDueInterval < MinimumAuthorizationRefresh) => MinimumAuthorizationRefresh,
_ when (refreshDueInterval > MaximumAuthorizationRefresh) => MaximumAuthorizationRefresh,