2021-11-15 19:02:23 +05:30
|
|
|
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusServiceBus;
|
|
|
|
|
2022-07-03 14:43:17 +03:00
|
|
|
public class EventBusServiceBus : IEventBus, IAsyncDisposable
|
2017-05-24 15:34:55 +02:00
|
|
|
{
|
2021-11-15 19:02:23 +05:30
|
|
|
private readonly IServiceBusPersisterConnection _serviceBusPersisterConnection;
|
|
|
|
private readonly ILogger<EventBusServiceBus> _logger;
|
|
|
|
private readonly IEventBusSubscriptionsManager _subsManager;
|
|
|
|
private readonly ILifetimeScope _autofac;
|
|
|
|
private readonly string _topicName = "eshop_event_bus";
|
|
|
|
private readonly string _subscriptionName;
|
2022-07-03 14:43:17 +03:00
|
|
|
private readonly ServiceBusSender _sender;
|
|
|
|
private readonly ServiceBusProcessor _processor;
|
2021-11-15 19:02:23 +05:30
|
|
|
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, string subscriptionClientName)
|
2017-05-24 15:34:55 +02:00
|
|
|
{
|
2021-11-15 19:02:23 +05:30
|
|
|
_serviceBusPersisterConnection = serviceBusPersisterConnection;
|
|
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
|
|
_subsManager = subsManager ?? new InMemoryEventBusSubscriptionsManager();
|
|
|
|
_autofac = autofac;
|
|
|
|
_subscriptionName = subscriptionClientName;
|
|
|
|
_sender = _serviceBusPersisterConnection.TopicClient.CreateSender(_topicName);
|
|
|
|
ServiceBusProcessorOptions options = new ServiceBusProcessorOptions { MaxConcurrentCalls = 10, AutoCompleteMessages = false };
|
|
|
|
_processor = _serviceBusPersisterConnection.TopicClient.CreateProcessor(_topicName, _subscriptionName, options);
|
|
|
|
|
|
|
|
RemoveDefaultRule();
|
|
|
|
RegisterSubscriptionClientMessageHandlerAsync().GetAwaiter().GetResult();
|
|
|
|
}
|
2017-05-24 15:34:55 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
public void Publish(IntegrationEvent @event)
|
|
|
|
{
|
|
|
|
var eventName = @event.GetType().Name.Replace(INTEGRATION_EVENT_SUFFIX, "");
|
|
|
|
var jsonMessage = JsonSerializer.Serialize(@event, @event.GetType());
|
|
|
|
var body = Encoding.UTF8.GetBytes(jsonMessage);
|
2017-05-24 15:34:55 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
var message = new ServiceBusMessage
|
|
|
|
{
|
|
|
|
MessageId = Guid.NewGuid().ToString(),
|
|
|
|
Body = new BinaryData(body),
|
|
|
|
Subject = eventName,
|
|
|
|
};
|
|
|
|
|
|
|
|
_sender.SendMessageAsync(message)
|
|
|
|
.GetAwaiter()
|
|
|
|
.GetResult();
|
|
|
|
}
|
2017-05-24 15:34:55 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
public void SubscribeDynamic<TH>(string eventName)
|
|
|
|
where TH : IDynamicIntegrationEventHandler
|
|
|
|
{
|
|
|
|
_logger.LogInformation("Subscribing to dynamic event {EventName} with {EventHandler}", eventName, typeof(TH).Name);
|
2017-05-24 15:34:55 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
_subsManager.AddDynamicSubscription<TH>(eventName);
|
|
|
|
}
|
2019-03-04 19:08:14 +00:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
public void Subscribe<T, TH>()
|
|
|
|
where T : IntegrationEvent
|
|
|
|
where TH : IIntegrationEventHandler<T>
|
|
|
|
{
|
|
|
|
var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFFIX, "");
|
2017-06-26 18:05:02 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
var containsKey = _subsManager.HasSubscriptionsForEvent<T>();
|
|
|
|
if (!containsKey)
|
2017-05-24 15:34:55 +02:00
|
|
|
{
|
2021-11-15 19:02:23 +05:30
|
|
|
try
|
2017-05-26 01:35:19 +02:00
|
|
|
{
|
2021-11-15 19:02:23 +05:30
|
|
|
_serviceBusPersisterConnection.AdministrationClient.CreateRuleAsync(_topicName, _subscriptionName, new CreateRuleOptions
|
2017-05-24 15:34:55 +02:00
|
|
|
{
|
2021-11-15 19:02:23 +05:30
|
|
|
Filter = new CorrelationRuleFilter() { Subject = eventName },
|
|
|
|
Name = eventName
|
|
|
|
}).GetAwaiter().GetResult();
|
|
|
|
}
|
|
|
|
catch (ServiceBusException)
|
|
|
|
{
|
|
|
|
_logger.LogWarning("The messaging entity {eventName} already exists.", eventName);
|
2017-05-24 15:34:55 +02:00
|
|
|
}
|
2021-11-15 19:02:23 +05:30
|
|
|
}
|
2017-05-24 15:34:55 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
_logger.LogInformation("Subscribing to event {EventName} with {EventHandler}", eventName, typeof(TH).Name);
|
2019-03-04 19:08:14 +00:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
_subsManager.AddSubscription<T, TH>();
|
|
|
|
}
|
|
|
|
|
|
|
|
public void Unsubscribe<T, TH>()
|
|
|
|
where T : IntegrationEvent
|
|
|
|
where TH : IIntegrationEventHandler<T>
|
|
|
|
{
|
|
|
|
var eventName = typeof(T).Name.Replace(INTEGRATION_EVENT_SUFFIX, "");
|
2017-05-24 15:34:55 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
try
|
|
|
|
{
|
|
|
|
_serviceBusPersisterConnection
|
|
|
|
.AdministrationClient
|
|
|
|
.DeleteRuleAsync(_topicName, _subscriptionName, eventName)
|
|
|
|
.GetAwaiter()
|
|
|
|
.GetResult();
|
|
|
|
}
|
|
|
|
catch (ServiceBusException ex) when (ex.Reason == ServiceBusFailureReason.MessagingEntityNotFound)
|
2017-05-24 15:34:55 +02:00
|
|
|
{
|
2021-11-15 19:02:23 +05:30
|
|
|
_logger.LogWarning("The messaging entity {eventName} Could not be found.", eventName);
|
|
|
|
}
|
2017-05-24 15:34:55 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
_logger.LogInformation("Unsubscribing from event {EventName}", eventName);
|
2017-05-24 15:34:55 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
_subsManager.RemoveSubscription<T, TH>();
|
|
|
|
}
|
2019-03-04 19:08:14 +00:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
public void UnsubscribeDynamic<TH>(string eventName)
|
|
|
|
where TH : IDynamicIntegrationEventHandler
|
|
|
|
{
|
|
|
|
_logger.LogInformation("Unsubscribing from dynamic event {EventName}", eventName);
|
2017-05-24 15:34:55 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
_subsManager.RemoveDynamicSubscription<TH>(eventName);
|
|
|
|
}
|
2019-03-04 19:08:14 +00:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
private async Task RegisterSubscriptionClientMessageHandlerAsync()
|
|
|
|
{
|
|
|
|
_processor.ProcessMessageAsync +=
|
|
|
|
async (args) =>
|
|
|
|
{
|
|
|
|
var eventName = $"{args.Message.Subject}{INTEGRATION_EVENT_SUFFIX}";
|
|
|
|
string messageData = args.Message.Body.ToString();
|
2017-06-26 18:05:02 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
// Complete the message so that it is not received again.
|
|
|
|
if (await ProcessEvent(eventName, messageData))
|
2017-05-24 16:26:40 +02:00
|
|
|
{
|
2021-11-15 19:02:23 +05:30
|
|
|
await args.CompleteMessageAsync(args.Message);
|
|
|
|
}
|
|
|
|
};
|
2021-10-26 17:39:15 +08:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
_processor.ProcessErrorAsync += ErrorHandler;
|
|
|
|
await _processor.StartProcessingAsync();
|
|
|
|
}
|
2021-10-26 17:39:15 +08:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
private Task ErrorHandler(ProcessErrorEventArgs args)
|
|
|
|
{
|
|
|
|
var ex = args.Exception;
|
|
|
|
var context = args.ErrorSource;
|
2019-03-04 19:08:14 +00:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
_logger.LogError(ex, "ERROR handling message: {ExceptionMessage} - Context: {@ExceptionContext}", ex.Message, context);
|
2019-03-04 19:08:14 +00:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
return Task.CompletedTask;
|
|
|
|
}
|
2017-05-24 15:34:55 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
private async Task<bool> ProcessEvent(string eventName, string message)
|
|
|
|
{
|
|
|
|
var processed = false;
|
|
|
|
if (_subsManager.HasSubscriptionsForEvent(eventName))
|
2017-05-24 15:34:55 +02:00
|
|
|
{
|
2022-03-23 15:26:45 +01:00
|
|
|
var scope = _autofac.BeginLifetimeScope(AUTOFAC_SCOPE_NAME);
|
|
|
|
var subscriptions = _subsManager.GetHandlersForEvent(eventName);
|
|
|
|
foreach (var subscription in subscriptions)
|
2017-05-24 15:34:55 +02:00
|
|
|
{
|
2022-03-23 15:26:45 +01:00
|
|
|
if (subscription.IsDynamic)
|
2017-05-24 15:34:55 +02:00
|
|
|
{
|
2022-03-23 15:26:45 +01:00
|
|
|
if (scope.ResolveOptional(subscription.HandlerType) is not IDynamicIntegrationEventHandler handler) 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);
|
2022-07-03 14:43:17 +03:00
|
|
|
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new[] { integrationEvent });
|
2017-05-24 15:34:55 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-03-23 15:26:45 +01:00
|
|
|
processed = true;
|
2021-11-15 19:02:23 +05:30
|
|
|
return processed;
|
|
|
|
}
|
2017-05-26 01:35:19 +02:00
|
|
|
|
2021-11-15 19:02:23 +05:30
|
|
|
private void RemoveDefaultRule()
|
|
|
|
{
|
|
|
|
try
|
2017-05-26 01:35:19 +02:00
|
|
|
{
|
2021-11-15 19:02:23 +05:30
|
|
|
_serviceBusPersisterConnection
|
|
|
|
.AdministrationClient
|
|
|
|
.DeleteRuleAsync(_topicName, _subscriptionName, RuleProperties.DefaultRuleName)
|
|
|
|
.GetAwaiter()
|
|
|
|
.GetResult();
|
|
|
|
}
|
|
|
|
catch (ServiceBusException ex) when (ex.Reason == ServiceBusFailureReason.MessagingEntityNotFound)
|
|
|
|
{
|
|
|
|
_logger.LogWarning("The messaging entity {DefaultRuleName} Could not be found.", RuleProperties.DefaultRuleName);
|
2017-05-26 01:35:19 +02:00
|
|
|
}
|
2017-05-24 15:34:55 +02:00
|
|
|
}
|
2022-07-03 14:43:17 +03:00
|
|
|
|
|
|
|
public async ValueTask DisposeAsync()
|
|
|
|
{
|
|
|
|
_subsManager.Clear();
|
|
|
|
await _processor.CloseAsync();
|
|
|
|
}
|
2021-11-15 19:02:23 +05:30
|
|
|
}
|