|
|
@ -1,203 +1,191 @@ |
|
|
|
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus |
|
|
|
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus; |
|
|
|
|
|
|
|
public class EventBusServiceBus : IEventBus |
|
|
|
{ |
|
|
|
using Autofac; |
|
|
|
using Microsoft.Azure.ServiceBus; |
|
|
|
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus; |
|
|
|
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions; |
|
|
|
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events; |
|
|
|
using Microsoft.Extensions.Logging; |
|
|
|
using System; |
|
|
|
using System.Text; |
|
|
|
using System.Text.Json; |
|
|
|
using System.Threading.Tasks; |
|
|
|
|
|
|
|
public class EventBusServiceBus : IEventBus |
|
|
|
private readonly IServiceBusPersisterConnection _serviceBusPersisterConnection; |
|
|
|
private readonly ILogger<EventBusServiceBus> _logger; |
|
|
|
private readonly IEventBusSubscriptionsManager _subsManager; |
|
|
|
private readonly ILifetimeScope _autofac; |
|
|
|
private readonly string AUTOFAC_SCOPE_NAME = "eshop_event_bus"; |
|
|
|
private const string INTEGRATION_EVENT_SUFFIX = "IntegrationEvent"; |
|
|
|
|
|
|
|
public EventBusServiceBus(IServiceBusPersisterConnection serviceBusPersisterConnection, |
|
|
|
ILogger<EventBusServiceBus> logger, IEventBusSubscriptionsManager subsManager, ILifetimeScope autofac) |
|
|
|
{ |
|
|
|
private readonly IServiceBusPersisterConnection _serviceBusPersisterConnection; |
|
|
|
private readonly ILogger<EventBusServiceBus> _logger; |
|
|
|
private readonly IEventBusSubscriptionsManager _subsManager; |
|
|
|
private readonly ILifetimeScope _autofac; |
|
|
|
private readonly string AUTOFAC_SCOPE_NAME = "eshop_event_bus"; |
|
|
|
private const string INTEGRATION_EVENT_SUFFIX = "IntegrationEvent"; |
|
|
|
|
|
|
|
public EventBusServiceBus(IServiceBusPersisterConnection serviceBusPersisterConnection, |
|
|
|
ILogger<EventBusServiceBus> logger, IEventBusSubscriptionsManager subsManager, ILifetimeScope autofac) |
|
|
|
{ |
|
|
|
_serviceBusPersisterConnection = serviceBusPersisterConnection; |
|
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
|
|
|
_subsManager = subsManager ?? new InMemoryEventBusSubscriptionsManager(); |
|
|
|
_autofac = autofac; |
|
|
|
|
|
|
|
RemoveDefaultRule(); |
|
|
|
RegisterSubscriptionClientMessageHandler(); |
|
|
|
} |
|
|
|
|
|
|
|
public void Publish(IntegrationEvent @event) |
|
|
|
{ |
|
|
|
var eventName = @event.GetType().Name.Replace(INTEGRATION_EVENT_SUFFIX, ""); |
|
|
|
var jsonMessage = JsonSerializer.Serialize(@event); |
|
|
|
var body = Encoding.UTF8.GetBytes(jsonMessage); |
|
|
|
|
|
|
|
var message = new Message |
|
|
|
{ |
|
|
|
MessageId = Guid.NewGuid().ToString(), |
|
|
|
Body = body, |
|
|
|
Label = eventName, |
|
|
|
}; |
|
|
|
|
|
|
|
_serviceBusPersisterConnection.TopicClient.SendAsync(message) |
|
|
|
.GetAwaiter() |
|
|
|
.GetResult(); |
|
|
|
} |
|
|
|
_serviceBusPersisterConnection = serviceBusPersisterConnection; |
|
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
|
|
|
_subsManager = subsManager ?? new InMemoryEventBusSubscriptionsManager(); |
|
|
|
_autofac = autofac; |
|
|
|
|
|
|
|
public void SubscribeDynamic<TH>(string eventName) |
|
|
|
where TH : IDynamicIntegrationEventHandler |
|
|
|
{ |
|
|
|
_logger.LogInformation("Subscribing to dynamic event {EventName} with {EventHandler}", eventName, typeof(TH).Name); |
|
|
|
RemoveDefaultRule(); |
|
|
|
RegisterSubscriptionClientMessageHandler(); |
|
|
|
} |
|
|
|
|
|
|
|
_subsManager.AddDynamicSubscription<TH>(eventName); |
|
|
|
} |
|
|
|
public void Publish(IntegrationEvent @event) |
|
|
|
{ |
|
|
|
var eventName = @event.GetType().Name.Replace(INTEGRATION_EVENT_SUFFIX, ""); |
|
|
|
var jsonMessage = JsonSerializer.Serialize(@event); |
|
|
|
var body = Encoding.UTF8.GetBytes(jsonMessage); |
|
|
|
|
|
|
|
public void Subscribe<T, TH>() |
|
|
|
where T : IntegrationEvent |
|
|
|
where TH : IIntegrationEventHandler<T> |
|
|
|
var message = new Message |
|
|
|
{ |
|
|
|
var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFFIX, ""); |
|
|
|
MessageId = Guid.NewGuid().ToString(), |
|
|
|
Body = body, |
|
|
|
Label = eventName, |
|
|
|
}; |
|
|
|
|
|
|
|
_serviceBusPersisterConnection.TopicClient.SendAsync(message) |
|
|
|
.GetAwaiter() |
|
|
|
.GetResult(); |
|
|
|
} |
|
|
|
|
|
|
|
var containsKey = _subsManager.HasSubscriptionsForEvent<T>(); |
|
|
|
if (!containsKey) |
|
|
|
{ |
|
|
|
try |
|
|
|
{ |
|
|
|
_serviceBusPersisterConnection.SubscriptionClient.AddRuleAsync(new RuleDescription |
|
|
|
{ |
|
|
|
Filter = new CorrelationFilter { Label = eventName }, |
|
|
|
Name = eventName |
|
|
|
}).GetAwaiter().GetResult(); |
|
|
|
} |
|
|
|
catch (ServiceBusException) |
|
|
|
{ |
|
|
|
_logger.LogWarning("The messaging entity {eventName} already exists.", eventName); |
|
|
|
} |
|
|
|
} |
|
|
|
public void SubscribeDynamic<TH>(string eventName) |
|
|
|
where TH : IDynamicIntegrationEventHandler |
|
|
|
{ |
|
|
|
_logger.LogInformation("Subscribing to dynamic event {EventName} with {EventHandler}", eventName, typeof(TH).Name); |
|
|
|
|
|
|
|
_logger.LogInformation("Subscribing to event {EventName} with {EventHandler}", eventName, typeof(TH).Name); |
|
|
|
_subsManager.AddDynamicSubscription<TH>(eventName); |
|
|
|
} |
|
|
|
|
|
|
|
_subsManager.AddSubscription<T, TH>(); |
|
|
|
} |
|
|
|
public void Subscribe<T, TH>() |
|
|
|
where T : IntegrationEvent |
|
|
|
where TH : IIntegrationEventHandler<T> |
|
|
|
{ |
|
|
|
var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFFIX, ""); |
|
|
|
|
|
|
|
public void Unsubscribe<T, TH>() |
|
|
|
where T : IntegrationEvent |
|
|
|
where TH : IIntegrationEventHandler<T> |
|
|
|
var containsKey = _subsManager.HasSubscriptionsForEvent<T>(); |
|
|
|
if (!containsKey) |
|
|
|
{ |
|
|
|
var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFFIX, ""); |
|
|
|
|
|
|
|
try |
|
|
|
{ |
|
|
|
_serviceBusPersisterConnection |
|
|
|
.SubscriptionClient |
|
|
|
.RemoveRuleAsync(eventName) |
|
|
|
.GetAwaiter() |
|
|
|
.GetResult(); |
|
|
|
_serviceBusPersisterConnection.SubscriptionClient.AddRuleAsync(new RuleDescription |
|
|
|
{ |
|
|
|
Filter = new CorrelationFilter { Label = eventName }, |
|
|
|
Name = eventName |
|
|
|
}).GetAwaiter().GetResult(); |
|
|
|
} |
|
|
|
catch (MessagingEntityNotFoundException) |
|
|
|
catch (ServiceBusException) |
|
|
|
{ |
|
|
|
_logger.LogWarning("The messaging entity {eventName} Could not be found.", eventName); |
|
|
|
_logger.LogWarning("The messaging entity {eventName} already exists.", eventName); |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
_logger.LogInformation("Unsubscribing from event {EventName}", eventName); |
|
|
|
_logger.LogInformation("Subscribing to event {EventName} with {EventHandler}", eventName, typeof(TH).Name); |
|
|
|
|
|
|
|
_subsManager.RemoveSubscription<T, TH>(); |
|
|
|
} |
|
|
|
_subsManager.AddSubscription<T, TH>(); |
|
|
|
} |
|
|
|
|
|
|
|
public void UnsubscribeDynamic<TH>(string eventName) |
|
|
|
where TH : IDynamicIntegrationEventHandler |
|
|
|
{ |
|
|
|
_logger.LogInformation("Unsubscribing from dynamic event {EventName}", eventName); |
|
|
|
public void Unsubscribe<T, TH>() |
|
|
|
where T : IntegrationEvent |
|
|
|
where TH : IIntegrationEventHandler<T> |
|
|
|
{ |
|
|
|
var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFFIX, ""); |
|
|
|
|
|
|
|
_subsManager.RemoveDynamicSubscription<TH>(eventName); |
|
|
|
try |
|
|
|
{ |
|
|
|
_serviceBusPersisterConnection |
|
|
|
.SubscriptionClient |
|
|
|
.RemoveRuleAsync(eventName) |
|
|
|
.GetAwaiter() |
|
|
|
.GetResult(); |
|
|
|
} |
|
|
|
|
|
|
|
public void Dispose() |
|
|
|
catch (MessagingEntityNotFoundException) |
|
|
|
{ |
|
|
|
_subsManager.Clear(); |
|
|
|
_logger.LogWarning("The messaging entity {eventName} Could not be found.", eventName); |
|
|
|
} |
|
|
|
|
|
|
|
private void RegisterSubscriptionClientMessageHandler() |
|
|
|
{ |
|
|
|
_serviceBusPersisterConnection.SubscriptionClient.RegisterMessageHandler( |
|
|
|
async (message, token) => |
|
|
|
{ |
|
|
|
var eventName = $"{message.Label}{INTEGRATION_EVENT_SUFFIX}"; |
|
|
|
var messageData = Encoding.UTF8.GetString(message.Body); |
|
|
|
_logger.LogInformation("Unsubscribing from event {EventName}", eventName); |
|
|
|
|
|
|
|
// Complete the message so that it is not received again.
|
|
|
|
if (await ProcessEvent(eventName, messageData)) |
|
|
|
{ |
|
|
|
await _serviceBusPersisterConnection.SubscriptionClient.CompleteAsync(message.SystemProperties.LockToken); |
|
|
|
} |
|
|
|
}, |
|
|
|
new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 10, AutoComplete = false }); |
|
|
|
} |
|
|
|
_subsManager.RemoveSubscription<T, TH>(); |
|
|
|
} |
|
|
|
|
|
|
|
private Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs) |
|
|
|
{ |
|
|
|
var ex = exceptionReceivedEventArgs.Exception; |
|
|
|
var context = exceptionReceivedEventArgs.ExceptionReceivedContext; |
|
|
|
public void UnsubscribeDynamic<TH>(string eventName) |
|
|
|
where TH : IDynamicIntegrationEventHandler |
|
|
|
{ |
|
|
|
_logger.LogInformation("Unsubscribing from dynamic event {EventName}", eventName); |
|
|
|
|
|
|
|
_logger.LogError(ex, "ERROR handling message: {ExceptionMessage} - Context: {@ExceptionContext}", ex.Message, context); |
|
|
|
_subsManager.RemoveDynamicSubscription<TH>(eventName); |
|
|
|
} |
|
|
|
|
|
|
|
return Task.CompletedTask; |
|
|
|
} |
|
|
|
public void Dispose() |
|
|
|
{ |
|
|
|
_subsManager.Clear(); |
|
|
|
} |
|
|
|
|
|
|
|
private void RegisterSubscriptionClientMessageHandler() |
|
|
|
{ |
|
|
|
_serviceBusPersisterConnection.SubscriptionClient.RegisterMessageHandler( |
|
|
|
async (message, token) => |
|
|
|
{ |
|
|
|
var eventName = $"{message.Label}{INTEGRATION_EVENT_SUFFIX}"; |
|
|
|
var messageData = Encoding.UTF8.GetString(message.Body); |
|
|
|
|
|
|
|
// Complete the message so that it is not received again.
|
|
|
|
if (await ProcessEvent(eventName, messageData)) |
|
|
|
{ |
|
|
|
await _serviceBusPersisterConnection.SubscriptionClient.CompleteAsync(message.SystemProperties.LockToken); |
|
|
|
} |
|
|
|
}, |
|
|
|
new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 10, AutoComplete = false }); |
|
|
|
} |
|
|
|
|
|
|
|
private async Task<bool> ProcessEvent(string eventName, string message) |
|
|
|
private Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs) |
|
|
|
{ |
|
|
|
var ex = exceptionReceivedEventArgs.Exception; |
|
|
|
var context = exceptionReceivedEventArgs.ExceptionReceivedContext; |
|
|
|
|
|
|
|
_logger.LogError(ex, "ERROR handling message: {ExceptionMessage} - Context: {@ExceptionContext}", ex.Message, context); |
|
|
|
|
|
|
|
return Task.CompletedTask; |
|
|
|
} |
|
|
|
|
|
|
|
private async Task<bool> ProcessEvent(string eventName, string message) |
|
|
|
{ |
|
|
|
var processed = false; |
|
|
|
if (_subsManager.HasSubscriptionsForEvent(eventName)) |
|
|
|
{ |
|
|
|
var processed = false; |
|
|
|
if (_subsManager.HasSubscriptionsForEvent(eventName)) |
|
|
|
using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME)) |
|
|
|
{ |
|
|
|
using (var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME)) |
|
|
|
var subscriptions = _subsManager.GetHandlersForEvent(eventName); |
|
|
|
foreach (var subscription in subscriptions) |
|
|
|
{ |
|
|
|
var subscriptions = _subsManager.GetHandlersForEvent(eventName); |
|
|
|
foreach (var subscription in subscriptions) |
|
|
|
if (subscription.IsDynamic) |
|
|
|
{ |
|
|
|
if (subscription.IsDynamic) |
|
|
|
{ |
|
|
|
var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler; |
|
|
|
if (handler == null) continue; |
|
|
|
var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler; |
|
|
|
if (handler == null) continue; |
|
|
|
|
|
|
|
using dynamic eventData = JsonDocument.Parse(message); |
|
|
|
await handler.Handle(eventData); |
|
|
|
} |
|
|
|
else |
|
|
|
{ |
|
|
|
var handler = scope.ResolveOptional(subscription.HandlerType); |
|
|
|
if (handler == null) continue; |
|
|
|
var eventType = _subsManager.GetEventTypeByName(eventName); |
|
|
|
var integrationEvent = JsonSerializer.Deserialize(message, eventType); |
|
|
|
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); |
|
|
|
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent }); |
|
|
|
} |
|
|
|
using dynamic eventData = JsonDocument.Parse(message); |
|
|
|
await handler.Handle(eventData); |
|
|
|
} |
|
|
|
else |
|
|
|
{ |
|
|
|
var handler = scope.ResolveOptional(subscription.HandlerType); |
|
|
|
if (handler == null) continue; |
|
|
|
var eventType = _subsManager.GetEventTypeByName(eventName); |
|
|
|
var integrationEvent = JsonSerializer.Deserialize(message, eventType); |
|
|
|
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType); |
|
|
|
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent }); |
|
|
|
} |
|
|
|
} |
|
|
|
processed = true; |
|
|
|
} |
|
|
|
return processed; |
|
|
|
processed = true; |
|
|
|
} |
|
|
|
return processed; |
|
|
|
} |
|
|
|
|
|
|
|
private void RemoveDefaultRule() |
|
|
|
private void RemoveDefaultRule() |
|
|
|
{ |
|
|
|
try |
|
|
|
{ |
|
|
|
try |
|
|
|
{ |
|
|
|
_serviceBusPersisterConnection |
|
|
|
.SubscriptionClient |
|
|
|
.RemoveRuleAsync(RuleDescription.DefaultRuleName) |
|
|
|
.GetAwaiter() |
|
|
|
.GetResult(); |
|
|
|
} |
|
|
|
catch (MessagingEntityNotFoundException) |
|
|
|
{ |
|
|
|
_logger.LogWarning("The messaging entity {DefaultRuleName} Could not be found.", RuleDescription.DefaultRuleName); |
|
|
|
} |
|
|
|
_serviceBusPersisterConnection |
|
|
|
.SubscriptionClient |
|
|
|
.RemoveRuleAsync(RuleDescription.DefaultRuleName) |
|
|
|
.GetAwaiter() |
|
|
|
.GetResult(); |
|
|
|
} |
|
|
|
catch (MessagingEntityNotFoundException) |
|
|
|
{ |
|
|
|
_logger.LogWarning("The messaging entity {DefaultRuleName} Could not be found.", RuleDescription.DefaultRuleName); |
|
|
|
} |
|
|
|
} |
|
|
|
} |