-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
AmqpConnectionScope.cs
1457 lines (1260 loc) · 67.3 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.Diagnostics;
using System.Globalization;
using System.Net;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Diagnostics;
using Azure.Messaging.ServiceBus.Authorization;
using Azure.Messaging.ServiceBus.Core;
using Azure.Messaging.ServiceBus.Diagnostics;
using Microsoft.Azure.Amqp;
using Microsoft.Azure.Amqp.Framing;
using Microsoft.Azure.Amqp.Sasl;
using Microsoft.Azure.Amqp.Transaction;
using Microsoft.Azure.Amqp.Transport;
namespace Azure.Messaging.ServiceBus.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 : TransportConnectionScope
{
/// <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 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 number of milliseconds to use as the basis for calculating a random jitter amount
/// when opening receiver links. This is intended to ensure that multiple
/// accept session operations don't timeout at the same exact moment.
/// </summary>
private static int OpenReceiveLinkBaseJitterMilliseconds { get; } = 100;
/// <summary>
/// The amount of time to subtract from the client timeout when setting the server timeout when attempting to
/// accept the next available session. This will decrease the likelihood that the client times out before receiving a
/// response from the server.
/// </summary>
private static TimeSpan OpenReceiveLinkBuffer { get; } = TimeSpan.FromMilliseconds(20);
/// <summary>
/// The amount minimum threshold for the server timeout for which we will subtract the <see cref="OpenReceiveLinkBuffer"/>.
/// If the server timeout is less than this, we will not subtract the additional buffer.
/// </summary>
private static TimeSpan OpenReceiveLinkBufferThreshold { get; } = TimeSpan.FromSeconds(1);
/// <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>
/// Indicates whether this <see cref="AmqpConnectionScope"/> has been disposed.
/// </summary>
///
/// <value><c>true</c> if disposed; otherwise, <c>false</c>.</value>
///
public override bool IsDisposed
{
get => _disposed;
protected set => _disposed = value;
}
/// <summary>
/// The cancellation token to use with operations initiated by the scope.
/// </summary>
private CancellationTokenSource OperationCancellationSource { get; } = new();
/// <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();
/// <summary>
/// The unique identifier of the scope.
/// </summary>
private string Id { get; }
/// <summary>
/// The endpoint for the Service Bus service to which the scope is associated.
/// </summary>
private Uri ServiceEndpoint { get; }
/// <summary>
/// The provider to use for obtaining a token for authorization with the Service Bus service.
/// </summary>
private CbsTokenProvider TokenProvider { get; }
/// <summary>
/// The type of transport to use for communication.
/// </summary>
private ServiceBusTransportType Transport { get; }
/// <summary>
/// The proxy, if any, which should be used for communication.
/// </summary>
private IWebProxy Proxy { get; }
/// <summary>
/// The AMQP connection that is active for the current scope.
/// </summary>
private FaultTolerantAmqpObject<AmqpConnection> ActiveConnection { get; }
/// <summary>
/// The controller responsible for managing transactions.
/// </summary>
internal FaultTolerantAmqpObject<Controller> TransactionController { get; }
private readonly bool _useSingleSession;
private readonly FaultTolerantAmqpObject<AmqpSession> _singletonSession;
private string _sendViaReceiverEntityPath;
private readonly object _syncLock = new();
private readonly TimeSpan _operationTimeout;
private readonly uint _connectionIdleTimeoutMilliseconds;
/// <summary>
/// Initializes a new instance of the <see cref="AmqpConnectionScope"/> class.
/// </summary>
/// <param name="serviceEndpoint">Endpoint for the Service Bus service to which the scope is associated.</param>
/// <param name="connectionEndpoint">The endpoint to use for the initial connection to the Service Bus service.</param>
/// <param name="credential">The credential to use for authorization with the Service Bus 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="useSingleSession">If true, all links will use a single session.</param>
/// <param name="operationTimeout">The timeout for operations associated with the connection.</param>
/// <param name="idleTimeout">The amount of time to allow a connection to have no observed traffic before considering it idle.</param>
public AmqpConnectionScope(
Uri serviceEndpoint,
Uri connectionEndpoint,
ServiceBusTokenCredential credential,
ServiceBusTransportType transport,
IWebProxy proxy,
bool useSingleSession,
TimeSpan operationTimeout,
TimeSpan idleTimeout)
{
Argument.AssertNotNull(serviceEndpoint, nameof(serviceEndpoint));
Argument.AssertNotNull(credential, nameof(credential));
Argument.AssertNotNegative(idleTimeout, nameof(idleTimeout));
ValidateTransport(transport);
_operationTimeout = operationTimeout;
_connectionIdleTimeoutMilliseconds = (uint)idleTimeout.TotalMilliseconds;
ServiceEndpoint = serviceEndpoint;
Transport = transport;
Proxy = proxy;
Id = $"{ServiceEndpoint}-{Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture).Substring(0, 8)}";
TokenProvider = new CbsTokenProvider(new ServiceBusTokenCredential(credential), AuthorizationTokenExpirationBuffer, OperationCancellationSource.Token);
_useSingleSession = useSingleSession;
#pragma warning disable CA2214 // Do not call overridable methods in constructors. This internal method is virtual for testing purposes.
Task<AmqpConnection> connectionFactory(TimeSpan timeout) => CreateAndOpenConnectionAsync(AmqpVersion, ServiceEndpoint, connectionEndpoint, Transport, Proxy, Id, timeout);
#pragma warning restore CA2214 // Do not call overridable methods in constructors
ActiveConnection = new FaultTolerantAmqpObject<AmqpConnection>(
connectionFactory,
CloseConnection);
_singletonSession = new FaultTolerantAmqpObject<AmqpSession>(
async (timeout) =>
{
var stopWatch = ValueStopwatch.StartNew();
AmqpConnection connection = await ActiveConnection.GetOrCreateAsync(timeout).ConfigureAwait(false);
AmqpSession session = await CreateAndOpenSessionAsync(
connection,
timeout.CalculateRemaining(stopWatch.GetElapsedTime()))
.ConfigureAwait(false);
// When using cross entity transactions, the controller needs to be opened before the link is established
// in order to let the service know that there will be cross entity transactions on this session. We can't
// wait until a transaction is declared to open the controller.
_ = await CreateControllerAsync(session, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);
return session;
},
session => session.Close());
TransactionController = new FaultTolerantAmqpObject<Controller>(
async (timeout) =>
{
var stopWatch = ValueStopwatch.StartNew();
AmqpConnection connection = await ActiveConnection.GetOrCreateAsync(timeout).ConfigureAwait(false);
AmqpSession session = await CreateSessionIfNeededAsync(connection, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);
return await CreateControllerAsync(session, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);
},
controller => controller.Close());
}
private async Task<Controller> CreateControllerAsync(AmqpSession amqpSession, TimeSpan timeout)
{
var stopWatch = ValueStopwatch.StartNew();
Controller controller;
try
{
controller = new Controller(amqpSession, timeout);
await controller.OpenAsync(timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);
}
catch (Exception exception)
{
if (amqpSession != null)
{
await amqpSession.CloseAsync(timeout).ConfigureAwait(false);
}
ServiceBusEventSource.Log.CreateControllerException(ActiveConnection.ToString(), exception.ToString());
throw;
}
return controller;
}
/// <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="entityPath">The path for the entity.</param>
/// <param name="identifier">The identifier for the sender or receiver that is opening a management link.</param>
/// <param name="timeout">The timeout to apply when 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(
string entityPath,
string identifier,
TimeSpan timeout,
CancellationToken cancellationToken)
{
ServiceBusEventSource.Log.CreateManagementLinkStart(identifier);
try
{
Argument.AssertNotDisposed(_disposed, nameof(AmqpConnectionScope));
var stopWatch = ValueStopwatch.StartNew();
var connection = await ActiveConnection.GetOrCreateAsync(timeout, cancellationToken).ConfigureAwait(false);
var link = await CreateManagementLinkAsync(
entityPath,
identifier,
connection,
timeout.CalculateRemaining(stopWatch.GetElapsedTime()),
cancellationToken).ConfigureAwait(false);
await OpenAmqpLinkAsync(link, entityPath, cancellationToken: cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
ServiceBusEventSource.Log.CreateManagementLinkComplete(identifier);
return link;
}
catch (Exception ex)
{
ServiceBusEventSource.Log.CreateManagementLinkException(identifier, ex.ToString());
throw;
}
}
/// <summary>
/// Opens an AMQP link for use with receiver operations.
/// </summary>
/// <param name="identifier">The identifier of the entity that is receiving.</param>
/// <param name="entityPath">The entity path to receive from.</param>
/// <param name="timeout">The timeout to apply when 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="receiveMode">The <see cref="ServiceBusReceiveMode"/> used to specify how messages are received. Defaults to PeekLock mode.</param>
/// <param name="sessionId">The session to connect to.</param>
/// <param name="isSessionReceiver">Whether or not this is a sessionful receiver.</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> OpenReceiverLinkAsync(
string identifier,
string entityPath,
TimeSpan timeout,
uint prefetchCount,
ServiceBusReceiveMode receiveMode,
string sessionId,
bool isSessionReceiver,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(_disposed, nameof(AmqpConnectionScope));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var stopWatch = ValueStopwatch.StartNew();
var receiverEndpoint = new Uri(ServiceEndpoint, entityPath);
var connection = await ActiveConnection.GetOrCreateAsync(timeout, cancellationToken).ConfigureAwait(false);
ReceivingAmqpLink link = await CreateReceivingLinkAsync(
entityPath: entityPath,
identifier: identifier,
connection: connection,
endpoint: receiverEndpoint,
timeout: timeout.CalculateRemaining(stopWatch.GetElapsedTime()),
prefetchCount: prefetchCount,
receiveMode: receiveMode,
sessionId: sessionId,
isSessionReceiver: isSessionReceiver,
cancellationToken: cancellationToken
).ConfigureAwait(false);
await OpenAmqpLinkAsync(link, entityPath, cancellationToken: cancellationToken).ConfigureAwait(false);
return link;
}
/// <summary>
/// Opens an AMQP link for use with sender operations.
/// </summary>
/// <param name="entityPath"></param>
/// <param name="identifier">The identifier for the sender that is opening a send link.</param>
/// <param name="timeout">The timeout to apply when 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 sender operations.</returns>
///
public virtual async Task<SendingAmqpLink> OpenSenderLinkAsync(
string entityPath,
string identifier,
TimeSpan timeout,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(_disposed, nameof(AmqpConnectionScope));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var stopWatch = ValueStopwatch.StartNew();
AmqpConnection connection = await ActiveConnection.GetOrCreateAsync(timeout, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
SendingAmqpLink link = await CreateSendingLinkAsync(
entityPath: entityPath,
identifier: identifier,
connection: connection,
timeout: timeout.CalculateRemaining(stopWatch.GetElapsedTime()),
cancellationToken: cancellationToken).ConfigureAwait(false);
await OpenAmqpLinkAsync(link, entityPath, cancellationToken).ConfigureAwait(false);
return link;
}
/// <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 override void Dispose()
{
if (IsDisposed)
{
return;
}
ActiveConnection?.Dispose();
OperationCancellationSource.Cancel();
OperationCancellationSource.Dispose();
_singletonSession?.Dispose();
TransactionController?.Dispose();
TokenProvider.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 Service Bus service to which the scope is associated.</param>
/// <param name="connectionEndpoint">The endpoint to use for the initial connection to the Service Bus service.</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="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 Service Bus service.</returns>
protected virtual async Task<AmqpConnection> CreateAndOpenConnectionAsync(
Version amqpVersion,
Uri serviceEndpoint,
Uri connectionEndpoint,
ServiceBusTransportType transportType,
IWebProxy proxy,
string scopeIdentifier,
TimeSpan timeout)
{
var serviceHostName = serviceEndpoint.Host;
AmqpSettings amqpSettings = CreateAmpqSettings(AmqpVersion);
AmqpConnectionSettings connectionSetings = CreateAmqpConnectionSettings(serviceHostName, scopeIdentifier, _connectionIdleTimeoutMilliseconds);
TransportSettings transportSettings = transportType.IsWebSocketTransport()
? CreateTransportSettingsForWebSockets(connectionEndpoint, proxy)
: CreateTransportSettingsforTcp(connectionEndpoint);
// Create and open the connection, respecting the timeout constraint
// that was received.
var stopWatch = ValueStopwatch.StartNew();
var initiator = new AmqpTransportInitiator(amqpSettings, transportSettings);
TransportBase 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.
#pragma warning disable CA1806 // Do not ignore method results
new AmqpCbsLink(connection);
#pragma warning restore CA1806 // Do not ignore method results
// 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;
}
/// <summary>
/// Creates an AMQP link for use with management operations.
/// </summary>
/// <param name="entityPath"></param>
/// <param name="identifier">The identifier for the sender or receiver that is opening a management link.</param>
/// <param name="connection">The active and opened AMQP connection to use for this link.</param>
/// <param name="timeout">The timeout to apply when 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(
string entityPath,
string identifier,
AmqpConnection connection,
TimeSpan timeout,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var session = default(AmqpSession);
var refreshTimer = default(Timer);
var stopWatch = ValueStopwatch.StartNew();
RequestResponseAmqpLink link = null;
try
{
// Create and open the AMQP session associated with the link.
session = await CreateSessionIfNeededAsync(connection, timeout).ConfigureAwait(false);
// Create and open the link.
var linkSettings = new AmqpLinkSettings();
linkSettings.AddProperty(AmqpClientConstants.TimeoutName, (uint)timeout.CalculateRemaining(stopWatch.GetElapsedTime()).TotalMilliseconds);
linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, AmqpClientConstants.EntityTypeManagement);
linkSettings.OperationTimeout = _operationTimeout;
entityPath += '/' + AmqpClientConstants.ManagementAddress;
// Perform the initial authorization for the link.
string[] claims = { ServiceBusClaim.Manage, ServiceBusClaim.Listen, ServiceBusClaim.Send };
var endpoint = new Uri(ServiceEndpoint, entityPath);
var audience = new[] { endpoint.AbsoluteUri };
DateTime authExpirationUtc = await RequestAuthorizationUsingCbsAsync(
connection: connection,
tokenProvider: TokenProvider,
endpoint: ServiceEndpoint,
audience: audience,
requiredClaims: claims,
timeout: timeout.CalculateRemaining(stopWatch.GetElapsedTime()),
identifier: identifier)
.ConfigureAwait(false);
link = new RequestResponseAmqpLink(
AmqpClientConstants.EntityTypeManagement,
session,
entityPath,
linkSettings.Properties);
linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{session.Identifier}:{link.Identifier}";
// Track the link before returning it, so that it can be managed with the scope.
TimerCallback refreshHandler = CreateAuthorizationRefreshHandler
(
entityPath: entityPath,
connection: connection,
amqpLink: link,
tokenProvider: TokenProvider,
endpoint: ServiceEndpoint,
audience: audience,
requiredClaims: claims,
refreshTimeout: AuthorizationRefreshTimeout,
refreshTimerFactory: () => (ActiveLinks.ContainsKey(link) ? refreshTimer : null),
identifier: identifier);
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(entityPath, link, refreshTimer);
return link;
}
catch (Exception exception)
{
StopTrackingLinkAsActive(link, refreshTimer);
// Closing the session will perform any necessary cleanup of
// the associated link as well.
session?.SafeClose();
ExceptionDispatchInfo.Capture(AmqpExceptionHelper.TranslateException(
exception,
null,
session.GetInnerException(),
connection.IsClosing()))
.Throw();
throw; // will never be reached
}
}
/// <summary>
/// Creates an AMQP link for use with receiving operations.
/// </summary>
/// <param name="entityPath">The entity path to receive from.</param>
/// <param name="identifier">The identifier for the receiver that is creating a receive link.</param>
/// <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="timeout">The timeout to apply when 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="receiveMode">The <see cref="ServiceBusReceiveMode"/> used to specify how messages are received. Defaults to PeekLock mode.</param>
/// <param name="sessionId">The session to receive from.</param>
/// <param name="isSessionReceiver">Whether or not this is a sessionful receiver.</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(
string entityPath,
string identifier,
AmqpConnection connection,
Uri endpoint,
TimeSpan timeout,
uint prefetchCount,
ServiceBusReceiveMode receiveMode,
string sessionId,
bool isSessionReceiver,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var session = default(AmqpSession);
var refreshTimer = default(Timer);
var stopWatch = ValueStopwatch.StartNew();
ReceivingAmqpLink link = null;
try
{
// Perform the initial authorization for the link.
string[] authClaims = new string[] { ServiceBusClaim.Send };
var audience = new[] { endpoint.AbsoluteUri };
DateTime authExpirationUtc = await RequestAuthorizationUsingCbsAsync(
connection: connection,
tokenProvider: TokenProvider,
endpoint: endpoint,
audience: audience,
requiredClaims: authClaims,
timeout: timeout,
identifier: identifier).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// Create and open the AMQP session associated with the link.
session = await CreateSessionIfNeededAsync(connection, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var filters = new FilterSet();
// even if supplied sessionId is null, we need to add the Session filter if it is a session receiver
if (isSessionReceiver)
{
filters.Add(AmqpClientConstants.SessionFilterName, sessionId);
}
var linkSettings = new AmqpLinkSettings
{
Role = true,
TotalLinkCredit = prefetchCount,
AutoSendFlow = prefetchCount > 0,
SettleType = (receiveMode == ServiceBusReceiveMode.PeekLock) ? SettleMode.SettleOnDispose : SettleMode.SettleOnSend,
Source = new Source { Address = endpoint.AbsolutePath, FilterSet = filters },
Target = new Target { Address = identifier },
OperationTimeout = _operationTimeout
};
if (isSessionReceiver && sessionId == null)
{
// Subtract a random amount up to 100ms from the operation timeout as the jitter when attempting to open next available session link.
// This prevents excessive resource usage when using high amounts of concurrency and accepting the next available session. Without the jitter,
// we can get many timeout exceptions occurring at the exact same time which leads to high CPU usage and thread starvation,
// particularly when using the session processor.
// Take the min of 1% of the total timeout and the BaseJitter amount so that we don't end up subtracting more than 1% of the total timeout.
var jitterBase = Math.Min(_operationTimeout.TotalMilliseconds / 100, OpenReceiveLinkBaseJitterMilliseconds);
// We set the operation timeout on the properties not only to include the jitter, but also because the server will otherwise
// restrict the maximum timeout to 1 minute and 5 seconds, regardless of the client timeout. We only do this for accepting next available
// session as this is the only long-polling scenario.
var serverTimeout = _operationTimeout.Subtract(TimeSpan.FromMilliseconds(jitterBase * RandomNumberGenerator.Value.NextDouble()));
// Subtract an additional constant buffer to reduce the likelihood that the client times out before the service which leads to unnecessary
// network traffic. If the timeout is too short, we won't do this.
if (serverTimeout >= OpenReceiveLinkBufferThreshold)
{
serverTimeout = serverTimeout.Subtract(OpenReceiveLinkBuffer);
}
linkSettings.Properties = new Fields
{
{
AmqpClientConstants.TimeoutName,
(uint)serverTimeout.TotalMilliseconds
}
};
}
link = new ReceivingAmqpLink(linkSettings);
linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{session.Identifier}:{link.Identifier}:{linkSettings.Source.ToString()}";
link.AttachTo(session);
// Configure refresh for authorization of the link.
TimerCallback refreshHandler = CreateAuthorizationRefreshHandler
(
entityPath: entityPath,
connection: connection,
amqpLink: link,
tokenProvider: TokenProvider,
endpoint: endpoint,
audience: audience,
requiredClaims: authClaims,
refreshTimeout: AuthorizationRefreshTimeout,
refreshTimerFactory: () => (ActiveLinks.ContainsKey(link) ? refreshTimer : null),
identifier: identifier);
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(entityPath, link, refreshTimer);
return link;
}
catch (Exception exception)
{
StopTrackingLinkAsActive(link, refreshTimer);
// Closing the session will perform any necessary cleanup of
// the associated link as well.
session?.SafeClose();
ExceptionDispatchInfo.Capture(AmqpExceptionHelper.TranslateException(
exception,
null,
session.GetInnerException(),
connection.IsClosing()))
.Throw();
throw; // will never be reached
}
}
private async Task<AmqpSession> CreateSessionIfNeededAsync(AmqpConnection connection, TimeSpan timeout)
{
if (_useSingleSession)
{
return await _singletonSession.GetOrCreateAsync(timeout).ConfigureAwait(false);
}
return await CreateAndOpenSessionAsync(connection, timeout).ConfigureAwait(false);
}
private async Task<AmqpSession> CreateAndOpenSessionAsync(AmqpConnection connection, TimeSpan timeout)
{
AmqpSession session;
var sessionSettings = new AmqpSessionSettings { Properties = new Fields() };
// This is the maximum number of unsettled transfers across all receive links on this session.
// This will allow the session to accept unlimited number of transfers, even if the receiver(s)
// are not settling any of the deliveries.
sessionSettings.IncomingWindow = uint.MaxValue;
session = connection.CreateSession(sessionSettings);
await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false);
return session;
}
/// <summary>
/// Creates an AMQP link for use with publishing operations.
/// </summary>
/// <param name="entityPath">The entity path to send to.</param>
/// <param name="identifier">The identifier of the sender that is creating a send link.</param>
/// <param name="connection">The active and opened AMQP connection to use for this link.</param>
/// <param name="timeout">The timeout to apply when 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 for operations related to receiving events.</returns>
protected virtual async Task<SendingAmqpLink> CreateSendingLinkAsync(
string entityPath,
string identifier,
AmqpConnection connection,
TimeSpan timeout,
CancellationToken cancellationToken)
{
Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope));
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
var session = default(AmqpSession);
var refreshTimer = default(Timer);
var stopWatch = ValueStopwatch.StartNew();
SendingAmqpLink link = null;
ValidateCanCreateSenderLink(entityPath);
try
{
string[] audience;
Uri destinationEndpoint = null;
destinationEndpoint = new Uri(ServiceEndpoint, entityPath);
audience = new string[] { destinationEndpoint.AbsoluteUri };
// Perform the initial authorization for the link.
var authClaims = new[] { ServiceBusClaim.Send };
DateTime authExpirationUtc = await RequestAuthorizationUsingCbsAsync(
connection: connection,
tokenProvider: TokenProvider,
endpoint: destinationEndpoint,
audience: audience,
requiredClaims: authClaims,
timeout: timeout,
identifier: identifier)
.ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// Create and open the AMQP session associated with the link.
session = await CreateSessionIfNeededAsync(connection, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>();
// Create and open the link.
var linkSettings = new AmqpLinkSettings
{
Role = false,
InitialDeliveryCount = 0,
Source = new Source { Address = identifier },
Target = new Target { Address = destinationEndpoint.AbsolutePath },
OperationTimeout = _operationTimeout,
};
linkSettings.AddProperty(AmqpClientConstants.TimeoutName, (uint)timeout.CalculateRemaining(stopWatch.GetElapsedTime()).TotalMilliseconds);
link = new SendingAmqpLink(linkSettings);
linkSettings.LinkName = $"{Id};{connection.Identifier}:{session.Identifier}:{link.Identifier}";
link.AttachTo(session);
// Configure refresh for authorization of the link.
TimerCallback refreshHandler = CreateAuthorizationRefreshHandler
(
entityPath: entityPath,
connection: connection,
amqpLink: link,
tokenProvider: TokenProvider,
endpoint: destinationEndpoint,
audience: audience,
requiredClaims: authClaims,
refreshTimeout: AuthorizationRefreshTimeout,
refreshTimerFactory: () => refreshTimer,
identifier: identifier
);
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(entityPath, link, refreshTimer);
return link;
}
catch (Exception exception)
{
StopTrackingLinkAsActive(link, refreshTimer);
// Closing the session will perform any necessary cleanup of
// the associated link as well.
session?.SafeClose();
ExceptionDispatchInfo.Capture(AmqpExceptionHelper.TranslateException(
exception,
null,
session.GetInnerException(),
connection.IsClosing()))
.Throw();
throw; // will never be reached
}
}
private void ValidateCanCreateSenderLink(string entityPath)
{
if (_useSingleSession)
{
lock (_syncLock)
{
// The send-via entity is a receiver and there are no active links. We are reconnecting the connection.
if (_sendViaReceiverEntityPath != null && ActiveLinks.IsEmpty)
{
// The sender is not going to the send-via entity path, so we need to ensure the receiver is reconnected first.
if (entityPath != _sendViaReceiverEntityPath)
{
// User code will already need to handle InvalidOperationExceptions for transactions where the connection drops.
// There is no point in attempting to reconnect the receiver here on the user's behalf, as the transaction will
// still fail since the connection dropped.
throw new InvalidOperationException(
string.Format(
CultureInfo.InvariantCulture,
Resources.TransactionReconnectionError,
entityPath,
_sendViaReceiverEntityPath));
}
}
}
}
}
/// <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="entityPath">The entity path for the associated link.</param>
/// <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 does operate 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(
string entityPath,
AmqpObject link,
Timer authorizationRefreshTimer = null)
{
if (_useSingleSession)
{
lock (_syncLock)
{
if (link is ReceivingAmqpLink)
{
// Track the send-via receiver in order to handle reconnecting in the proper order (sender first).
if (_sendViaReceiverEntityPath == null)
{
_sendViaReceiverEntityPath = entityPath;
}
}
}
}
// 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 ServiceBusException(true, entityPath, 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;
}
private 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();
}