| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Collections.Concurrent; |
| | 6 | | using System.Collections.Generic; |
| | 7 | | using System.Globalization; |
| | 8 | | using System.Net; |
| | 9 | | using System.Runtime.ExceptionServices; |
| | 10 | | using System.Threading; |
| | 11 | | using System.Threading.Tasks; |
| | 12 | | using Azure.Core; |
| | 13 | | using Azure.Core.Diagnostics; |
| | 14 | | using Azure.Messaging.ServiceBus.Authorization; |
| | 15 | | using Azure.Messaging.ServiceBus.Core; |
| | 16 | | using Azure.Messaging.ServiceBus.Diagnostics; |
| | 17 | | using Microsoft.Azure.Amqp; |
| | 18 | | using Microsoft.Azure.Amqp.Framing; |
| | 19 | | using Microsoft.Azure.Amqp.Sasl; |
| | 20 | | using Microsoft.Azure.Amqp.Transaction; |
| | 21 | | using Microsoft.Azure.Amqp.Transport; |
| | 22 | |
|
| | 23 | | namespace Azure.Messaging.ServiceBus.Amqp |
| | 24 | | { |
| | 25 | | /// <summary> |
| | 26 | | /// Defines a context for AMQP operations which can be shared amongst the different |
| | 27 | | /// client types within a given scope. |
| | 28 | | /// </summary> |
| | 29 | | /// |
| | 30 | | internal class AmqpConnectionScope : TransportConnectionScope |
| | 31 | | { |
| | 32 | | /// <summary>The name to assign to the SASL handler to specify that CBS tokens are in use.</summary> |
| | 33 | | private const string CbsSaslHandlerName = "MSSBCBS"; |
| | 34 | |
|
| | 35 | | /// <summary>The suffix to attach to the resource path when using web sockets for service communication.</summar |
| | 36 | | private const string WebSocketsPathSuffix = "/$servicebus/websocket/"; |
| | 37 | |
|
| | 38 | | /// <summary>The URI scheme to apply when using web sockets for service communication.</summary> |
| | 39 | | private const string WebSocketsUriScheme = "wss"; |
| | 40 | |
|
| | 41 | | /// <summary> |
| | 42 | | /// The version of AMQP to use within the scope. |
| | 43 | | /// </summary> |
| | 44 | | /// |
| 0 | 45 | | private static Version AmqpVersion { get; } = new Version(1, 0, 0, 0); |
| | 46 | |
|
| | 47 | | /// <summary> |
| | 48 | | /// The amount of time to allow an AMQP connection to be idle before considering |
| | 49 | | /// it to be timed out. |
| | 50 | | /// </summary> |
| | 51 | | /// |
| 0 | 52 | | private static TimeSpan ConnectionIdleTimeout { get; } = TimeSpan.FromMinutes(1); |
| | 53 | |
|
| | 54 | | /// <summary> |
| | 55 | | /// The amount of buffer to apply to account for clock skew when |
| | 56 | | /// refreshing authorization. Authorization will be refreshed earlier |
| | 57 | | /// than the expected expiration by this amount. |
| | 58 | | /// </summary> |
| | 59 | | /// |
| 0 | 60 | | private static TimeSpan AuthorizationRefreshBuffer { get; } = TimeSpan.FromMinutes(5); |
| | 61 | |
|
| | 62 | | /// <summary> |
| | 63 | | /// The minimum amount of time for authorization to be refreshed; any calculations that |
| | 64 | | /// call for refreshing more frequently will be substituted with this value. |
| | 65 | | /// </summary> |
| | 66 | | /// |
| 0 | 67 | | private static TimeSpan MinimumAuthorizationRefresh { get; } = TimeSpan.FromMinutes(4); |
| | 68 | |
|
| | 69 | | /// <summary> |
| | 70 | | /// The amount time to allow to refresh authorization of an AMQP link. |
| | 71 | | /// </summary> |
| | 72 | | /// |
| 0 | 73 | | private static TimeSpan AuthorizationRefreshTimeout { get; } = TimeSpan.FromMinutes(3); |
| | 74 | |
|
| | 75 | | /// <summary> |
| | 76 | | /// Indicates whether this <see cref="AmqpConnectionScope"/> has been disposed. |
| | 77 | | /// </summary> |
| | 78 | | /// |
| | 79 | | /// <value><c>true</c> if disposed; otherwise, <c>false</c>.</value> |
| | 80 | | /// |
| 0 | 81 | | public override bool IsDisposed { get; protected set; } |
| | 82 | |
|
| | 83 | | /// <summary> |
| | 84 | | /// The cancellation token to use with operations initiated by the scope. |
| | 85 | | /// </summary> |
| | 86 | | /// |
| 112 | 87 | | private CancellationTokenSource OperationCancellationSource { get; } = new CancellationTokenSource(); |
| | 88 | |
|
| | 89 | | /// <summary> |
| | 90 | | /// The set of active AMQP links associated with the connection scope. These are considered children |
| | 91 | | /// of the active connection and should be managed as such. |
| | 92 | | /// </summary> |
| | 93 | | /// |
| 0 | 94 | | private ConcurrentDictionary<AmqpObject, Timer> ActiveLinks { get; } = new ConcurrentDictionary<AmqpObject, Time |
| | 95 | |
|
| | 96 | | /// <summary> |
| | 97 | | /// The unique identifier of the scope. |
| | 98 | | /// </summary> |
| | 99 | | /// |
| 0 | 100 | | private string Id { get; } |
| | 101 | |
|
| | 102 | | /// <summary> |
| | 103 | | /// The endpoint for the Service Bus service to which the scope is associated. |
| | 104 | | /// </summary> |
| | 105 | | /// |
| 42 | 106 | | private Uri ServiceEndpoint { get; } |
| | 107 | |
|
| | 108 | | /// <summary> |
| | 109 | | /// The provider to use for obtaining a token for authorization with the Service Bus service. |
| | 110 | | /// </summary> |
| | 111 | | /// |
| 0 | 112 | | private CbsTokenProvider TokenProvider { get; } |
| | 113 | |
|
| | 114 | | /// <summary> |
| | 115 | | /// The type of transport to use for communication. |
| | 116 | | /// </summary> |
| | 117 | | /// |
| 0 | 118 | | private ServiceBusTransportType Transport { get; } |
| | 119 | |
|
| | 120 | | /// <summary> |
| | 121 | | /// The proxy, if any, which should be used for communication. |
| | 122 | | /// </summary> |
| | 123 | | /// |
| 0 | 124 | | private IWebProxy Proxy { get; } |
| | 125 | |
|
| | 126 | | /// <summary> |
| | 127 | | /// The AMQP connection that is active for the current scope. |
| | 128 | | /// </summary> |
| | 129 | | /// |
| 0 | 130 | | private FaultTolerantAmqpObject<AmqpConnection> ActiveConnection { get; } |
| 0 | 131 | | public FaultTolerantAmqpObject<Controller> TransactionController { get; } |
| | 132 | |
|
| | 133 | | /// <summary> |
| | 134 | | /// Initializes a new instance of the <see cref="AmqpConnectionScope"/> class. |
| | 135 | | /// </summary> |
| | 136 | | /// |
| | 137 | | /// <param name="serviceEndpoint">Endpoint for the Service Bus service to which the scope is associated.</param> |
| | 138 | | /// <param name="credential">The credential to use for authorization with the Service Bus service.</param> |
| | 139 | | /// <param name="transport">The transport to use for communication.</param> |
| | 140 | | /// <param name="proxy">The proxy, if any, to use for communication.</param> |
| | 141 | | /// <param name="identifier">The identifier to assign this scope; if not provided, one will be generated.</param |
| | 142 | | /// |
| 42 | 143 | | public AmqpConnectionScope(Uri serviceEndpoint, |
| 42 | 144 | | ServiceBusTokenCredential credential, |
| 42 | 145 | | ServiceBusTransportType transport, |
| 42 | 146 | | IWebProxy proxy, |
| 42 | 147 | | string identifier = default) |
| | 148 | | { |
| 42 | 149 | | Argument.AssertNotNull(serviceEndpoint, nameof(serviceEndpoint)); |
| 42 | 150 | | Argument.AssertNotNull(credential, nameof(credential)); |
| 42 | 151 | | ValidateTransport(transport); |
| | 152 | |
|
| 42 | 153 | | ServiceEndpoint = serviceEndpoint; |
| 42 | 154 | | Transport = transport; |
| 42 | 155 | | Proxy = proxy; |
| 42 | 156 | | TokenProvider = new CbsTokenProvider(new ServiceBusTokenCredential(credential, serviceEndpoint.ToString()), |
| 42 | 157 | | Id = identifier ?? $"{ ServiceEndpoint }-{ Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture).Substr |
| | 158 | |
|
| | 159 | | #pragma warning disable CA2214 // Do not call overridable methods in constructors. This internal method is virtual for t |
| 0 | 160 | | Task<AmqpConnection> connectionFactory(TimeSpan timeout) => CreateAndOpenConnectionAsync(AmqpVersion, Servic |
| | 161 | | #pragma warning restore CA2214 // Do not call overridable methods in constructors |
| 42 | 162 | | ActiveConnection = new FaultTolerantAmqpObject<AmqpConnection>( |
| 42 | 163 | | connectionFactory, |
| 42 | 164 | | CloseConnection); |
| 42 | 165 | | TransactionController = new FaultTolerantAmqpObject<Controller>( |
| 42 | 166 | | CreateControllerAsync, |
| 42 | 167 | | CloseController); |
| 42 | 168 | | } |
| | 169 | |
|
| | 170 | | private async Task<Controller> CreateControllerAsync(TimeSpan timeout) |
| | 171 | | { |
| 0 | 172 | | var stopWatch = ValueStopwatch.StartNew(); |
| 0 | 173 | | AmqpConnection connection = await ActiveConnection.GetOrCreateAsync(timeout.CalculateRemaining(stopWatch.Get |
| | 174 | |
|
| 0 | 175 | | var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; |
| 0 | 176 | | AmqpSession amqpSession = null; |
| | 177 | | Controller controller; |
| | 178 | |
|
| | 179 | | try |
| | 180 | | { |
| 0 | 181 | | amqpSession = connection.CreateSession(sessionSettings); |
| 0 | 182 | | await amqpSession.OpenAsync(timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false |
| | 183 | |
|
| 0 | 184 | | controller = new Controller(amqpSession, timeout.CalculateRemaining(stopWatch.GetElapsedTime())); |
| 0 | 185 | | await controller.OpenAsync(timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false) |
| 0 | 186 | | } |
| 0 | 187 | | catch (Exception exception) |
| | 188 | | { |
| 0 | 189 | | if (amqpSession != null) |
| | 190 | | { |
| 0 | 191 | | await amqpSession.CloseAsync(timeout).ConfigureAwait(false); |
| | 192 | | } |
| | 193 | |
|
| 0 | 194 | | ServiceBusEventSource.Log.CreateControllerException(ActiveConnection.ToString(), exception.ToString()); |
| 0 | 195 | | throw; |
| 0 | 196 | | } |
| | 197 | |
|
| 0 | 198 | | return controller; |
| 0 | 199 | | } |
| | 200 | |
|
| | 201 | | private void CloseController(Controller controller) => |
| 0 | 202 | | controller.Close(); |
| | 203 | |
|
| | 204 | | /// <summary> |
| | 205 | | /// Initializes a new instance of the <see cref="AmqpConnectionScope"/> class. |
| | 206 | | /// </summary> |
| | 207 | | /// |
| 28 | 208 | | protected AmqpConnectionScope() |
| | 209 | | { |
| 28 | 210 | | } |
| | 211 | |
|
| | 212 | | /// <summary> |
| | 213 | | /// Opens an AMQP link for use with management operations. |
| | 214 | | /// </summary> |
| | 215 | | /// <param name="entityPath">The path for the entity.</param> |
| | 216 | | /// <param name="identifier">The identifier for the sender or receiver that is opening a management link.</param |
| | 217 | | /// <param name="timeout">The timeout to apply when creating the link.</param> |
| | 218 | | /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request t |
| | 219 | | /// |
| | 220 | | /// <returns>A link for use with management operations.</returns> |
| | 221 | | /// |
| | 222 | | /// <remarks> |
| | 223 | | /// The authorization for this link does not require periodic |
| | 224 | | /// refreshing. |
| | 225 | | /// </remarks> |
| | 226 | | /// |
| | 227 | | public virtual async Task<RequestResponseAmqpLink> OpenManagementLinkAsync( |
| | 228 | | string entityPath, |
| | 229 | | string identifier, |
| | 230 | | TimeSpan timeout, |
| | 231 | | CancellationToken cancellationToken) |
| | 232 | | { |
| 0 | 233 | | ServiceBusEventSource.Log.CreateManagementLinkStart(identifier); |
| | 234 | | try |
| | 235 | | { |
| 0 | 236 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 237 | |
|
| 0 | 238 | | var stopWatch = ValueStopwatch.StartNew(); |
| 0 | 239 | | var connection = await ActiveConnection.GetOrCreateAsync(timeout).ConfigureAwait(false); |
| 0 | 240 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 241 | |
|
| 0 | 242 | | var link = await CreateManagementLinkAsync( |
| 0 | 243 | | entityPath, |
| 0 | 244 | | connection, |
| 0 | 245 | | timeout.CalculateRemaining(stopWatch.GetElapsedTime()), cancellationToken).ConfigureAwait(false); |
| 0 | 246 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 247 | |
|
| 0 | 248 | | await OpenAmqpObjectAsync(link, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(f |
| 0 | 249 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| 0 | 250 | | ServiceBusEventSource.Log.CreateManagementLinkComplete(identifier); |
| 0 | 251 | | return link; |
| | 252 | | } |
| 0 | 253 | | catch (Exception ex) |
| | 254 | | { |
| 0 | 255 | | ServiceBusEventSource.Log.CreateManagementLinkException(identifier, ex.ToString()); |
| 0 | 256 | | throw; |
| | 257 | | } |
| 0 | 258 | | } |
| | 259 | |
|
| | 260 | | /// <summary> |
| | 261 | | /// Opens an AMQP link for use with consumer operations. |
| | 262 | | /// </summary> |
| | 263 | | /// <param name="entityPath"></param> |
| | 264 | | /// |
| | 265 | | /// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whet |
| | 266 | | /// <param name="receiveMode">The <see cref="ReceiveMode"/> used to specify how messages are received. Defaults |
| | 267 | | /// <param name="sessionId"></param> |
| | 268 | | /// <param name="isSessionReceiver"></param> |
| | 269 | | /// <param name="timeout">The timeout to apply when creating the link.</param> |
| | 270 | | /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request t |
| | 271 | | /// |
| | 272 | | /// <returns>A link for use with consumer operations.</returns> |
| | 273 | | /// |
| | 274 | | public virtual async Task<ReceivingAmqpLink> OpenReceiverLinkAsync( |
| | 275 | | string entityPath, |
| | 276 | | TimeSpan timeout, |
| | 277 | | uint prefetchCount, |
| | 278 | | ReceiveMode receiveMode, |
| | 279 | | string sessionId, |
| | 280 | | bool isSessionReceiver, |
| | 281 | | CancellationToken cancellationToken) |
| | 282 | | { |
| 0 | 283 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 284 | |
|
| 0 | 285 | | var stopWatch = ValueStopwatch.StartNew(); |
| 0 | 286 | | var receiverEndpoint = new Uri(ServiceEndpoint, entityPath); |
| | 287 | |
|
| 0 | 288 | | var connection = await ActiveConnection.GetOrCreateAsync(timeout).ConfigureAwait(false); |
| 0 | 289 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 290 | |
|
| 0 | 291 | | ReceivingAmqpLink link = await CreateReceivingLinkAsync( |
| 0 | 292 | | entityPath, |
| 0 | 293 | | connection, |
| 0 | 294 | | receiverEndpoint, |
| 0 | 295 | | timeout.CalculateRemaining(stopWatch.GetElapsedTime()), |
| 0 | 296 | | prefetchCount, |
| 0 | 297 | | receiveMode, |
| 0 | 298 | | sessionId, |
| 0 | 299 | | isSessionReceiver, |
| 0 | 300 | | cancellationToken |
| 0 | 301 | | ).ConfigureAwait(false); |
| | 302 | |
|
| 0 | 303 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 304 | |
|
| 0 | 305 | | await OpenAmqpObjectAsync(link, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false |
| 0 | 306 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| 0 | 307 | | return link; |
| | 308 | |
|
| 0 | 309 | | } |
| | 310 | |
|
| | 311 | | /// <summary> |
| | 312 | | /// Opens an AMQP link for use with producer operations. |
| | 313 | | /// </summary> |
| | 314 | | /// <param name="entityPath"></param> |
| | 315 | | /// <param name="viaEntityPath">The entity path to route the message through. Useful when using transactions.</p |
| | 316 | | /// <param name="timeout">The timeout to apply when creating the link.</param> |
| | 317 | | /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request t |
| | 318 | | /// |
| | 319 | | /// <returns>A link for use with producer operations.</returns> |
| | 320 | | /// |
| | 321 | | public virtual async Task<SendingAmqpLink> OpenSenderLinkAsync( |
| | 322 | | string entityPath, |
| | 323 | | string viaEntityPath, |
| | 324 | | TimeSpan timeout, |
| | 325 | | CancellationToken cancellationToken) |
| | 326 | | { |
| 0 | 327 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 328 | |
|
| 0 | 329 | | var stopWatch = ValueStopwatch.StartNew(); |
| | 330 | |
|
| 0 | 331 | | AmqpConnection connection = await ActiveConnection.GetOrCreateAsync(timeout).ConfigureAwait(false); |
| 0 | 332 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 333 | |
|
| 0 | 334 | | SendingAmqpLink link = await CreateSendingLinkAsync( |
| 0 | 335 | | entityPath, |
| 0 | 336 | | viaEntityPath, |
| 0 | 337 | | connection, |
| 0 | 338 | | timeout.CalculateRemaining(stopWatch.GetElapsedTime()), cancellationToken).ConfigureAwait(false); |
| | 339 | |
|
| 0 | 340 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 341 | |
|
| 0 | 342 | | await OpenAmqpObjectAsync(link, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false |
| 0 | 343 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 344 | |
|
| 0 | 345 | | return link; |
| 0 | 346 | | } |
| | 347 | |
|
| | 348 | | /// <summary> |
| | 349 | | /// Performs the task needed to clean up resources used by the <see cref="AmqpConnectionScope" />, |
| | 350 | | /// including ensuring that the client itself has been closed. |
| | 351 | | /// </summary> |
| | 352 | | /// |
| | 353 | | public override void Dispose() |
| | 354 | | { |
| 0 | 355 | | if (IsDisposed) |
| | 356 | | { |
| 0 | 357 | | return; |
| | 358 | | } |
| | 359 | |
|
| 0 | 360 | | ActiveConnection?.Dispose(); |
| 0 | 361 | | OperationCancellationSource.Cancel(); |
| 0 | 362 | | OperationCancellationSource.Dispose(); |
| | 363 | |
|
| 0 | 364 | | IsDisposed = true; |
| 0 | 365 | | } |
| | 366 | |
|
| | 367 | | /// <summary> |
| | 368 | | /// Creates an AMQP connection for a given scope. |
| | 369 | | /// </summary> |
| | 370 | | /// |
| | 371 | | /// <param name="amqpVersion">The version of AMQP to use for the connection.</param> |
| | 372 | | /// <param name="serviceEndpoint">The endpoint for the Service Bus service to which the scope is associated.</pa |
| | 373 | | /// <param name="transportType">The type of transport to use for communication.</param> |
| | 374 | | /// <param name="proxy">The proxy, if any, to use for communication.</param> |
| | 375 | | /// <param name="scopeIdentifier">The unique identifier for the associated scope.</param> |
| | 376 | | /// <param name="timeout">The timeout to consider when creating the connection.</param> |
| | 377 | | /// |
| | 378 | | /// <returns>An AMQP connection that may be used for communicating with the Service Bus service.</returns> |
| | 379 | | /// |
| | 380 | | protected virtual async Task<AmqpConnection> CreateAndOpenConnectionAsync( |
| | 381 | | Version amqpVersion, |
| | 382 | | Uri serviceEndpoint, |
| | 383 | | ServiceBusTransportType transportType, |
| | 384 | | IWebProxy proxy, |
| | 385 | | string scopeIdentifier, |
| | 386 | | TimeSpan timeout) |
| | 387 | | { |
| 0 | 388 | | var hostName = serviceEndpoint.Host; |
| 0 | 389 | | AmqpSettings amqpSettings = CreateAmpqSettings(AmqpVersion); |
| 0 | 390 | | AmqpConnectionSettings connectionSetings = CreateAmqpConnectionSettings(hostName, scopeIdentifier); |
| | 391 | |
|
| 0 | 392 | | TransportSettings transportSettings = transportType.IsWebSocketTransport() |
| 0 | 393 | | ? CreateTransportSettingsForWebSockets(hostName, proxy) |
| 0 | 394 | | : CreateTransportSettingsforTcp(hostName, serviceEndpoint.Port); |
| | 395 | |
|
| | 396 | | // Create and open the connection, respecting the timeout constraint |
| | 397 | | // that was received. |
| | 398 | |
|
| 0 | 399 | | var stopWatch = ValueStopwatch.StartNew(); |
| | 400 | |
|
| 0 | 401 | | var initiator = new AmqpTransportInitiator(amqpSettings, transportSettings); |
| 0 | 402 | | TransportBase transport = await initiator.ConnectTaskAsync(timeout).ConfigureAwait(false); |
| | 403 | |
|
| 0 | 404 | | var connection = new AmqpConnection(transport, amqpSettings, connectionSetings); |
| 0 | 405 | | await OpenAmqpObjectAsync(connection, timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait |
| | 406 | |
|
| | 407 | | // Create the CBS link that will be used for authorization. The act of creating the link will associate |
| | 408 | | // it with the connection. |
| | 409 | |
|
| | 410 | | #pragma warning disable CA1806 // Do not ignore method results |
| 0 | 411 | | new AmqpCbsLink(connection); |
| | 412 | | #pragma warning restore CA1806 // Do not ignore method results |
| | 413 | |
|
| | 414 | | // When the connection is closed, close each of the links associated with it. |
| | 415 | |
|
| 0 | 416 | | EventHandler closeHandler = null; |
| | 417 | |
|
| 0 | 418 | | closeHandler = (snd, args) => |
| 0 | 419 | | { |
| 0 | 420 | | foreach (var link in ActiveLinks.Keys) |
| 0 | 421 | | { |
| 0 | 422 | | link.SafeClose(); |
| 0 | 423 | | } |
| 0 | 424 | |
|
| 0 | 425 | | connection.Closed -= closeHandler; |
| 0 | 426 | | }; |
| | 427 | |
|
| 0 | 428 | | connection.Closed += closeHandler; |
| 0 | 429 | | return connection; |
| 0 | 430 | | } |
| | 431 | |
|
| | 432 | | /// <summary> |
| | 433 | | /// Creates an AMQP link for use with management operations. |
| | 434 | | /// </summary> |
| | 435 | | /// <param name="entityPath"></param> |
| | 436 | | /// |
| | 437 | | /// <param name="connection">The active and opened AMQP connection to use for this link.</param> |
| | 438 | | /// <param name="timeout">The timeout to apply when creating the link.</param> |
| | 439 | | /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request t |
| | 440 | | /// |
| | 441 | | /// <returns>A link for use with management operations.</returns> |
| | 442 | | /// |
| | 443 | | protected virtual async Task<RequestResponseAmqpLink> CreateManagementLinkAsync( |
| | 444 | | string entityPath, |
| | 445 | | AmqpConnection connection, |
| | 446 | | TimeSpan timeout, |
| | 447 | | CancellationToken cancellationToken) |
| | 448 | | { |
| 0 | 449 | | Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); |
| 0 | 450 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 451 | |
|
| 0 | 452 | | var session = default(AmqpSession); |
| 0 | 453 | | var stopWatch = ValueStopwatch.StartNew(); |
| | 454 | |
|
| | 455 | | try |
| | 456 | | { |
| | 457 | | // Create and open the AMQP session associated with the link. |
| | 458 | |
|
| 0 | 459 | | var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; |
| 0 | 460 | | session = connection.CreateSession(sessionSettings); |
| | 461 | |
|
| 0 | 462 | | await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); |
| 0 | 463 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 464 | |
|
| | 465 | | // Create and open the link. |
| | 466 | |
|
| 0 | 467 | | var linkSettings = new AmqpLinkSettings(); |
| 0 | 468 | | linkSettings.AddProperty(AmqpClientConstants.TimeoutName, (uint)timeout.CalculateRemaining(stopWatch.Get |
| 0 | 469 | | linkSettings.AddProperty(AmqpClientConstants.EntityTypeName, AmqpClientConstants.EntityTypeManagement); |
| 0 | 470 | | entityPath += '/' + AmqpClientConstants.ManagementAddress; |
| | 471 | |
|
| | 472 | | // Perform the initial authorization for the link. |
| | 473 | |
|
| 0 | 474 | | string[] claims = { ServiceBusClaim.Manage, ServiceBusClaim.Listen, ServiceBusClaim.Send }; |
| 0 | 475 | | var endpoint = new Uri(ServiceEndpoint, entityPath); |
| 0 | 476 | | var audience = new[] { endpoint.AbsoluteUri }; |
| 0 | 477 | | DateTime authExpirationUtc = await RequestAuthorizationUsingCbsAsync( |
| 0 | 478 | | connection, |
| 0 | 479 | | TokenProvider, |
| 0 | 480 | | ServiceEndpoint, |
| 0 | 481 | | audience, |
| 0 | 482 | | claims, |
| 0 | 483 | | timeout.CalculateRemaining(stopWatch.GetElapsedTime())) |
| 0 | 484 | | .ConfigureAwait(false); |
| | 485 | |
|
| 0 | 486 | | var link = new RequestResponseAmqpLink( |
| 0 | 487 | | AmqpClientConstants.EntityTypeManagement, |
| 0 | 488 | | session, |
| 0 | 489 | | entityPath, |
| 0 | 490 | | linkSettings.Properties); |
| 0 | 491 | | linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{session.Identifier} |
| | 492 | |
|
| | 493 | | // Track the link before returning it, so that it can be managed with the scope. |
| 0 | 494 | | var refreshTimer = default(Timer); |
| | 495 | |
|
| 0 | 496 | | TimerCallback refreshHandler = CreateAuthorizationRefreshHandler |
| 0 | 497 | | ( |
| 0 | 498 | | entityPath, |
| 0 | 499 | | connection, |
| 0 | 500 | | link, |
| 0 | 501 | | TokenProvider, |
| 0 | 502 | | ServiceEndpoint, |
| 0 | 503 | | audience, |
| 0 | 504 | | claims, |
| 0 | 505 | | AuthorizationRefreshTimeout, |
| 0 | 506 | | () => (ActiveLinks.ContainsKey(link) ? refreshTimer : null) |
| 0 | 507 | | ); |
| | 508 | |
|
| 0 | 509 | | refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationU |
| | 510 | |
|
| | 511 | | // Track the link before returning it, so that it can be managed with the scope. |
| | 512 | |
|
| 0 | 513 | | BeginTrackingLinkAsActive(entityPath, link, refreshTimer); |
| 0 | 514 | | return link; |
| | 515 | | } |
| | 516 | | catch (Exception exception) |
| | 517 | | { |
| | 518 | | // Aborting the session will perform any necessary cleanup of |
| | 519 | | // the associated link as well. |
| | 520 | |
|
| 0 | 521 | | session?.Abort(); |
| 0 | 522 | | ExceptionDispatchInfo.Capture(AmqpExceptionHelper.TranslateException( |
| 0 | 523 | | exception, |
| 0 | 524 | | null, |
| 0 | 525 | | session.GetInnerException(), |
| 0 | 526 | | connection.IsClosing())) |
| 0 | 527 | | .Throw(); |
| | 528 | |
|
| 0 | 529 | | throw; // will never be reached |
| | 530 | | } |
| 0 | 531 | | } |
| | 532 | |
|
| | 533 | | /// <summary> |
| | 534 | | /// Creates an AMQP link for use with receiving operations. |
| | 535 | | /// </summary> |
| | 536 | | /// <param name="entityPath"></param> |
| | 537 | | /// |
| | 538 | | /// <param name="connection">The active and opened AMQP connection to use for this link.</param> |
| | 539 | | /// <param name="endpoint">The fully qualified endpoint to open the link for.</param> |
| | 540 | | /// <param name="prefetchCount">Controls the number of events received and queued locally without regard to whet |
| | 541 | | /// <param name="receiveMode">The <see cref="ReceiveMode"/> used to specify how messages are received. Defaults |
| | 542 | | /// <param name="sessionId"></param> |
| | 543 | | /// <param name="isSessionReceiver"></param> |
| | 544 | | /// <param name="timeout">The timeout to apply when creating the link.</param> |
| | 545 | | /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request t |
| | 546 | | /// |
| | 547 | | /// <returns>A link for use for operations related to receiving events.</returns> |
| | 548 | | /// |
| | 549 | | protected virtual async Task<ReceivingAmqpLink> CreateReceivingLinkAsync( |
| | 550 | | string entityPath, |
| | 551 | | AmqpConnection connection, |
| | 552 | | Uri endpoint, |
| | 553 | | TimeSpan timeout, |
| | 554 | | uint prefetchCount, |
| | 555 | | ReceiveMode receiveMode, |
| | 556 | | string sessionId, |
| | 557 | | bool isSessionReceiver, |
| | 558 | | CancellationToken cancellationToken) |
| | 559 | | { |
| 0 | 560 | | Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); |
| 0 | 561 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 562 | |
|
| 0 | 563 | | var session = default(AmqpSession); |
| 0 | 564 | | var stopWatch = ValueStopwatch.StartNew(); |
| | 565 | |
|
| | 566 | | try |
| | 567 | | { |
| | 568 | | // Perform the initial authorization for the link. |
| | 569 | |
|
| 0 | 570 | | string[] authClaims = new string[] { ServiceBusClaim.Send }; |
| 0 | 571 | | var audience = new[] { endpoint.AbsoluteUri }; |
| 0 | 572 | | DateTime authExpirationUtc = await RequestAuthorizationUsingCbsAsync( |
| 0 | 573 | | connection, |
| 0 | 574 | | TokenProvider, |
| 0 | 575 | | endpoint, |
| 0 | 576 | | audience, |
| 0 | 577 | | authClaims, |
| 0 | 578 | | timeout.CalculateRemaining(stopWatch.GetElapsedTime())).ConfigureAwait(false); |
| 0 | 579 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 580 | |
|
| | 581 | | // Create and open the AMQP session associated with the link. |
| | 582 | |
|
| 0 | 583 | | var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; |
| 0 | 584 | | session = connection.CreateSession(sessionSettings); |
| | 585 | |
|
| 0 | 586 | | await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); |
| 0 | 587 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 588 | |
|
| 0 | 589 | | var filters = new FilterSet(); |
| | 590 | |
|
| | 591 | | // even if supplied sessionId is null, we need to add the Session filter if it is a session receiver |
| 0 | 592 | | if (isSessionReceiver) |
| | 593 | | { |
| 0 | 594 | | filters.Add(AmqpClientConstants.SessionFilterName, sessionId); |
| | 595 | | } |
| | 596 | |
|
| 0 | 597 | | var linkSettings = new AmqpLinkSettings |
| 0 | 598 | | { |
| 0 | 599 | | Role = true, |
| 0 | 600 | | TotalLinkCredit = prefetchCount, |
| 0 | 601 | | AutoSendFlow = prefetchCount > 0, |
| 0 | 602 | | SettleType = (receiveMode == ReceiveMode.PeekLock) ? SettleMode.SettleOnDispose : SettleMode.SettleO |
| 0 | 603 | | Source = new Source { Address = endpoint.AbsolutePath, FilterSet = filters }, |
| 0 | 604 | | Target = new Target { Address = Guid.NewGuid().ToString() } |
| 0 | 605 | | }; |
| | 606 | |
|
| 0 | 607 | | var link = new ReceivingAmqpLink(linkSettings); |
| 0 | 608 | | linkSettings.LinkName = $"{connection.Settings.ContainerId};{connection.Identifier}:{session.Identifier} |
| | 609 | |
|
| 0 | 610 | | link.AttachTo(session); |
| | 611 | |
|
| | 612 | | // Configure refresh for authorization of the link. |
| | 613 | |
|
| 0 | 614 | | var refreshTimer = default(Timer); |
| | 615 | |
|
| 0 | 616 | | TimerCallback refreshHandler = CreateAuthorizationRefreshHandler |
| 0 | 617 | | ( |
| 0 | 618 | | entityPath, |
| 0 | 619 | | connection, |
| 0 | 620 | | link, |
| 0 | 621 | | TokenProvider, |
| 0 | 622 | | endpoint, |
| 0 | 623 | | audience, |
| 0 | 624 | | authClaims, |
| 0 | 625 | | AuthorizationRefreshTimeout, |
| 0 | 626 | | () => (ActiveLinks.ContainsKey(link) ? refreshTimer : null) |
| 0 | 627 | | ); |
| | 628 | |
|
| 0 | 629 | | refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationU |
| | 630 | |
|
| | 631 | | // Track the link before returning it, so that it can be managed with the scope. |
| | 632 | |
|
| 0 | 633 | | BeginTrackingLinkAsActive(entityPath, link, refreshTimer); |
| 0 | 634 | | return link; |
| | 635 | | } |
| | 636 | | catch (Exception exception) |
| | 637 | | { |
| | 638 | | // Aborting the session will perform any necessary cleanup of |
| | 639 | | // the associated link as well. |
| | 640 | |
|
| 0 | 641 | | session?.Abort(); |
| 0 | 642 | | ExceptionDispatchInfo.Capture(AmqpExceptionHelper.TranslateException( |
| 0 | 643 | | exception, |
| 0 | 644 | | null, |
| 0 | 645 | | session.GetInnerException(), |
| 0 | 646 | | connection.IsClosing())) |
| 0 | 647 | | .Throw(); |
| | 648 | |
|
| 0 | 649 | | throw; // will never be reached |
| | 650 | | } |
| 0 | 651 | | } |
| | 652 | |
|
| | 653 | | /// <summary> |
| | 654 | | /// Creates an AMQP link for use with publishing operations. |
| | 655 | | /// </summary> |
| | 656 | | /// <param name="entityPath"></param> |
| | 657 | | /// <param name="viaEntityPath">The entity path to route the message through. Useful when using transactions.</p |
| | 658 | | /// <param name="connection">The active and opened AMQP connection to use for this link.</param> |
| | 659 | | /// <param name="timeout">The timeout to apply when creating the link.</param> |
| | 660 | | /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request t |
| | 661 | | /// |
| | 662 | | /// <returns>A link for use for operations related to receiving events.</returns> |
| | 663 | | /// |
| | 664 | | protected virtual async Task<SendingAmqpLink> CreateSendingLinkAsync( |
| | 665 | | string entityPath, |
| | 666 | | string viaEntityPath, |
| | 667 | | AmqpConnection connection, |
| | 668 | | TimeSpan timeout, |
| | 669 | | CancellationToken cancellationToken) |
| | 670 | | { |
| 0 | 671 | | Argument.AssertNotDisposed(IsDisposed, nameof(AmqpConnectionScope)); |
| 0 | 672 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 673 | |
|
| 0 | 674 | | var session = default(AmqpSession); |
| 0 | 675 | | var stopWatch = ValueStopwatch.StartNew(); |
| | 676 | |
|
| | 677 | | try |
| | 678 | | { |
| | 679 | | string[] audience; |
| 0 | 680 | | Uri destinationEndpoint = null; |
| | 681 | |
|
| | 682 | | // if there is a via entityPath, include that in the audience |
| | 683 | |
|
| 0 | 684 | | if (!string.IsNullOrEmpty(viaEntityPath)) |
| | 685 | | { |
| 0 | 686 | | destinationEndpoint = new Uri(ServiceEndpoint, viaEntityPath); |
| 0 | 687 | | var finalDestinationEndpoint = new Uri(ServiceEndpoint, entityPath); |
| 0 | 688 | | audience = new string[] { finalDestinationEndpoint.AbsoluteUri, destinationEndpoint.AbsoluteUri }; |
| | 689 | | } |
| | 690 | | else |
| | 691 | | { |
| 0 | 692 | | destinationEndpoint = new Uri(ServiceEndpoint, entityPath); |
| 0 | 693 | | audience = new string[] { destinationEndpoint.AbsoluteUri }; |
| | 694 | | } |
| | 695 | |
|
| | 696 | | // Perform the initial authorization for the link. |
| | 697 | |
|
| 0 | 698 | | var authClaims = new[] { ServiceBusClaim.Send }; |
| | 699 | |
|
| 0 | 700 | | DateTime authExpirationUtc = await RequestAuthorizationUsingCbsAsync( |
| 0 | 701 | | connection, |
| 0 | 702 | | TokenProvider, |
| 0 | 703 | | destinationEndpoint, |
| 0 | 704 | | audience, |
| 0 | 705 | | authClaims, |
| 0 | 706 | | timeout.CalculateRemaining(stopWatch.GetElapsedTime())) |
| 0 | 707 | | .ConfigureAwait(false); |
| | 708 | |
|
| 0 | 709 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 710 | |
|
| | 711 | | // Create and open the AMQP session associated with the link. |
| | 712 | |
|
| 0 | 713 | | var sessionSettings = new AmqpSessionSettings { Properties = new Fields() }; |
| 0 | 714 | | session = connection.CreateSession(sessionSettings); |
| | 715 | |
|
| 0 | 716 | | await OpenAmqpObjectAsync(session, timeout).ConfigureAwait(false); |
| 0 | 717 | | cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); |
| | 718 | |
|
| | 719 | | // Create and open the link. |
| | 720 | |
|
| 0 | 721 | | var linkSettings = new AmqpLinkSettings |
| 0 | 722 | | { |
| 0 | 723 | | Role = false, |
| 0 | 724 | | InitialDeliveryCount = 0, |
| 0 | 725 | | Source = new Source { Address = Guid.NewGuid().ToString() }, |
| 0 | 726 | | Target = new Target { Address = destinationEndpoint.AbsolutePath } |
| 0 | 727 | | }; |
| | 728 | |
|
| 0 | 729 | | if (!string.IsNullOrEmpty(viaEntityPath)) |
| | 730 | | { |
| 0 | 731 | | linkSettings.AddProperty(AmqpClientConstants.TransferDestinationAddress, entityPath); |
| | 732 | | } |
| | 733 | |
|
| 0 | 734 | | linkSettings.AddProperty(AmqpClientConstants.TimeoutName, (uint)timeout.CalculateRemaining(stopWatch.Get |
| | 735 | |
|
| 0 | 736 | | var link = new SendingAmqpLink(linkSettings); |
| 0 | 737 | | linkSettings.LinkName = $"{ Id };{ connection.Identifier }:{ session.Identifier }:{ link.Identifier }"; |
| 0 | 738 | | link.AttachTo(session); |
| | 739 | |
|
| | 740 | | // Configure refresh for authorization of the link. |
| | 741 | |
|
| 0 | 742 | | var refreshTimer = default(Timer); |
| | 743 | |
|
| 0 | 744 | | TimerCallback refreshHandler = CreateAuthorizationRefreshHandler |
| 0 | 745 | | ( |
| 0 | 746 | | entityPath, |
| 0 | 747 | | connection, |
| 0 | 748 | | link, |
| 0 | 749 | | TokenProvider, |
| 0 | 750 | | destinationEndpoint, |
| 0 | 751 | | audience, |
| 0 | 752 | | authClaims, |
| 0 | 753 | | AuthorizationRefreshTimeout, |
| 0 | 754 | | () => refreshTimer |
| 0 | 755 | | ); |
| | 756 | |
|
| 0 | 757 | | refreshTimer = new Timer(refreshHandler, null, CalculateLinkAuthorizationRefreshInterval(authExpirationU |
| | 758 | |
|
| | 759 | | // Track the link before returning it, so that it can be managed with the scope. |
| | 760 | |
|
| 0 | 761 | | BeginTrackingLinkAsActive(entityPath, link, refreshTimer); |
| 0 | 762 | | return link; |
| | 763 | | } |
| | 764 | | catch (Exception exception) |
| | 765 | | { |
| | 766 | | // Aborting the session will perform any necessary cleanup of |
| | 767 | | // the associated link as well. |
| | 768 | |
|
| 0 | 769 | | session?.Abort(); |
| 0 | 770 | | ExceptionDispatchInfo.Capture(AmqpExceptionHelper.TranslateException( |
| 0 | 771 | | exception, |
| 0 | 772 | | null, |
| 0 | 773 | | session.GetInnerException(), |
| 0 | 774 | | connection.IsClosing())) |
| 0 | 775 | | .Throw(); |
| | 776 | |
|
| 0 | 777 | | throw; // will never be reached |
| | 778 | | } |
| 0 | 779 | | } |
| | 780 | |
|
| | 781 | | /// <summary> |
| | 782 | | /// Performs the actions needed to configure and begin tracking the specified AMQP |
| | 783 | | /// link as an active link bound to this scope. |
| | 784 | | /// </summary> |
| | 785 | | /// <param name="entityPath"></param> |
| | 786 | | /// |
| | 787 | | /// <param name="link">The link to begin tracking.</param> |
| | 788 | | /// <param name="authorizationRefreshTimer">The timer used to manage refreshing authorization, if the link requi |
| | 789 | | /// |
| | 790 | | /// <remarks> |
| | 791 | | /// This method does operate on the specified <paramref name="link"/> in order to configure it |
| | 792 | | /// for active tracking; no assumptions are made about the open/connected state of the link nor are |
| | 793 | | /// its communication properties modified. |
| | 794 | | /// </remarks> |
| | 795 | | /// |
| | 796 | | protected virtual void BeginTrackingLinkAsActive( |
| | 797 | | string entityPath, |
| | 798 | | AmqpObject link, |
| | 799 | | Timer authorizationRefreshTimer = null) |
| | 800 | | { |
| | 801 | | // Register the link as active and having authorization automatically refreshed, so that it can be |
| | 802 | | // managed with the scope. |
| | 803 | |
|
| 0 | 804 | | if (!ActiveLinks.TryAdd(link, authorizationRefreshTimer)) |
| | 805 | | { |
| 0 | 806 | | throw new ServiceBusException(true, entityPath, Resources.CouldNotCreateLink); |
| | 807 | | } |
| | 808 | |
|
| | 809 | | // When the link is closed, stop refreshing authorization and remove it from the |
| | 810 | | // set of associated links. |
| | 811 | |
|
| 0 | 812 | | var closeHandler = default(EventHandler); |
| | 813 | |
|
| 0 | 814 | | closeHandler = (snd, args) => |
| 0 | 815 | | { |
| 0 | 816 | | ActiveLinks.TryRemove(link, out var timer); |
| 0 | 817 | |
|
| 0 | 818 | | timer?.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); |
| 0 | 819 | | timer?.Dispose(); |
| 0 | 820 | |
|
| 0 | 821 | | link.Closed -= closeHandler; |
| 0 | 822 | | }; |
| | 823 | |
|
| 0 | 824 | | link.Closed += closeHandler; |
| 0 | 825 | | } |
| | 826 | |
|
| | 827 | | /// <summary> |
| | 828 | | /// Performs the tasks needed to close a connection. |
| | 829 | | /// </summary> |
| | 830 | | /// |
| | 831 | | /// <param name="connection">The connection to close.</param> |
| | 832 | | /// |
| 0 | 833 | | protected virtual void CloseConnection(AmqpConnection connection) => connection.SafeClose(); |
| | 834 | |
|
| | 835 | | /// <summary> |
| | 836 | | /// Calculates the interval after which authorization for an AMQP link should be |
| | 837 | | /// refreshed. |
| | 838 | | /// </summary> |
| | 839 | | /// |
| | 840 | | /// <param name="expirationTimeUtc">The date/time, in UTC, that the current authorization is expected to expire. |
| | 841 | | /// |
| | 842 | | /// <returns>The interval after which authorization should be refreshed.</returns> |
| | 843 | | /// |
| | 844 | | protected virtual TimeSpan CalculateLinkAuthorizationRefreshInterval(DateTime expirationTimeUtc) |
| | 845 | | { |
| 0 | 846 | | var refreshDueInterval = (expirationTimeUtc.Subtract(DateTime.UtcNow)).Add(AuthorizationRefreshBuffer); |
| 0 | 847 | | return (refreshDueInterval < MinimumAuthorizationRefresh) ? MinimumAuthorizationRefresh : refreshDueInterval |
| | 848 | | } |
| | 849 | |
|
| | 850 | | /// <summary> |
| | 851 | | /// Creates the timer event handler to support refreshing AMQP link authorization |
| | 852 | | /// on a recurring basis. |
| | 853 | | /// </summary> |
| | 854 | | /// <param name="entityPath"></param> |
| | 855 | | /// |
| | 856 | | /// <param name="connection">The AMQP connection to which the link being refreshed is bound to.</param> |
| | 857 | | /// <param name="amqpLink">The AMQO link to refresh authorization for.</param> |
| | 858 | | /// <param name="tokenProvider">The <see cref="CbsTokenProvider" /> to use for obtaining access tokens.</param> |
| | 859 | | /// <param name="endpoint">The Service Bus service endpoint that the AMQP link is communicating with.</param> |
| | 860 | | /// <param name="audience">The audience associated with the authorization. This is likely the <paramref name="e |
| | 861 | | /// <param name="requiredClaims">The set of claims required to support the operations of the AMQP link.</param> |
| | 862 | | /// <param name="refreshTimeout">The timeout to apply when requesting authorization refresh.</param> |
| | 863 | | /// <param name="refreshTimerFactory">A function to allow retrieving the <see cref="Timer" /> associated with th |
| | 864 | | /// |
| | 865 | | /// <returns>A <see cref="TimerCallback"/> delegate to perform the refresh when a timer is due.</returns> |
| | 866 | | /// |
| | 867 | | protected virtual TimerCallback CreateAuthorizationRefreshHandler( |
| | 868 | | string entityPath, |
| | 869 | | AmqpConnection connection, |
| | 870 | | AmqpObject amqpLink, |
| | 871 | | CbsTokenProvider tokenProvider, |
| | 872 | | Uri endpoint, |
| | 873 | | string[] audience, |
| | 874 | | string[] requiredClaims, |
| | 875 | | TimeSpan refreshTimeout, |
| | 876 | | Func<Timer> refreshTimerFactory) |
| | 877 | | { |
| 0 | 878 | | return async _ => |
| 0 | 879 | | { |
| 0 | 880 | | ServiceBusEventSource.Log.AmqpLinkAuthorizationRefreshStart(entityPath, endpoint.AbsoluteUri); |
| 0 | 881 | | Timer refreshTimer = refreshTimerFactory(); |
| 0 | 882 | |
|
| 0 | 883 | | try |
| 0 | 884 | | { |
| 0 | 885 | | if (refreshTimer == null) |
| 0 | 886 | | { |
| 0 | 887 | | return; |
| 0 | 888 | | } |
| 0 | 889 | |
|
| 0 | 890 | | DateTime authExpirationUtc = await RequestAuthorizationUsingCbsAsync( |
| 0 | 891 | | connection, |
| 0 | 892 | | tokenProvider, |
| 0 | 893 | | endpoint, |
| 0 | 894 | | audience, |
| 0 | 895 | | requiredClaims, |
| 0 | 896 | | refreshTimeout) |
| 0 | 897 | | .ConfigureAwait(false); |
| 0 | 898 | |
|
| 0 | 899 | | // Reset the timer for the next refresh. |
| 0 | 900 | |
|
| 0 | 901 | | if (authExpirationUtc >= DateTimeOffset.UtcNow) |
| 0 | 902 | | { |
| 0 | 903 | | refreshTimer.Change(CalculateLinkAuthorizationRefreshInterval(authExpirationUtc), Timeout.Infini |
| 0 | 904 | | } |
| 0 | 905 | | } |
| 0 | 906 | | catch (ObjectDisposedException) |
| 0 | 907 | | { |
| 0 | 908 | | // This can occur if the connection is closed or the scope disposed after the factory |
| 0 | 909 | | // is called but before the timer is updated. The callback may also fire while the timer is |
| 0 | 910 | | // in the act of disposing. Do not consider it an error. |
| 0 | 911 | | } |
| 0 | 912 | | catch (Exception ex) |
| 0 | 913 | | { |
| 0 | 914 | | ServiceBusEventSource.Log.AmqpLinkAuthorizationRefreshError(entityPath, endpoint.AbsoluteUri, ex.Mes |
| 0 | 915 | |
|
| 0 | 916 | | // Attempt to unset the timer; there's a decent chance that it has been disposed at this point or |
| 0 | 917 | | // that the connection has been closed. Ignore potential exceptions, as they won't impact operation. |
| 0 | 918 | | // At worse, another timer tick will occur and the operation will be retried. |
| 0 | 919 | |
|
| 0 | 920 | | try |
| 0 | 921 | | { refreshTimer.Change(Timeout.Infinite, Timeout.Infinite); } |
| 0 | 922 | | catch { } |
| 0 | 923 | | } |
| 0 | 924 | | finally |
| 0 | 925 | | { |
| 0 | 926 | | ServiceBusEventSource.Log.AmqpLinkAuthorizationRefreshComplete(entityPath, endpoint.AbsoluteUri); |
| 0 | 927 | | } |
| 0 | 928 | | }; |
| | 929 | | } |
| | 930 | |
|
| | 931 | | /// <summary> |
| | 932 | | /// Performs the actions needed to open an AMQP object, such |
| | 933 | | /// as a session or link for use. |
| | 934 | | /// </summary> |
| | 935 | | /// |
| | 936 | | /// <param name="target">The target AMQP object to open.</param> |
| | 937 | | /// <param name="timeout">The timeout to apply when opening the link.</param> |
| | 938 | | /// |
| | 939 | | protected virtual async Task OpenAmqpObjectAsync( |
| | 940 | | AmqpObject target, |
| | 941 | | TimeSpan timeout) |
| | 942 | | { |
| | 943 | | try |
| | 944 | | { |
| 0 | 945 | | await target.OpenAsync(timeout).ConfigureAwait(false); |
| 0 | 946 | | } |
| 0 | 947 | | catch |
| | 948 | | { |
| | 949 | | switch (target) |
| | 950 | | { |
| | 951 | | case AmqpLink linkTarget: |
| 0 | 952 | | linkTarget.Session?.SafeClose(); |
| 0 | 953 | | break; |
| | 954 | | case RequestResponseAmqpLink linkTarget: |
| 0 | 955 | | linkTarget.Session?.SafeClose(); |
| | 956 | | break; |
| | 957 | |
|
| | 958 | | default: |
| | 959 | | break; |
| | 960 | | } |
| | 961 | |
|
| 0 | 962 | | target.SafeClose(); |
| 0 | 963 | | throw; |
| | 964 | | } |
| 0 | 965 | | } |
| | 966 | |
|
| | 967 | | /// <summary> |
| | 968 | | /// Requests authorization for a connection or link using a connection via the CBS mechanism. |
| | 969 | | /// </summary> |
| | 970 | | /// |
| | 971 | | /// <param name="connection">The AMQP connection for which the authorization is associated.</param> |
| | 972 | | /// <param name="tokenProvider">The <see cref="CbsTokenProvider" /> to use for obtaining access tokens.</param> |
| | 973 | | /// <param name="endpoint">The Service Bus service endpoint that the authorization is requested for.</param> |
| | 974 | | /// <param name="audience">The audience associated with the authorization. This is likely the <paramref name="e |
| | 975 | | /// <param name="requiredClaims">The set of claims required to support the operations of the AMQP link.</param> |
| | 976 | | /// <param name="timeout">The timeout to apply when requesting authorization.</param> |
| | 977 | | /// |
| | 978 | | /// <returns>The date/time, in UTC, when the authorization expires.</returns> |
| | 979 | | /// |
| | 980 | | /// <remarks> |
| | 981 | | /// It is assumed that there is a valid <see cref="AmqpCbsLink" /> already associated |
| | 982 | | /// with the connection; this will be used as the transport for the authorization |
| | 983 | | /// credentials. |
| | 984 | | /// </remarks> |
| | 985 | | /// |
| | 986 | | protected virtual async Task<DateTime> RequestAuthorizationUsingCbsAsync( |
| | 987 | | AmqpConnection connection, |
| | 988 | | CbsTokenProvider tokenProvider, |
| | 989 | | Uri endpoint, |
| | 990 | | string[] audience, |
| | 991 | | string[] requiredClaims, |
| | 992 | | TimeSpan timeout) |
| | 993 | | { |
| 0 | 994 | | AmqpCbsLink authLink = connection.Extensions.Find<AmqpCbsLink>(); |
| 0 | 995 | | DateTime cbsTokenExpiresAtUtc = DateTime.MaxValue; |
| 0 | 996 | | foreach (string resource in audience) |
| | 997 | | { |
| 0 | 998 | | DateTime expiresAt = |
| 0 | 999 | | await authLink.SendTokenAsync(TokenProvider, endpoint, resource, resource, requiredClaims, timeout). |
| 0 | 1000 | | if (expiresAt < cbsTokenExpiresAtUtc) |
| | 1001 | | { |
| 0 | 1002 | | cbsTokenExpiresAtUtc = expiresAt; |
| | 1003 | | } |
| | 1004 | | } |
| 0 | 1005 | | return cbsTokenExpiresAtUtc; |
| 0 | 1006 | | } |
| | 1007 | |
|
| | 1008 | | /// <summary> |
| | 1009 | | /// Creates the settings to use for AMQP communication. |
| | 1010 | | /// </summary> |
| | 1011 | | /// |
| | 1012 | | /// <param name="amqpVersion">The version of AMQP to be used.</param> |
| | 1013 | | /// |
| | 1014 | | /// <returns>The settings for AMQP to use for communication with the Service Bus service.</returns> |
| | 1015 | | /// |
| | 1016 | | private static AmqpSettings CreateAmpqSettings(Version amqpVersion) |
| | 1017 | | { |
| 0 | 1018 | | var saslProvider = new SaslTransportProvider(); |
| 0 | 1019 | | saslProvider.Versions.Add(new AmqpVersion(amqpVersion)); |
| 0 | 1020 | | saslProvider.AddHandler(new SaslAnonymousHandler(CbsSaslHandlerName)); |
| | 1021 | |
|
| 0 | 1022 | | var amqpProvider = new AmqpTransportProvider(); |
| 0 | 1023 | | amqpProvider.Versions.Add(new AmqpVersion(amqpVersion)); |
| | 1024 | |
|
| 0 | 1025 | | var settings = new AmqpSettings(); |
| 0 | 1026 | | settings.TransportProviders.Add(saslProvider); |
| 0 | 1027 | | settings.TransportProviders.Add(amqpProvider); |
| | 1028 | |
|
| 0 | 1029 | | return settings; |
| | 1030 | | } |
| | 1031 | |
|
| | 1032 | | /// <summary> |
| | 1033 | | /// Creates the transport settings for use with TCP. |
| | 1034 | | /// </summary> |
| | 1035 | | /// |
| | 1036 | | /// <param name="hostName">The host name of the Service Bus service endpoint.</param> |
| | 1037 | | /// <param name="port">The port to use for connecting to the endpoint.</param> |
| | 1038 | | /// |
| | 1039 | | /// <returns>The settings to use for transport.</returns> |
| | 1040 | | /// |
| | 1041 | | private static TransportSettings CreateTransportSettingsforTcp( |
| | 1042 | | string hostName, |
| | 1043 | | int port) |
| | 1044 | | { |
| 0 | 1045 | | var tcpSettings = new TcpTransportSettings |
| 0 | 1046 | | { |
| 0 | 1047 | | Host = hostName, |
| 0 | 1048 | | Port = port < 0 ? AmqpConstants.DefaultSecurePort : port, |
| 0 | 1049 | | ReceiveBufferSize = AmqpConstants.TransportBufferSize, |
| 0 | 1050 | | SendBufferSize = AmqpConstants.TransportBufferSize |
| 0 | 1051 | | }; |
| | 1052 | |
|
| 0 | 1053 | | return new TlsTransportSettings(tcpSettings) |
| 0 | 1054 | | { |
| 0 | 1055 | | TargetHost = hostName, |
| 0 | 1056 | | }; |
| | 1057 | | } |
| | 1058 | |
|
| | 1059 | | /// <summary> |
| | 1060 | | /// Creates the transport settings for use with web sockets. |
| | 1061 | | /// </summary> |
| | 1062 | | /// |
| | 1063 | | /// <param name="hostName">The host name of the Service Bus service endpoint.</param> |
| | 1064 | | /// <param name="proxy">The proxy to use for connecting to the endpoint.</param> |
| | 1065 | | /// |
| | 1066 | | /// <returns>The settings to use for transport.</returns> |
| | 1067 | | /// |
| | 1068 | | private static TransportSettings CreateTransportSettingsForWebSockets( |
| | 1069 | | string hostName, |
| | 1070 | | IWebProxy proxy) |
| | 1071 | | { |
| 0 | 1072 | | var uriBuilder = new UriBuilder(hostName) |
| 0 | 1073 | | { |
| 0 | 1074 | | Path = WebSocketsPathSuffix, |
| 0 | 1075 | | Scheme = WebSocketsUriScheme, |
| 0 | 1076 | | Port = -1 |
| 0 | 1077 | | }; |
| | 1078 | |
|
| 0 | 1079 | | return new WebSocketTransportSettings |
| 0 | 1080 | | { |
| 0 | 1081 | | Uri = uriBuilder.Uri, |
| 0 | 1082 | | Proxy = proxy ?? (default) |
| 0 | 1083 | | }; |
| | 1084 | | } |
| | 1085 | |
|
| | 1086 | | /// <summary> |
| | 1087 | | /// Creates the AMQP connection settings to use when communicating with the Service Bus service. |
| | 1088 | | /// </summary> |
| | 1089 | | /// |
| | 1090 | | /// <param name="hostName">The host name of the Service Bus service endpoint.</param> |
| | 1091 | | /// <param name="identifier">unique identifier of the current Service Bus scope.</param> |
| | 1092 | | /// |
| | 1093 | | /// <returns>The settings to apply to the connection.</returns> |
| | 1094 | | /// |
| | 1095 | | private static AmqpConnectionSettings CreateAmqpConnectionSettings( |
| | 1096 | | string hostName, |
| | 1097 | | string identifier) |
| | 1098 | | { |
| 0 | 1099 | | var connectionSettings = new AmqpConnectionSettings |
| 0 | 1100 | | { |
| 0 | 1101 | | IdleTimeOut = (uint)ConnectionIdleTimeout.TotalMilliseconds, |
| 0 | 1102 | | MaxFrameSize = AmqpConstants.DefaultMaxFrameSize, |
| 0 | 1103 | | ContainerId = identifier, |
| 0 | 1104 | | HostName = hostName |
| 0 | 1105 | | }; |
| | 1106 | |
|
| 0 | 1107 | | foreach (KeyValuePair<string, string> property in ClientLibraryInformation.Current.EnumerateProperties()) |
| | 1108 | | { |
| 0 | 1109 | | connectionSettings.AddProperty(property.Key, property.Value); |
| | 1110 | | } |
| | 1111 | |
|
| 0 | 1112 | | return connectionSettings; |
| | 1113 | | } |
| | 1114 | |
|
| | 1115 | | /// <summary> |
| | 1116 | | /// Validates the transport associated with the scope, throwing an argument exception |
| | 1117 | | /// if it is unknown in this context. |
| | 1118 | | /// </summary> |
| | 1119 | | /// |
| | 1120 | | /// <param name="transport">The transport to validate.</param> |
| | 1121 | | /// |
| | 1122 | | private static void ValidateTransport(ServiceBusTransportType transport) |
| | 1123 | | { |
| 42 | 1124 | | if ((transport != ServiceBusTransportType.AmqpTcp) && (transport != ServiceBusTransportType.AmqpWebSockets)) |
| | 1125 | | { |
| 0 | 1126 | | throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.UnknownConnectionType, t |
| | 1127 | | } |
| 42 | 1128 | | } |
| | 1129 | | } |
| | 1130 | | } |