-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
ServiceBusConnection.cs
346 lines (297 loc) · 14.6 KB
/
ServiceBusConnection.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.ServiceBus
{
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Amqp;
using Microsoft.Azure.Amqp.Framing;
using Microsoft.Azure.Amqp.Transaction;
using Microsoft.Azure.Amqp.Transport;
using Microsoft.Azure.ServiceBus.Amqp;
using Microsoft.Azure.ServiceBus.Primitives;
/// <summary>
/// Connection object to service bus namespace
/// </summary>
public class ServiceBusConnection
{
static readonly Version AmqpVersion = new Version(1, 0, 0, 0);
readonly object syncLock;
bool isClosedOrClosing;
/// <summary>
/// Creates a new connection to service bus.
/// </summary>
/// <param name="connectionStringBuilder"><see cref="ServiceBusConnectionStringBuilder"/> having namespace information.</param>
/// <remarks>It is the responsibility of the user to close the connection after use through <see cref="CloseAsync"/></remarks>
public ServiceBusConnection(ServiceBusConnectionStringBuilder connectionStringBuilder)
: this(connectionStringBuilder?.GetNamespaceConnectionString())
{
}
/// <summary>
/// Creates a new connection to service bus.
/// </summary>
/// <param name="namespaceConnectionString">Namespace connection string</param>
/// <remarks>It is the responsibility of the user to close the connection after use through <see cref="CloseAsync"/></remarks>
public ServiceBusConnection(string namespaceConnectionString)
: this(namespaceConnectionString, RetryPolicy.Default)
{
}
/// <summary>
/// Creates a new connection to service bus.
/// </summary>
/// <param name="namespaceConnectionString">Namespace connection string.</param>
/// <param name="retryPolicy">Retry policy for operations. Defaults to <see cref="RetryPolicy.Default"/></param>
/// <remarks>It is the responsibility of the user to close the connection after use through <see cref="CloseAsync"/></remarks>
public ServiceBusConnection(string namespaceConnectionString, RetryPolicy retryPolicy = null)
: this(retryPolicy)
{
if (string.IsNullOrWhiteSpace(namespaceConnectionString))
{
throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(namespaceConnectionString));
}
var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(namespaceConnectionString);
if (!string.IsNullOrWhiteSpace(serviceBusConnectionStringBuilder.EntityPath))
{
throw Fx.Exception.Argument(nameof(namespaceConnectionString), "NamespaceConnectionString should not contain EntityPath.");
}
this.InitializeConnection(serviceBusConnectionStringBuilder);
}
/// <summary>
/// Creates a new connection to service bus.
/// </summary>
/// <param name="namespaceConnectionString">Namespace connection string.</param>
/// <param name="operationTimeout">Duration after which individual operations will timeout.</param>
/// <param name="retryPolicy">Retry policy for operations. Defaults to <see cref="RetryPolicy.Default"/></param>
/// <remarks>It is the responsibility of the user to close the connection after use through <see cref="CloseAsync"/></remarks>
[Obsolete("This constructor is obsolete. Use ServiceBusConnection(string namespaceConnectionString, RetryPolicy retryPolicy) constructor instead, providing operationTimeout in the connection string.")]
public ServiceBusConnection(string namespaceConnectionString, TimeSpan operationTimeout, RetryPolicy retryPolicy = null)
: this(retryPolicy)
{
if (string.IsNullOrWhiteSpace(namespaceConnectionString))
{
throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(namespaceConnectionString));
}
var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(namespaceConnectionString);
if (!string.IsNullOrWhiteSpace(serviceBusConnectionStringBuilder.EntityPath))
{
throw Fx.Exception.Argument(nameof(namespaceConnectionString), "NamespaceConnectionString should not contain EntityPath.");
}
this.InitializeConnection(serviceBusConnectionStringBuilder);
// operationTimeout argument explicitly provided by caller should take precedence over OperationTimeout found in the connection string.
this.OperationTimeout = operationTimeout;
}
/// <summary>
/// Creates a new connection to service bus.
/// </summary>
/// <param name="endpoint">Fully qualified domain name for Service Bus. Most likely, {yournamespace}.servicebus.windows.net</param>
/// <param name="transportType">Transport type.</param>
/// <param name="retryPolicy">Retry policy for operations. Defaults to <see cref="RetryPolicy.Default"/></param>
public ServiceBusConnection(string endpoint, TransportType transportType, RetryPolicy retryPolicy = null)
: this(retryPolicy)
{
if (string.IsNullOrWhiteSpace(endpoint))
{
throw Fx.Exception.ArgumentNullOrWhiteSpace(nameof(endpoint));
}
var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder()
{
Endpoint = endpoint,
TransportType = transportType
};
this.InitializeConnection(serviceBusConnectionStringBuilder);
}
internal ServiceBusConnection(RetryPolicy retryPolicy = null)
{
this.RetryPolicy = retryPolicy ?? RetryPolicy.Default;
this.syncLock = new object();
}
/// <summary>
/// Fully qualified domain name for Service Bus.
/// </summary>
public Uri Endpoint { get; set; }
/// <summary>
/// OperationTimeout is applied in erroneous situations to notify the caller about the relevant <see cref="ServiceBusException"/>
/// </summary>
/// <remarks>Defaults to 1 minute.</remarks>
public TimeSpan OperationTimeout { get; set; }
/// <summary>
/// ConnectionIdleTimeout is applied when a connection recevies no traffic for a certain period of time.
/// In some situations, underlying transport layer takes really long time to detect a socket error and it may
/// cause some operations to time out after a long wait. This timeout helps to detect and close an idle connection
/// without waiting for the network layer to identify a socket error. But this setting may result in some increased
/// heartbeat traffic between the client and service.
/// </summary>
/// <remarks>Defaults to null</remarks>
public TimeSpan? ConnectionIdleTimeout { get; set; }
/// <summary>
/// Retry policy for operations performed on the connection.
/// </summary>
/// <remarks>Defaults to <see cref="RetryPolicy.Default"/></remarks>
public RetryPolicy RetryPolicy { get; set; }
/// <summary>
/// Get the transport type from the connection string.
/// <remarks>Available options: Amqp and AmqpWebSockets.</remarks>
/// </summary>
public TransportType TransportType { get; set; }
/// <summary>
/// Token provider for authentication. <see cref="TokenProvider"/>
/// </summary>
public ITokenProvider TokenProvider { get; set; }
/// <summary>
/// Returns true if the Service Bus Connection is closed or closing.
/// </summary>
public bool IsClosedOrClosing
{
get
{
lock (syncLock)
{
return isClosedOrClosing;
}
}
internal set
{
lock (syncLock)
{
isClosedOrClosing = value;
}
}
}
internal FaultTolerantAmqpObject<AmqpConnection> ConnectionManager { get; set; }
internal FaultTolerantAmqpObject<Controller> TransactionController { get; set; }
/// <summary>
/// Throw an OperationCanceledException if the object is Closing.
/// </summary>
internal virtual void ThrowIfClosed()
{
if (this.IsClosedOrClosing)
{
throw new ObjectDisposedException($"{nameof(ServiceBusConnection)} has already been closed. Please create a new instance");
}
}
/// <summary>
/// Closes the connection.
/// </summary>
public async Task CloseAsync()
{
var callClose = false;
lock (this.syncLock)
{
if (!this.IsClosedOrClosing)
{
this.IsClosedOrClosing = true;
callClose = true;
}
}
if (callClose)
{
await this.ConnectionManager.CloseAsync().ConfigureAwait(false);
}
}
void InitializeConnection(ServiceBusConnectionStringBuilder builder)
{
this.Endpoint = new Uri(builder.Endpoint);
if (builder.SasToken != null)
{
this.TokenProvider = new SharedAccessSignatureTokenProvider(builder.SasToken);
}
else if (builder.SasKeyName != null || builder.SasKey != null)
{
this.TokenProvider = new SharedAccessSignatureTokenProvider(builder.SasKeyName, builder.SasKey);
}
else if (builder.Authentication.Equals(ServiceBusConnectionStringBuilder.AuthenticationType.ManagedIdentity))
{
this.TokenProvider = new ManagedIdentityTokenProvider();
}
this.OperationTimeout = builder.OperationTimeout;
this.TransportType = builder.TransportType;
this.ConnectionIdleTimeout = builder.ConnectionIdleTimeout;
this.ConnectionManager = new FaultTolerantAmqpObject<AmqpConnection>(this.CreateConnectionAsync, CloseConnection);
this.TransactionController = new FaultTolerantAmqpObject<Controller>(this.CreateControllerAsync, CloseController);
}
static void CloseConnection(AmqpConnection connection)
{
MessagingEventSource.Log.AmqpConnectionClosed(connection);
connection.SafeClose();
}
static void CloseController(Controller controller)
{
controller.Close();
}
async Task<AmqpConnection> CreateConnectionAsync(TimeSpan timeout)
{
var hostName = this.Endpoint.Host;
var timeoutHelper = new TimeoutHelper(timeout, true);
var amqpSettings = AmqpConnectionHelper.CreateAmqpSettings(
amqpVersion: AmqpVersion,
useSslStreamSecurity: true,
hasTokenProvider: true,
useWebSockets: TransportType == TransportType.AmqpWebSockets);
var transportSettings = CreateTransportSettings();
var amqpTransportInitiator = new AmqpTransportInitiator(amqpSettings, transportSettings);
var transport = await amqpTransportInitiator.ConnectTaskAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
var containerId = Guid.NewGuid().ToString();
var amqpConnectionSettings = AmqpConnectionHelper.CreateAmqpConnectionSettings(AmqpConstants.DefaultMaxFrameSize, containerId, hostName);
if (this.ConnectionIdleTimeout.HasValue && this.ConnectionIdleTimeout.Value > TimeSpan.Zero)
{
uint timeOutInMillis = checked((uint)this.ConnectionIdleTimeout.Value.TotalMilliseconds);
amqpConnectionSettings.IdleTimeOut = timeOutInMillis;
}
var connection = new AmqpConnection(transport, amqpSettings, amqpConnectionSettings);
await connection.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
// Always create the CBS Link + Session
var cbsLink = new AmqpCbsLink(connection);
if (connection.Extensions.Find<AmqpCbsLink>() == null)
{
connection.Extensions.Add(cbsLink);
}
MessagingEventSource.Log.AmqpConnectionCreated(hostName, connection);
return connection;
}
async Task<Controller> CreateControllerAsync(TimeSpan timeout)
{
var timeoutHelper = new TimeoutHelper(timeout, true);
var connection = await this.ConnectionManager.GetOrCreateAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
var sessionSettings = new AmqpSessionSettings { Properties = new Fields() };
AmqpSession amqpSession = null;
Controller controller;
try
{
amqpSession = connection.CreateSession(sessionSettings);
await amqpSession.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
controller = new Controller(amqpSession, timeoutHelper.RemainingTime());
await controller.OpenAsync(timeoutHelper.RemainingTime()).ConfigureAwait(false);
}
catch (Exception exception)
{
if (amqpSession != null)
{
await amqpSession.CloseAsync(timeout).ConfigureAwait(false);
}
MessagingEventSource.Log.AmqpCreateControllerException(this.ConnectionManager.ToString(), exception);
throw;
}
return controller;
}
TransportSettings CreateTransportSettings()
{
var hostName = this.Endpoint.Host;
var networkHost = this.Endpoint.Host;
var port = this.Endpoint.Port;
if (TransportType == TransportType.AmqpWebSockets)
{
return AmqpConnectionHelper.CreateWebSocketTransportSettings(
networkHost: networkHost,
hostName: hostName,
port: port,
proxy: WebRequest.DefaultWebProxy);
}
return AmqpConnectionHelper.CreateTcpTransportSettings(
networkHost: networkHost,
hostName: hostName,
port: port,
useSslStreamSecurity: true);
}
}
}