-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRabbitMqBus.cs
317 lines (246 loc) · 10.4 KB
/
RabbitMqBus.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
using System.Net.Sockets;
using System.Text;
using System.Text.Json;
using Autofac;
using Infra.Core.EventBus;
using Infra.Core.EventBus.Abstractions;
using Infra.Core.EventBus.Events;
using Infra.Core.EventBus.Extensions;
using Infra.Core.Extensions;
using Infra.EventBus.RabbitMQ.Abstractions;
using Infra.EventBus.RabbitMQ.Configuration;
using Infra.EventBus.RabbitMQ.Configuration.Validators;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Polly;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
namespace Infra.EventBus.RabbitMQ;
public class RabbitMqBus : IEventBus, IDisposable
{
private const string RabbitmqExchangeName = "event.bus";
private const string RabbitmqType = "direct";
private const string AutofacScopeName = "event.bus";
private readonly ILogger<RabbitMqBus> logger;
private readonly Settings settings;
private readonly IRabbitMqConnection connection;
private readonly IEventBusSubscriptionsManager subsManager;
private readonly ILifetimeScope autofac;
private readonly JsonSerializerOptions jsonSerializeOptions = new() { WriteIndented = true };
private readonly JsonSerializerOptions jsonDeserializeOptions = new() { PropertyNameCaseInsensitive = true };
private IModel consumer;
private bool disposed;
#region Constructor
public RabbitMqBus(
ILogger<RabbitMqBus> logger,
IOptions<Settings> settings,
IRabbitMqConnection connection,
IEventBusSubscriptionsManager subsManager,
ILifetimeScope autofac)
{
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
this.settings = SettingsValidator.TryValidate(settings.Value, out var validationException) ? settings.Value : throw validationException;
this.connection = connection ?? throw new ArgumentNullException(nameof(connection));
this.subsManager = subsManager ?? new InMemoryEventBusSubscriptionsManager();
this.autofac = autofac;
consumer = CreateConsumer();
this.subsManager.OnEventRemoved += SubsManager_OnEventRemoved;
}
#endregion
public void Publish(IntegrationEvent integrationEvent)
{
if (!connection.IsConnected)
connection.TryConnect();
var policy = Policy.Handle<SocketException>()
.Or<BrokerUnreachableException>()
.WaitAndRetry(settings.RetryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time)
=> logger.Warning(ex, $"Could not publish event: {integrationEvent.Id} after {time.TotalSeconds:n1}s. ({ex.Message})"));
policy.Execute(() =>
{
var eventName = integrationEvent.GetType().Name;
logger.Trace($"Creating RabbitMQ channel to publish event: {integrationEvent.Id}. ({eventName})");
using var channel = connection.CreateChannel();
logger.Trace($"Declaring RabbitMQ exchange to publish event: {integrationEvent.Id}.");
channel.ExchangeDeclare(exchange: RabbitmqExchangeName, type: RabbitmqType);
var body = JsonSerializer.SerializeToUtf8Bytes(integrationEvent, integrationEvent.GetType(), jsonSerializeOptions);
var properties = channel.CreateBasicProperties();
properties.DeliveryMode = 2; // persistent
logger.Trace($"Publishing event to RabbitMQ: {integrationEvent.Id}.");
channel.BasicPublish(
exchange: RabbitmqExchangeName,
routingKey: eventName,
mandatory: true,
basicProperties: properties,
body: body);
});
}
public void Subscribe<TIntegrationEvent, TIntegrationEventHandler>()
where TIntegrationEvent : IntegrationEvent
where TIntegrationEventHandler : IIntegrationEventHandler<TIntegrationEvent>
{
var eventName = subsManager.GetEventName<TIntegrationEvent>();
DoInternalSubscription(eventName);
logger.Information($"Subscribing to event {eventName} with {typeof(TIntegrationEventHandler).GetGenericTypeName()}.");
subsManager.AddSubscription<TIntegrationEvent, TIntegrationEventHandler>();
StartBasicConsume();
}
public void SubscribeDynamic<TDynamicIntegrationEventHandler>(string eventName) where TDynamicIntegrationEventHandler : IDynamicIntegrationEventHandler
{
logger.Information($"Subscribing to dynamic event {eventName} with {typeof(TDynamicIntegrationEventHandler).GetGenericTypeName()}.");
DoInternalSubscription(eventName);
subsManager.AddDynamicSubscription<TDynamicIntegrationEventHandler>(eventName);
StartBasicConsume();
}
public void Unsubscribe<TIntegrationEvent, TIntegrationEventHandler>()
where TIntegrationEvent : IntegrationEvent
where TIntegrationEventHandler : IIntegrationEventHandler<TIntegrationEvent>
{
var eventName = subsManager.GetEventName<TIntegrationEvent>();
logger.Information($"Unsubscribing from event {eventName}.");
subsManager.RemoveSubscription<TIntegrationEvent, TIntegrationEventHandler>();
}
public void UnsubscribeDynamic<TDynamicIntegrationEventHandler>(string eventName) where TDynamicIntegrationEventHandler : IDynamicIntegrationEventHandler
{
logger.Information($"Unsubscribing from dynamic event {eventName}.");
subsManager.RemoveDynamicSubscription<TDynamicIntegrationEventHandler>(eventName);
}
#region Private Method
private void SubsManager_OnEventRemoved(object sender, string eventName)
{
if (!connection.IsConnected)
connection.TryConnect();
using var channel = connection.CreateChannel();
channel.QueueUnbind(
queue: settings.QueueName,
exchange: RabbitmqExchangeName,
routingKey: eventName);
if (subsManager.IsEmpty)
consumer.Close();
}
private void DoInternalSubscription(string eventName)
{
if (!subsManager.HasSubscriptionsForEvent(eventName))
{
if (!connection.IsConnected)
connection.TryConnect();
consumer.QueueBind(
queue: settings.QueueName,
exchange: RabbitmqExchangeName,
routingKey: eventName);
}
}
private IModel CreateConsumer()
{
if (!connection.IsConnected)
connection.TryConnect();
logger.Trace("Creating RabbitMQ consumer channel.");
var channel = connection.CreateChannel();
channel.ExchangeDeclare(
exchange: RabbitmqExchangeName,
type: RabbitmqType);
channel.QueueDeclare(
queue: settings.QueueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
channel.CallbackException += (_, ea) =>
{
logger.Warning(ea.Exception, "Recreating RabbitMQ consumer channel.");
consumer.Dispose();
consumer = CreateConsumer();
StartBasicConsume();
};
return channel;
}
private void StartBasicConsume()
{
logger.Trace("Starting RabbitMQ basic consume.");
if (consumer != null)
{
var basicConsumer = new AsyncEventingBasicConsumer(consumer);
basicConsumer.Received += Consumer_Received;
consumer.BasicConsume(
queue: settings.QueueName,
autoAck: false,
consumer: basicConsumer);
}
else
{
logger.Error("StartBasicConsume can't call on _consumerChannel == null .");
}
}
private async Task Consumer_Received(object sender, BasicDeliverEventArgs eventArgs)
{
var eventName = eventArgs.RoutingKey;
var message = Encoding.UTF8.GetString(eventArgs.Body.Span);
try
{
await ProcessEvent(eventName, message);
}
catch (Exception ex)
{
logger.Warning(ex, $"----- ERROR Processing message \"{message}\"");
}
// Even on exception we take the message off the queue.
// in a REAL WORLD app this should be handled with a Dead Letter Exchange (DLX).
// For more information see: https://www.rabbitmq.com/dlx.html
consumer.BasicAck(eventArgs.DeliveryTag, multiple: false);
}
private async Task ProcessEvent(string eventName, string message)
{
logger.Trace($"Processing RabbitMQ event: {eventName}");
if (subsManager.HasSubscriptionsForEvent(eventName))
{
await using var scope = autofac.BeginLifetimeScope(AutofacScopeName);
var subscriptions = subsManager.GetHandlersForEvent(eventName);
foreach (var subscription in subscriptions)
{
if (subscription.IsDynamic)
{
if (scope.ResolveOptional(subscription.HandlerType) is not IDynamicIntegrationEventHandler handler)
continue;
using dynamic eventData = JsonDocument.Parse(message);
await Task.Yield();
await handler.HandleAsync(eventData);
}
else
{
var handler = scope.ResolveOptional(subscription.HandlerType);
if (handler is null)
continue;
var eventType = subsManager.GetEventTypeByName(eventName);
var integrationEvent = JsonSerializer.Deserialize(message, eventType, jsonDeserializeOptions);
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await Task.Yield();
await ((Task)concreteType.GetMethod("HandleAsync")?.Invoke(handler, [integrationEvent]))!;
}
}
}
else
{
logger.Warning($"No subscription for RabbitMQ event: {eventName}");
}
}
#endregion
#region Dispose
~RabbitMqBus() => Dispose(false);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
consumer?.Dispose();
subsManager.Clear();
}
disposed = true;
}
#endregion
}