-
Notifications
You must be signed in to change notification settings - Fork 2k
/
RabbitMQEventBus.cs
301 lines (242 loc) · 11.7 KB
/
RabbitMQEventBus.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
namespace eShop.EventBusRabbitMQ;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using OpenTelemetry;
using OpenTelemetry.Context.Propagation;
public class RabbitMQEventBus(
ILogger<RabbitMQEventBus> logger,
IServiceProvider serviceProvider,
IOptions<EventBusOptions> options,
IOptions<EventBusSubscriptionInfo> subscriptionOptions,
RabbitMQTelemetry rabbitMQTelemetry) : IEventBus, IDisposable, IHostedService
{
private const string ExchangeName = "eshop_event_bus";
private readonly int _retryCount = options.Value.RetryCount;
private readonly TextMapPropagator _propagator = rabbitMQTelemetry.Propagator;
private readonly ActivitySource _activitySource = rabbitMQTelemetry.ActivitySource;
private string _queueName = options.Value.SubscriptionClientName;
private readonly EventBusSubscriptionInfo _subscriptionInfo = subscriptionOptions.Value;
private IConnection _rabbitMQConnection;
private IModel _consumerChannel;
public Task PublishAsync(IntegrationEvent @event)
{
var policy = Policy.Handle<BrokerUnreachableException>()
.Or<SocketException>()
.WaitAndRetryAsync(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
var routingKey = @event.GetType().Name;
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Creating RabbitMQ channel to publish event: {EventId} ({EventName})", @event.Id, routingKey);
}
using var channel = _rabbitMQConnection?.CreateModel() ?? throw new InvalidOperationException("RabbitMQ connection is not open");
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", @event.Id);
}
channel.ExchangeDeclare(exchange: ExchangeName, type: "direct");
var body = SerializeMessage(@event);
// Start an activity with a name following the semantic convention of the OpenTelemetry messaging specification.
// https://github.com/open-telemetry/semantic-conventions/blob/main/docs/messaging/messaging-spans.md
var activityName = $"{routingKey} publish";
return policy.ExecuteAsync(() =>
{
using var activity = _activitySource.StartActivity(activityName, ActivityKind.Client);
// Depending on Sampling (and whether a listener is registered or not), the activity above may not be created.
// If it is created, then propagate its context. If it is not created, the propagate the Current context, if any.
ActivityContext contextToInject = default;
if (activity != null)
{
contextToInject = activity.Context;
}
else if (Activity.Current != null)
{
contextToInject = Activity.Current.Context;
}
var properties = channel.CreateBasicProperties();
// persistent
properties.DeliveryMode = 2;
static void InjectTraceContextIntoBasicProperties(IBasicProperties props, string key, string value)
{
props.Headers ??= new Dictionary<string, object>();
props.Headers[key] = value;
}
_propagator.Inject(new PropagationContext(contextToInject, Baggage.Current), properties, InjectTraceContextIntoBasicProperties);
SetActivityContext(activity, routingKey, "publish");
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Publishing event to RabbitMQ: {EventId}", @event.Id);
}
try
{
channel.BasicPublish(
exchange: ExchangeName,
routingKey: routingKey,
mandatory: true,
basicProperties: properties,
body: body);
return Task.CompletedTask;
}
catch (Exception ex)
{
activity.SetExceptionTags(ex);
throw;
}
});
}
private static void SetActivityContext(Activity activity, string routingKey, string operation)
{
if (activity is not null)
{
// These tags are added demonstrating the semantic conventions of the OpenTelemetry messaging specification
// https://github.com/open-telemetry/semantic-conventions/blob/main/docs/messaging/messaging-spans.md
activity.SetTag("messaging.system", "rabbitmq");
activity.SetTag("messaging.destination_kind", "queue");
activity.SetTag("messaging.operation", operation);
activity.SetTag("messaging.destination.name", routingKey);
activity.SetTag("messaging.rabbitmq.routing_key", routingKey);
}
}
public void Dispose()
{
_consumerChannel?.Dispose();
}
private async Task OnMessageReceived(object sender, BasicDeliverEventArgs eventArgs)
{
static IEnumerable<string> ExtractTraceContextFromBasicProperties(IBasicProperties props, string key)
{
if (props.Headers.TryGetValue(key, out var value))
{
var bytes = value as byte[];
return [Encoding.UTF8.GetString(bytes)];
}
return [];
}
// Extract the PropagationContext of the upstream parent from the message headers.
var parentContext = _propagator.Extract(default, eventArgs.BasicProperties, ExtractTraceContextFromBasicProperties);
Baggage.Current = parentContext.Baggage;
// Start an activity with a name following the semantic convention of the OpenTelemetry messaging specification.
// https://github.com/open-telemetry/semantic-conventions/blob/main/docs/messaging/messaging-spans.md
var activityName = $"{eventArgs.RoutingKey} receive";
using var activity = _activitySource.StartActivity(activityName, ActivityKind.Client, parentContext.ActivityContext);
SetActivityContext(activity, eventArgs.RoutingKey, "receive");
var eventName = eventArgs.RoutingKey;
var message = Encoding.UTF8.GetString(eventArgs.Body.Span);
try
{
activity?.SetTag("message", message);
if (message.Contains("throw-fake-exception", StringComparison.InvariantCultureIgnoreCase))
{
throw new InvalidOperationException($"Fake exception requested: \"{message}\"");
}
await ProcessEvent(eventName, message);
}
catch (Exception ex)
{
logger.LogWarning(ex, "Error Processing message \"{Message}\"", message);
activity.SetExceptionTags(ex);
}
// 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
_consumerChannel.BasicAck(eventArgs.DeliveryTag, multiple: false);
}
private async Task ProcessEvent(string eventName, string message)
{
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Processing RabbitMQ event: {EventName}", eventName);
}
await using var scope = serviceProvider.CreateAsyncScope();
if (!_subscriptionInfo.EventTypes.TryGetValue(eventName, out var eventType))
{
logger.LogWarning("Unable to resolve event type for event name {EventName}", eventName);
return;
}
// REVIEW: This could be done in parallel
// Get all the handlers using the event type as the key
foreach (var handler in scope.ServiceProvider.GetKeyedServices<IIntegrationEventHandler>(eventType))
{
// Deserialize the event
var integrationEvent = DeserializeMessage(message, eventType);
await handler.Handle(integrationEvent);
}
}
[UnconditionalSuppressMessage("Trimming", "IL2026:RequiresUnreferencedCode",
Justification = "The 'JsonSerializer.IsReflectionEnabledByDefault' feature switch, which is set to false by default for trimmed .NET apps, ensures the JsonSerializer doesn't use Reflection.")]
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode", Justification = "See above.")]
private IntegrationEvent DeserializeMessage(string message, Type eventType)
{
return JsonSerializer.Deserialize(message, eventType, _subscriptionInfo.JsonSerializerOptions) as IntegrationEvent;
}
[UnconditionalSuppressMessage("Trimming", "IL2026:RequiresUnreferencedCode",
Justification = "The 'JsonSerializer.IsReflectionEnabledByDefault' feature switch, which is set to false by default for trimmed .NET apps, ensures the JsonSerializer doesn't use Reflection.")]
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode", Justification = "See above.")]
private byte[] SerializeMessage(IntegrationEvent @event)
{
return JsonSerializer.SerializeToUtf8Bytes(@event, @event.GetType(), _subscriptionInfo.JsonSerializerOptions);
}
public Task StartAsync(CancellationToken cancellationToken)
{
// Messaging is async so we don't need to wait for it to complete. On top of this
// the APIs are blocking, so we need to run this on a background thread.
_ = Task.Factory.StartNew(() =>
{
try
{
logger.LogInformation("Starting RabbitMQ connection on a background thread");
_rabbitMQConnection = serviceProvider.GetRequiredService<IConnection>();
if (!_rabbitMQConnection.IsOpen)
{
return;
}
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Creating RabbitMQ consumer channel");
}
_consumerChannel = _rabbitMQConnection.CreateModel();
_consumerChannel.CallbackException += (sender, ea) =>
{
logger.LogWarning(ea.Exception, "Error with RabbitMQ consumer channel");
};
_consumerChannel.ExchangeDeclare(exchange: ExchangeName,
type: "direct");
_consumerChannel.QueueDeclare(queue: _queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
if (logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Starting RabbitMQ basic consume");
}
var consumer = new AsyncEventingBasicConsumer(_consumerChannel);
consumer.Received += OnMessageReceived;
_consumerChannel.BasicConsume(
queue: _queueName,
autoAck: false,
consumer: consumer);
foreach (var (eventName, _) in _subscriptionInfo.EventTypes)
{
_consumerChannel.QueueBind(
queue: _queueName,
exchange: ExchangeName,
routingKey: eventName);
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error starting RabbitMQ connection");
}
},
TaskCreationOptions.LongRunning);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}