-
Notifications
You must be signed in to change notification settings - Fork 7
/
RabbitMQHost.cs
302 lines (272 loc) · 13 KB
/
RabbitMQHost.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
// The MIT License (MIT)
//
// Copyright (c) 2016 Jesse Sweetland
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using Platibus.Journaling;
using Platibus.Security;
using Platibus.Utils;
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Platibus.RabbitMQ
{
/// <inheritdoc cref="ITransportService" />
/// <inheritdoc cref="IQueueListener" />
/// <inheritdoc cref="IDisposable" />
/// <summary>
/// Hosts for a bus instance whose queueing and transport are based on RabbitMQ queues
/// </summary>
public class RabbitMQHost : IQueueListener, IDisposable
{
/// <summary>
/// Creates and starts a new <see cref="RabbitMQHost"/>
/// </summary>
/// <returns>Returns the fully initialized and listening RabbitMQ host</returns>
#if NET452 || NET461
/// <seealso cref="RabbitMQHostConfigurationSection"/>
#endif
public static RabbitMQHost Start() => Start(null, _ => { });
/// <summary>
/// Creates and starts a new <see cref="RabbitMQHost"/>
/// </summary>
/// <param name="configSectionName">The name of the configuration section containing
/// the RabbitMQ host configuration</param>
/// <returns>Returns the fully initialized and listening RabbitMQ host</returns>
#if NET452 || NET461
/// <seealso cref="RabbitMQHostConfigurationSection"/>
#endif
public static RabbitMQHost Start(string configSectionName) => Start(configSectionName, _ => { });
/// <summary>
/// Creates and starts a new <see cref="RabbitMQHost"/>
/// </summary>
/// <param name="configure">Delegate used to modify the configuration loaded
/// from the default configuration section</param>
/// <param name="cancellationToken">(Optional) A cancellation token that can be used by the
/// caller to cancel RabbitMQ host initialization</param>
/// <returns>Returns the fully initialized and listening RabbitMQ host</returns>
#if NET452 || NET461
/// <seealso cref="RabbitMQHostConfigurationSection"/>
#endif
public static RabbitMQHost Start(
Action<RabbitMQHostConfiguration> configure,
CancellationToken cancellationToken = default(CancellationToken)) => Start(null, configure, cancellationToken);
/// <summary>
/// Creates and starts a new <see cref="RabbitMQHost"/>
/// </summary>
/// <param name="configure">Delegate used to modify the configuration loaded
/// from the default configuration section</param>
/// <param name="cancellationToken">(Optional) A cancellation token that can be used by the
/// caller to cancel RabbitMQ host initialization</param>
/// <returns>Returns the fully initialized and listening RabbitMQ host</returns>
#if NET452 || NET461
/// <seealso cref="RabbitMQHostConfigurationSection"/>
#endif
public static RabbitMQHost Start(
Func<RabbitMQHostConfiguration, Task> configure,
CancellationToken cancellationToken = default(CancellationToken)) => Start(null, configure, cancellationToken);
/// <summary>
/// Creates and starts a new <see cref="RabbitMQHost"/>
/// </summary>
/// <param name="configSectionName">The name of the configuration section from which
/// declarative configuration should be loaded before invoking the <paramref name="configure"/></param>
/// <param name="configure">Delegate used to modify the configuration loaded
/// from the default configuration section</param>
/// <param name="cancellationToken">(Optional) A cancellation token that can be used by the
/// caller to cancel RabbitMQ host initialization</param>
/// <returns>Returns the fully initialized and listening RabbitMQ host</returns>
#if NET452 || NET461
/// <seealso cref="RabbitMQHostConfigurationSection"/>
#endif
public static RabbitMQHost Start(
string configSectionName,
Action<RabbitMQHostConfiguration> configure,
CancellationToken cancellationToken = default(CancellationToken))
{
return Start(configSectionName, configuration =>
{
configure?.Invoke(configuration);
return Task.FromResult(0);
}, cancellationToken);
}
/// <summary>
/// Creates and starts a new <see cref="RabbitMQHost"/>
/// </summary>
/// <param name="configSectionName">The name of the configuration section from which
/// declarative configuration should be loaded before invoking the
/// <paramref name="configure"/></param>
/// <param name="configure">Delegate used to modify the configuration loaded
/// from the default configuration section</param>
/// <param name="cancellationToken">(Optional) A cancellation token that can be used by the
/// caller to cancel RabbitMQ host initialization</param>
/// <returns>Returns the fully initialized and listening RabbitMQ host</returns>
#if NET452 || NET461
/// <seealso cref="RabbitMQHostConfigurationSection"/>
#endif
public static RabbitMQHost Start(
string configSectionName,
Func<RabbitMQHostConfiguration, Task> configure,
CancellationToken cancellationToken = default(CancellationToken))
{
return StartAsync(configSectionName, configure, cancellationToken)
.GetResultFromCompletionSource(cancellationToken);
}
/// <summary>
/// Creates and starts a new <see cref="RabbitMQHost"/>
/// </summary>
/// <param name="configuration">The HTTP sever configuration</param>
/// <param name="cancellationToken">(Optional) A cancellation token that can be used by the
/// caller to cancel RabbitMQ host initialization</param>
/// <returns>Returns the fully initialized and listening RabbitMQ host</returns>
public static RabbitMQHost Start(IRabbitMQHostConfiguration configuration, CancellationToken cancellationToken = default(CancellationToken))
{
return StartAsync(configuration, cancellationToken)
.GetResultFromCompletionSource(cancellationToken);
}
private static async Task<RabbitMQHost> StartAsync(
string configSectionName,
Func<RabbitMQHostConfiguration, Task> configure,
CancellationToken cancellationToken = default(CancellationToken))
{
var configManager = new RabbitMQHostConfigurationManager();
var configuration = new RabbitMQHostConfiguration();
await configManager.Initialize(configuration, configSectionName);
#pragma warning disable 612
await configManager.FindAndProcessConfigurationHooks(configuration);
#pragma warning restore 612
if (configure != null)
{
await configure(configuration);
}
var server = await StartAsync(configuration, cancellationToken);
return server;
}
private static async Task<RabbitMQHost> StartAsync(
IRabbitMQHostConfiguration configuration,
CancellationToken cancellationToken = default(CancellationToken))
{
var server = new RabbitMQHost(configuration);
await server.Init(cancellationToken);
return server;
}
private readonly IConnectionManager _connectionManager;
private readonly IMessageQueueingService _messageQueueingService;
private readonly IMessageJournal _messageJournal;
private readonly RabbitMQTransportService _transportService;
private bool _disposed;
/// <summary>
/// The hosted bus instance
/// </summary>
public Bus Bus { get; }
private RabbitMQHost(IRabbitMQHostConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
var diagnosticService = configuration.DiagnosticService;
var baseUri = configuration.BaseUri.WithoutTrailingSlash();
_connectionManager = new ConnectionManager();
var encoding = configuration.Encoding ?? Encoding.UTF8;
var defaultQueueOptions = new QueueOptions
{
AutoAcknowledge = configuration.AutoAcknowledge,
MaxAttempts = configuration.MaxAttempts,
ConcurrencyLimit = configuration.ConcurrencyLimit,
RetryDelay = configuration.RetryDelay,
IsDurable = configuration.IsDurable
};
var securityTokenService = configuration.SecurityTokenService ?? new JwtSecurityTokenService();
_messageJournal = configuration.MessageJournal;
var queueingOptions = new RabbitMQMessageQueueingOptions(baseUri)
{
ConnectionManager = _connectionManager,
DefaultQueueOptions = defaultQueueOptions,
DiagnosticService = diagnosticService,
Encoding = encoding,
SecurityTokenService = securityTokenService
};
_messageQueueingService = new RabbitMQMessageQueueingService(queueingOptions);
var transportServiceOptions = new RabbitMQTransportServiceOptions(baseUri, _connectionManager)
{
DiagnosticService = configuration.DiagnosticService,
MessageJournal = configuration.MessageJournal,
SecurityTokenService = configuration.SecurityTokenService,
Encoding = configuration.Encoding,
DefaultQueueOptions = defaultQueueOptions,
Topics = configuration.Topics
};
_transportService = new RabbitMQTransportService(transportServiceOptions);
Bus = new Bus(configuration, configuration.BaseUri, _transportService, _messageQueueingService);
}
private async Task Init(CancellationToken cancellationToken = default(CancellationToken))
{
await Bus.Init(cancellationToken);
}
/// <inheritdoc />
async Task IQueueListener.MessageReceived(Message message, IQueuedMessageContext context, CancellationToken cancellationToken)
{
await _transportService.ReceiveMessage(message, context.Principal, cancellationToken);
await context.Acknowledge();
}
/// <summary>
/// Finalizer to ensure resources are released
/// </summary>
~RabbitMQHost()
{
Dispose(false);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
if (_disposed) return;
Dispose(true);
_disposed = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Called by the <see cref="Dispose()"/> method or finalizer to ensure that
/// resources are released
/// </summary>
/// <param name="disposing">Indicates whether this method is called from the
/// <see cref="Dispose()"/> method (<c>true</c>) or the finalizer (<c>false</c>)</param>
/// <remarks>
/// This method will not be called more than once
/// </remarks>
protected virtual void Dispose(bool disposing)
{
if (!disposing) return;
_transportService.Dispose();
Bus.Dispose();
if (_messageQueueingService is IDisposable disposableMessageQueueingService)
{
disposableMessageQueueingService.Dispose();
}
if (_messageJournal is IDisposable disposableMessageJournal)
{
disposableMessageJournal.Dispose();
}
if (_connectionManager is IDisposable disposableConnectionManager)
{
disposableConnectionManager.Dispose();
}
}
}
}