Browse Source

Merge pull request #26148 from abpframework/maliming/dynamic-job-tenant

Keep the tenant of dynamic background jobs and events
pull/26176/head
Ma Liming 2 months ago
committed by GitHub
parent
commit
185bf6ee65
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 25
      docs/en/release-info/migration-guides/abp-10-7.md
  2. 8
      framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/DefaultDynamicBackgroundJobManager.cs
  3. 10
      framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/DynamicBackgroundJobArgs.cs
  4. 16
      framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/IncomingEventInfo.cs
  5. 16
      framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/OutgoingEventInfo.cs
  6. 23
      framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/DynamicEventData.cs
  7. 2
      framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/EventBusConsts.cs
  8. 26
      framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/EventBusTenantIdHelper.cs
  9. 40
      framework/src/Volo.Abp.EventBus.Azure/Volo/Abp/EventBus/Azure/AzureDistributedEventBus.cs
  10. 26
      framework/src/Volo.Abp.EventBus.Kafka/Volo/Abp/EventBus/Kafka/KafkaDistributedEventBus.cs
  11. 13
      framework/src/Volo.Abp.EventBus.Kafka/Volo/Abp/EventBus/Kafka/MessageExtensions.cs
  12. 54
      framework/src/Volo.Abp.EventBus.RabbitMQ/Volo/Abp/EventBus/RabbitMq/RabbitMqDistributedEventBus.cs
  13. 31
      framework/src/Volo.Abp.EventBus.Rebus/Volo/Abp/EventBus/Rebus/RebusDistributedEventBus.cs
  14. 45
      framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Distributed/DistributedEventBusBase.cs
  15. 14
      framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus.cs
  16. 72
      framework/test/Volo.Abp.BackgroundJobs.Tests/Volo/Abp/BackgroundJobs/DynamicBackgroundJob_MultiTenancy_Tests.cs
  17. 18
      framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/EventBusOutboxTestModule.cs
  18. 41
      framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/FakeEventOutbox.cs
  19. 113
      framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_MultiTenancy_Test.cs
  20. 70
      framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_Outbox_MultiTenancy_Test.cs

25
docs/en/release-info/migration-guides/abp-10-7.md

@ -203,6 +203,31 @@ Upgrade the packages. There is no configuration change.
Until you can upgrade, give every authorization server its own client signing key, so an assertion cannot be replayed across them.
### Tenant of Dynamic Background Jobs and Events
**Who is affected**
- Applications that enqueue jobs through `IDynamicBackgroundJobManager` with a runtime registered handler.
- Applications that publish string named dynamic events and handle them after an outbox or a message broker.
- Applications that derive from `DefaultDynamicBackgroundJobManager`, or that override `DistributedEventBusBase.AddToInboxAsync` or `AzureDistributedEventBus.PublishAsync(string, object)`.
**What changed**
- A dynamic handler job now runs under the tenant that enqueued it. `DynamicBackgroundJobArgs` implements `IMultiTenant` and `DefaultDynamicBackgroundJobManager` fills it from `ICurrentTenant`, so the existing `BackgroundJobExecuter` restores the tenant before the handler runs. Previously the transport args carried no tenant and the job ran under the host, because the worker thread has none.
- A string named dynamic event now runs under the tenant that published it. Its payload is arbitrary user data with no place for a tenant, so the tenant travels on the transport as the `X-Tenant-Id` header, next to the correlation id, and the message body is unchanged. Typed events keep carrying their tenant in the event data itself and are not touched: no header is written for them and their handlers behave exactly as before.
- `DefaultDynamicBackgroundJobManager` takes a new `ICurrentTenant` dependency, and `AddToInboxAsync` and the Azure `PublishAsync(string, object)` take a new optional tenant parameter. A derived class does not compile until its constructor or its override is updated.
- A tenant header that is present but is not a GUID fails the message instead of handling it under the host.
- Dapr is unchanged, because it does not support dynamic event subscriptions.
**What to do**
- Add the new parameters to your derived constructors and overrides.
- Review the dynamic handlers you register at runtime. A handler that reads host wide data while the job is enqueued from a tenant request now sees that tenant's data. Wrap such a handler in `using (CurrentTenant.Change(null))` if it has to run under the host, or enqueue the job inside the same scope.
- Drain or re-enqueue the jobs and the events that are still waiting from before the upgrade. They carry no tenant and keep running under the host.
- Upgrade the consumers before the producers in a tiered or microservice solution. A message published by an upgraded producer loses its tenant on a consumer that is not upgraded yet, the same way it did before the upgrade.
> See [#26148](https://github.com/abpframework/abp/pull/26148) for details.
### Dependency Updates
**Who is affected**

8
framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/DefaultDynamicBackgroundJobManager.cs

@ -9,6 +9,7 @@ using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Json;
using Volo.Abp.MultiTenancy;
namespace Volo.Abp.BackgroundJobs;
@ -20,18 +21,21 @@ public class DefaultDynamicBackgroundJobManager : IDynamicBackgroundJobManager,
protected IDynamicBackgroundJobHandlerRegistry HandlerRegistry { get; }
protected AbpBackgroundJobOptions BackgroundJobOptions { get; }
protected IJsonSerializer JsonSerializer { get; }
protected ICurrentTenant CurrentTenant { get; }
public ILogger<DefaultDynamicBackgroundJobManager> Logger { get; set; }
public DefaultDynamicBackgroundJobManager(
IBackgroundJobManager backgroundJobManager,
IDynamicBackgroundJobHandlerRegistry handlerRegistry,
IOptions<AbpBackgroundJobOptions> backgroundJobOptions,
IJsonSerializer jsonSerializer)
IJsonSerializer jsonSerializer,
ICurrentTenant currentTenant)
{
BackgroundJobManager = backgroundJobManager;
HandlerRegistry = handlerRegistry;
BackgroundJobOptions = backgroundJobOptions.Value;
JsonSerializer = jsonSerializer;
CurrentTenant = currentTenant;
Logger = NullLogger<DefaultDynamicBackgroundJobManager>.Instance;
}
@ -99,7 +103,7 @@ public class DefaultDynamicBackgroundJobManager : IDynamicBackgroundJobManager,
TimeSpan? delay)
{
var jsonData = JsonSerializer.Serialize(args);
var dynamicArgs = new DynamicBackgroundJobArgs(jobName, jsonData);
var dynamicArgs = new DynamicBackgroundJobArgs(jobName, jsonData, CurrentTenant.Id);
return BackgroundJobManager.EnqueueAsync(dynamicArgs, priority, delay);
}

10
framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/DynamicBackgroundJobArgs.cs

@ -1,7 +1,10 @@
using System;
using Volo.Abp.MultiTenancy;
namespace Volo.Abp.BackgroundJobs;
[BackgroundJobName(JobNameConstant)]
public class DynamicBackgroundJobArgs
public class DynamicBackgroundJobArgs : IMultiTenant
{
public const string JobNameConstant = "Abp.DynamicJob";
@ -9,6 +12,8 @@ public class DynamicBackgroundJobArgs
public string JsonData { get; private set; }
public Guid? TenantId { get; private set; }
// For serializers that require a parameterless constructor (e.g. System.Text.Json)
private DynamicBackgroundJobArgs()
{
@ -16,9 +21,10 @@ public class DynamicBackgroundJobArgs
JsonData = string.Empty;
}
public DynamicBackgroundJobArgs(string jobName, string jsonData)
public DynamicBackgroundJobArgs(string jobName, string jsonData, Guid? tenantId = null)
{
JobName = Check.NotNullOrWhiteSpace(jobName, nameof(jobName));
JsonData = Check.NotNull(jsonData, nameof(jsonData));
TenantId = tenantId;
}
}

16
framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/IncomingEventInfo.cs

@ -67,4 +67,20 @@ public class IncomingEventInfo : IIncomingEventInfo
{
return ExtraProperties.GetOrDefault(EventBusConsts.CorrelationIdHeaderName)?.ToString();
}
public void SetTenantId(Guid? tenantId)
{
if (tenantId == null)
{
ExtraProperties.Remove(EventBusConsts.TenantIdHeaderName);
return;
}
ExtraProperties[EventBusConsts.TenantIdHeaderName] = tenantId.Value.ToString();
}
public Guid? GetTenantId()
{
return EventBusTenantIdHelper.Parse(ExtraProperties.GetOrDefault(EventBusConsts.TenantIdHeaderName)?.ToString());
}
}

16
framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/OutgoingEventInfo.cs

@ -47,4 +47,20 @@ public class OutgoingEventInfo : IOutgoingEventInfo
{
return ExtraProperties.GetOrDefault(EventBusConsts.CorrelationIdHeaderName)?.ToString();
}
public void SetTenantId(Guid? tenantId)
{
if (tenantId == null)
{
ExtraProperties.Remove(EventBusConsts.TenantIdHeaderName);
return;
}
ExtraProperties[EventBusConsts.TenantIdHeaderName] = tenantId.Value.ToString();
}
public Guid? GetTenantId()
{
return EventBusTenantIdHelper.Parse(ExtraProperties.GetOrDefault(EventBusConsts.TenantIdHeaderName)?.ToString());
}
}

23
framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/DynamicEventData.cs

@ -1,17 +1,38 @@
using System;
namespace Volo.Abp.EventBus;
/// <summary>
/// Wraps arbitrary event data with a string-based event name for dynamic (type-less) event handling.
/// </summary>
public class DynamicEventData
public class DynamicEventData : IEventDataMayHaveTenantId
{
public string EventName { get; }
public object Data { get; }
private Guid? _tenantId;
private bool _hasTenantId;
public DynamicEventData(string eventName, object data)
{
EventName = Check.NotNullOrWhiteSpace(eventName, nameof(eventName));
Data = Check.NotNull(data, nameof(data));
}
/// <summary>
/// <see cref="Data"/> is user data, so the tenant id can only come from the transport.
/// </summary>
public DynamicEventData SetTenantId(Guid? tenantId)
{
_tenantId = tenantId;
_hasTenantId = true;
return this;
}
public bool IsMultiTenant(out Guid? tenantId)
{
tenantId = _tenantId;
return _hasTenantId;
}
}

2
framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/EventBusConsts.cs

@ -3,4 +3,6 @@ namespace Volo.Abp.EventBus;
public static class EventBusConsts
{
public const string CorrelationIdHeaderName = "X-Correlation-Id";
public const string TenantIdHeaderName = "X-Tenant-Id";
}

26
framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/EventBusTenantIdHelper.cs

@ -0,0 +1,26 @@
using System;
namespace Volo.Abp.EventBus;
public static class EventBusTenantIdHelper
{
/// <summary>
/// Throws for an unparsable value so the provider can fail the message
/// instead of silently handling it in the host context.
/// </summary>
public static Guid? Parse(string? value)
{
if (value.IsNullOrWhiteSpace())
{
return null;
}
if (!Guid.TryParse(value, out var tenantId))
{
throw new AbpException(
$"'{EventBusConsts.TenantIdHeaderName}' header of the distributed event was not a valid GUID: {value}");
}
return tenantId;
}
}

40
framework/src/Volo.Abp.EventBus.Azure/Volo/Abp/EventBus/Azure/AzureDistributedEventBus.cs

@ -86,6 +86,7 @@ public class AzureDistributedEventBus : DistributedEventBusBase, ISingletonDepen
var eventType = EventTypes.GetOrDefault(eventName);
object eventData;
Guid? tenantId = null;
if (eventType != null)
{
@ -94,7 +95,8 @@ public class AzureDistributedEventBus : DistributedEventBusBase, ISingletonDepen
else if (DynamicHandlerFactories.ContainsKey(eventName))
{
var rawBytes = message.Body.ToArray();
eventData = new DynamicEventData(eventName, Serializer.Deserialize<object>(rawBytes));
tenantId = GetTenantIdFromMessage(message);
eventData = CreateDynamicEventData(eventName, Serializer.Deserialize<object>(rawBytes), tenantId);
eventType = typeof(DynamicEventData);
}
else
@ -102,7 +104,7 @@ public class AzureDistributedEventBus : DistributedEventBusBase, ISingletonDepen
return;
}
if (await AddToInboxAsync(message.MessageId, eventName, eventType, eventData, message.CorrelationId))
if (await AddToInboxAsync(message.MessageId, eventName, eventType, eventData, message.CorrelationId, tenantId))
{
return;
}
@ -199,7 +201,7 @@ public class AzureDistributedEventBus : DistributedEventBusBase, ISingletonDepen
public override Task PublishAsync(string eventName, object eventData, bool onUnitOfWorkComplete = true)
{
var eventType = EventTypes.GetOrDefault(eventName);
var dynamicEventData = eventData as DynamicEventData ?? new DynamicEventData(eventName, eventData);
var dynamicEventData = CreateDynamicEventDataForPublishing(eventName, eventData);
if (eventType != null)
{
@ -212,7 +214,7 @@ public class AzureDistributedEventBus : DistributedEventBusBase, ISingletonDepen
protected async override Task PublishToEventBusAsync(Type eventType, object eventData)
{
var (eventName, resolvedData) = ResolveEventForPublishing(eventType, eventData);
await PublishAsync(eventName, resolvedData);
await PublishAsync(eventName, resolvedData, GetTenantIdToPropagate(eventType, eventData));
}
protected override void AddToUnitOfWork(IUnitOfWork unitOfWork, UnitOfWorkEventRecord eventRecord)
@ -222,7 +224,7 @@ public class AzureDistributedEventBus : DistributedEventBusBase, ISingletonDepen
public async override Task PublishFromOutboxAsync(OutgoingEventInfo outgoingEvent, OutboxConfig outboxConfig)
{
await PublishAsync(outgoingEvent.EventName, outgoingEvent.EventData, outgoingEvent.GetCorrelationId(), outgoingEvent.Id);
await PublishAsync(outgoingEvent.EventName, outgoingEvent.EventData, outgoingEvent.GetCorrelationId(), outgoingEvent.Id, outgoingEvent.GetTenantId());
using (CorrelationIdProvider.Change(outgoingEvent.GetCorrelationId()))
{
@ -255,6 +257,7 @@ public class AzureDistributedEventBus : DistributedEventBusBase, ISingletonDepen
}
message.CorrelationId = outgoingEvent.GetCorrelationId();
SetTenantIdProperty(message, outgoingEvent.GetTenantId());
if (!messageBatch.TryAddMessage(message))
{
@ -290,7 +293,7 @@ public class AzureDistributedEventBus : DistributedEventBusBase, ISingletonDepen
}
else if (DynamicHandlerFactories.ContainsKey(incomingEvent.EventName))
{
eventData = new DynamicEventData(incomingEvent.EventName, Serializer.Deserialize<object>(incomingEvent.EventData));
eventData = CreateDynamicEventData(incomingEvent, Serializer.Deserialize<object>(incomingEvent.EventData));
eventType = typeof(DynamicEventData);
}
else
@ -313,18 +316,36 @@ public class AzureDistributedEventBus : DistributedEventBusBase, ISingletonDepen
return Serializer.Serialize(eventData);
}
protected virtual Task PublishAsync(string eventName, object eventData)
protected virtual Task PublishAsync(string eventName, object eventData, Guid? tenantId = null)
{
var body = Serializer.Serialize(eventData);
return PublishAsync(eventName, body, CorrelationIdProvider.Get(), null);
return PublishAsync(eventName, body, CorrelationIdProvider.Get(), null, tenantId);
}
protected virtual void SetTenantIdProperty(ServiceBusMessage message, Guid? tenantId)
{
if (tenantId == null)
{
return;
}
message.ApplicationProperties[EventBusConsts.TenantIdHeaderName] = tenantId.Value.ToString();
}
protected virtual Guid? GetTenantIdFromMessage(ServiceBusReceivedMessage message)
{
return message.ApplicationProperties.TryGetValue(EventBusConsts.TenantIdHeaderName, out var value)
? EventBusTenantIdHelper.Parse(value?.ToString())
: null;
}
protected virtual async Task PublishAsync(
string eventName,
byte[] body,
string? correlationId,
Guid? eventId)
Guid? eventId,
Guid? tenantId = null)
{
var message = new ServiceBusMessage(body)
{
@ -337,6 +358,7 @@ public class AzureDistributedEventBus : DistributedEventBusBase, ISingletonDepen
}
message.CorrelationId = correlationId;
SetTenantIdProperty(message, tenantId);
var publisher = await PublisherPool.GetAsync(
Options.TopicName,

26
framework/src/Volo.Abp.EventBus.Kafka/Volo/Abp/EventBus/Kafka/KafkaDistributedEventBus.cs

@ -86,6 +86,7 @@ public class KafkaDistributedEventBus : DistributedEventBusBase, ISingletonDepen
var messageId = message.GetMessageId();
var correlationId = message.GetCorrelationId();
object eventData;
Guid? tenantId = null;
if (eventType != null)
{
@ -93,7 +94,8 @@ public class KafkaDistributedEventBus : DistributedEventBusBase, ISingletonDepen
}
else if (DynamicHandlerFactories.ContainsKey(eventName))
{
eventData = new DynamicEventData(eventName, Serializer.Deserialize<object>(message.Value));
tenantId = message.GetTenantId();
eventData = CreateDynamicEventData(eventName, Serializer.Deserialize<object>(message.Value), tenantId);
eventType = typeof(DynamicEventData);
}
else
@ -101,7 +103,7 @@ public class KafkaDistributedEventBus : DistributedEventBusBase, ISingletonDepen
return;
}
if (await AddToInboxAsync(messageId, eventName, eventType, eventData, correlationId))
if (await AddToInboxAsync(messageId, eventName, eventType, eventData, correlationId, tenantId))
{
return;
}
@ -199,7 +201,7 @@ public class KafkaDistributedEventBus : DistributedEventBusBase, ISingletonDepen
public override Task PublishAsync(string eventName, object eventData, bool onUnitOfWorkComplete = true)
{
var eventType = EventTypes.GetOrDefault(eventName);
var dynamicEventData = eventData as DynamicEventData ?? new DynamicEventData(eventName, eventData);
var dynamicEventData = CreateDynamicEventDataForPublishing(eventName, eventData);
if (eventType != null)
{
@ -221,6 +223,8 @@ public class KafkaDistributedEventBus : DistributedEventBusBase, ISingletonDepen
headers.Add(EventBusConsts.CorrelationIdHeaderName, System.Text.Encoding.UTF8.GetBytes(CorrelationIdProvider.Get()!));
}
AddTenantIdHeader(headers, GetTenantIdToPropagate(eventType, eventData));
await PublishAsync(
AbpKafkaEventBusOptions.TopicName,
eventType,
@ -247,6 +251,8 @@ public class KafkaDistributedEventBus : DistributedEventBusBase, ISingletonDepen
headers.Add(EventBusConsts.CorrelationIdHeaderName, System.Text.Encoding.UTF8.GetBytes(outgoingEvent.GetCorrelationId()!));
}
AddTenantIdHeader(headers, outgoingEvent.GetTenantId());
var result = await PublishAsync(
AbpKafkaEventBusOptions.TopicName,
outgoingEvent.EventName,
@ -288,6 +294,8 @@ public class KafkaDistributedEventBus : DistributedEventBusBase, ISingletonDepen
headers.Add(EventBusConsts.CorrelationIdHeaderName, System.Text.Encoding.UTF8.GetBytes(outgoingEvent.GetCorrelationId()!));
}
AddTenantIdHeader(headers, outgoingEvent.GetTenantId());
var result = await producer.ProduceAsync(
AbpKafkaEventBusOptions.TopicName,
new Message<string, byte[]>
@ -327,7 +335,7 @@ public class KafkaDistributedEventBus : DistributedEventBusBase, ISingletonDepen
}
else if (DynamicHandlerFactories.ContainsKey(incomingEvent.EventName))
{
eventData = new DynamicEventData(incomingEvent.EventName, Serializer.Deserialize<object>(incomingEvent.EventData));
eventData = CreateDynamicEventData(incomingEvent, Serializer.Deserialize<object>(incomingEvent.EventData));
eventType = typeof(DynamicEventData);
}
else
@ -350,6 +358,16 @@ public class KafkaDistributedEventBus : DistributedEventBusBase, ISingletonDepen
return Serializer.Serialize(eventData);
}
protected virtual void AddTenantIdHeader(Headers headers, Guid? tenantId)
{
if (tenantId == null)
{
return;
}
headers.Add(EventBusConsts.TenantIdHeaderName, System.Text.Encoding.UTF8.GetBytes(tenantId.Value.ToString()));
}
private async Task PublishAsync(string topicName, Type eventType, object eventData, Headers headers)
{
var (eventName, resolvedData) = ResolveEventForPublishing(eventType, eventData);

13
framework/src/Volo.Abp.EventBus.Kafka/Volo/Abp/EventBus/Kafka/MessageExtensions.cs

@ -1,4 +1,5 @@
using Confluent.Kafka;
using System;
using Confluent.Kafka;
namespace Volo.Abp.EventBus.Kafka;
@ -27,4 +28,14 @@ public static class MessageExtensions
return correlationId;
}
public static Guid? GetTenantId<TKey, TValue>(this Message<TKey, TValue> message)
{
if (message.Headers.TryGetLastBytes(EventBusConsts.TenantIdHeaderName, out var tenantIdBytes))
{
return EventBusTenantIdHelper.Parse(System.Text.Encoding.UTF8.GetString(tenantIdBytes));
}
return null;
}
}

54
framework/src/Volo.Abp.EventBus.RabbitMQ/Volo/Abp/EventBus/RabbitMq/RabbitMqDistributedEventBus.cs

@ -104,6 +104,7 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
var eventName = ea.RoutingKey;
var eventType = EventTypes.GetOrDefault(eventName);
object eventData;
Guid? tenantId = null;
if (eventType != null)
{
@ -113,7 +114,8 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
{
var rawBytes = ea.Body.ToArray();
eventType = typeof(DynamicEventData);
eventData = new DynamicEventData(eventName, Serializer.Deserialize<object>(rawBytes));
tenantId = GetTenantIdFromHeaders(ea.BasicProperties.Headers);
eventData = CreateDynamicEventData(eventName, Serializer.Deserialize<object>(rawBytes), tenantId);
}
else
{
@ -121,7 +123,7 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
}
var correlationId = ea.BasicProperties.CorrelationId;
if (await AddToInboxAsync(ea.BasicProperties.MessageId, eventName, eventType, eventData, correlationId))
if (await AddToInboxAsync(ea.BasicProperties.MessageId, eventName, eventType, eventData, correlationId, tenantId))
{
return;
}
@ -229,7 +231,7 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
public override Task PublishAsync(string eventName, object eventData, bool onUnitOfWorkComplete = true)
{
var eventType = EventTypes.GetOrDefault(eventName);
var dynamicEventData = eventData as DynamicEventData ?? new DynamicEventData(eventName, eventData);
var dynamicEventData = CreateDynamicEventDataForPublishing(eventName, eventData);
if (eventType != null)
{
@ -241,7 +243,7 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
protected async override Task PublishToEventBusAsync(Type eventType, object eventData)
{
await PublishAsync(eventType, eventData, correlationId: CorrelationIdProvider.Get());
await PublishAsync(eventType, eventData, correlationId: CorrelationIdProvider.Get(), tenantId: GetTenantIdToPropagate(eventType, eventData));
}
protected override void AddToUnitOfWork(IUnitOfWork unitOfWork, UnitOfWorkEventRecord eventRecord)
@ -253,7 +255,7 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
OutgoingEventInfo outgoingEvent,
OutboxConfig outboxConfig)
{
await PublishAsync(outgoingEvent.EventName, outgoingEvent.EventData, eventId: outgoingEvent.Id, correlationId: outgoingEvent.GetCorrelationId());
await PublishAsync(outgoingEvent.EventName, outgoingEvent.EventData, eventId: outgoingEvent.Id, correlationId: outgoingEvent.GetCorrelationId(), tenantId: outgoingEvent.GetTenantId());
using (CorrelationIdProvider.Change(outgoingEvent.GetCorrelationId()))
{
@ -282,7 +284,8 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
outgoingEvent.EventName,
outgoingEvent.EventData,
eventId: outgoingEvent.Id,
correlationId: outgoingEvent.GetCorrelationId());
correlationId: outgoingEvent.GetCorrelationId(),
tenantId: outgoingEvent.GetTenantId());
using (CorrelationIdProvider.Change(outgoingEvent.GetCorrelationId()))
{
@ -310,7 +313,7 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
}
else if (DynamicHandlerFactories.ContainsKey(incomingEvent.EventName))
{
eventData = new DynamicEventData(incomingEvent.EventName, Serializer.Deserialize<object>(incomingEvent.EventData));
eventData = CreateDynamicEventData(incomingEvent, Serializer.Deserialize<object>(incomingEvent.EventData));
eventType = typeof(DynamicEventData);
}
else
@ -338,12 +341,13 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
object eventData,
Dictionary<string, object>? headersArguments = null,
Guid? eventId = null,
string? correlationId = null)
string? correlationId = null,
Guid? tenantId = null)
{
var (eventName, resolvedData) = ResolveEventForPublishing(eventType, eventData);
var body = Serializer.Serialize(resolvedData);
return PublishAsync(eventName, body, headersArguments, eventId, correlationId);
return PublishAsync(eventName, body, headersArguments, eventId, correlationId, tenantId);
}
protected virtual async Task PublishAsync(
@ -351,11 +355,12 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
byte[] body,
Dictionary<string, object>? headersArguments = null,
Guid? eventId = null,
string? correlationId = null)
string? correlationId = null,
Guid? tenantId = null)
{
using (var channel = await (await ConnectionPool.GetAsync(AbpRabbitMqEventBusOptions.ConnectionName)).CreateChannelAsync())
{
await PublishAsync(channel, eventName, body, headersArguments, eventId, correlationId);
await PublishAsync(channel, eventName, body, headersArguments, eventId, correlationId, tenantId);
}
}
@ -365,7 +370,8 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
byte[] body,
Dictionary<string, object>? headersArguments = null,
Guid? eventId = null,
string? correlationId = null)
string? correlationId = null,
Guid? tenantId = null)
{
await EnsureExchangeExistsAsync(channel);
@ -385,6 +391,7 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
}
SetEventMessageHeaders(properties, headersArguments);
SetTenantIdHeader(properties, tenantId);
await channel.BasicPublishAsync(
exchange: AbpRabbitMqEventBusOptions.ExchangeName,
@ -420,6 +427,29 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis
_exchangeCreated = true;
}
protected virtual void SetTenantIdHeader(IBasicProperties properties, Guid? tenantId)
{
if (tenantId == null)
{
return;
}
properties.Headers ??= new Dictionary<string, object?>();
properties.Headers[EventBusConsts.TenantIdHeaderName] = tenantId.Value.ToString();
}
protected virtual Guid? GetTenantIdFromHeaders(IDictionary<string, object?>? headers)
{
if (headers == null || !headers.TryGetValue(EventBusConsts.TenantIdHeaderName, out var value))
{
return null;
}
return EventBusTenantIdHelper.Parse(value is byte[] bytes
? System.Text.Encoding.UTF8.GetString(bytes)
: value?.ToString());
}
protected virtual void SetEventMessageHeaders(IBasicProperties properties, Dictionary<string, object>? headersArguments)
{
if (headersArguments == null)

31
framework/src/Volo.Abp.EventBus.Rebus/Volo/Abp/EventBus/Rebus/RebusDistributedEventBus.cs

@ -85,8 +85,16 @@ public class RebusDistributedEventBus : DistributedEventBusBase, ISingletonDepen
eventName = EventNameAttribute.GetNameOrDefault(eventType);
}
var correlationId = MessageContext.Current.Headers.GetOrDefault(EventBusConsts.CorrelationIdHeaderName);
Guid? tenantId = null;
if (await AddToInboxAsync(messageId, eventName, eventType, eventData, correlationId))
if (eventData is DynamicEventData receivedDynamicEventData)
{
tenantId = EventBusTenantIdHelper.Parse(
MessageContext.Current.Headers.GetOrDefault(EventBusConsts.TenantIdHeaderName));
eventData = CreateDynamicEventData(receivedDynamicEventData.EventName, receivedDynamicEventData.Data, tenantId);
}
if (await AddToInboxAsync(messageId, eventName, eventType, eventData, correlationId, tenantId))
{
return;
}
@ -194,7 +202,7 @@ public class RebusDistributedEventBus : DistributedEventBusBase, ISingletonDepen
public override Task PublishAsync(string eventName, object eventData, bool onUnitOfWorkComplete = true)
{
var eventType = EventTypes.GetOrDefault(eventName);
var dynamicEventData = eventData as DynamicEventData ?? new DynamicEventData(eventName, eventData);
var dynamicEventData = CreateDynamicEventDataForPublishing(eventName, eventData);
if (eventType != null)
{
@ -211,6 +219,9 @@ public class RebusDistributedEventBus : DistributedEventBusBase, ISingletonDepen
{
headers.Add(EventBusConsts.CorrelationIdHeaderName, CorrelationIdProvider.Get()!);
}
AddTenantIdHeader(headers, GetTenantIdToPropagate(eventType, eventData));
await PublishAsync(eventType, eventData, headersArguments: headers);
}
@ -232,7 +243,7 @@ public class RebusDistributedEventBus : DistributedEventBusBase, ISingletonDepen
}
else if (DynamicHandlerFactories.ContainsKey(outgoingEvent.EventName))
{
eventData = new DynamicEventData(outgoingEvent.EventName, Serializer.Deserialize(outgoingEvent.EventData, typeof(object)));
eventData = CreateDynamicEventData(outgoingEvent, Serializer.Deserialize(outgoingEvent.EventData, typeof(object)));
eventType = typeof(DynamicEventData);
}
else
@ -246,6 +257,8 @@ public class RebusDistributedEventBus : DistributedEventBusBase, ISingletonDepen
headers.Add(EventBusConsts.CorrelationIdHeaderName, outgoingEvent.GetCorrelationId()!);
}
AddTenantIdHeader(headers, outgoingEvent.GetTenantId());
await PublishAsync(eventType, eventData, eventId: outgoingEvent.Id, headersArguments: headers);
using (CorrelationIdProvider.Change(outgoingEvent.GetCorrelationId()))
@ -296,7 +309,7 @@ public class RebusDistributedEventBus : DistributedEventBusBase, ISingletonDepen
}
else if (DynamicHandlerFactories.ContainsKey(incomingEvent.EventName))
{
eventData = new DynamicEventData(incomingEvent.EventName, Serializer.Deserialize(incomingEvent.EventData, typeof(object)));
eventData = CreateDynamicEventData(incomingEvent, Serializer.Deserialize(incomingEvent.EventData, typeof(object)));
eventType = typeof(DynamicEventData);
}
else
@ -319,6 +332,16 @@ public class RebusDistributedEventBus : DistributedEventBusBase, ISingletonDepen
return Serializer.Serialize(eventData);
}
protected virtual void AddTenantIdHeader(Dictionary<string, string> headers, Guid? tenantId)
{
if (tenantId == null)
{
return;
}
headers[EventBusConsts.TenantIdHeaderName] = tenantId.Value.ToString();
}
protected virtual async Task PublishAsync(
Type eventType,
object eventData,

45
framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Distributed/DistributedEventBusBase.cs

@ -113,7 +113,7 @@ public abstract class DistributedEventBusBase : EventBusBase, IDistributedEventB
bool useOutbox = true)
{
var eventType = GetEventTypeByEventName(eventName);
var dynamicEventData = eventData as DynamicEventData ?? new DynamicEventData(eventName, eventData);
var dynamicEventData = CreateDynamicEventDataForPublishing(eventName, eventData);
if (eventType != null)
{
@ -146,6 +146,7 @@ public abstract class DistributedEventBusBase : EventBusBase, IDistributedEventB
}
var addedToOutbox = false;
var tenantId = GetTenantIdToPropagate(eventType, eventData);
foreach (var outboxConfig in AbpDistributedEventBusOptions.Outboxes.Values.OrderBy(x => x.Selector is null))
{
@ -169,6 +170,8 @@ public abstract class DistributedEventBusBase : EventBusBase, IDistributedEventB
outgoingEventInfo.SetCorrelationId(correlationId);
}
outgoingEventInfo.SetTenantId(tenantId);
await eventOutbox.EnqueueAsync(outgoingEventInfo);
addedToOutbox = true;
}
@ -187,7 +190,8 @@ public abstract class DistributedEventBusBase : EventBusBase, IDistributedEventB
string eventName,
Type eventType,
object eventData,
string? correlationId)
string? correlationId,
Guid? tenantId = null)
{
if (AbpDistributedEventBusOptions.Inboxes.Count <= 0)
{
@ -224,6 +228,7 @@ public abstract class DistributedEventBusBase : EventBusBase, IDistributedEventB
Clock.Now
);
incomingEventInfo.SetCorrelationId(correlationId!);
incomingEventInfo.SetTenantId(tenantId);
await eventInbox.EnqueueAsync(incomingEventInfo);
addToInbox = true;
}
@ -293,6 +298,42 @@ public abstract class DistributedEventBusBase : EventBusBase, IDistributedEventB
return EventNameAttribute.GetNameOrDefault(eventType);
}
protected virtual DynamicEventData CreateDynamicEventDataForPublishing(string eventName, object eventData)
{
var dynamicEventData = eventData as DynamicEventData ?? new DynamicEventData(eventName, eventData);
return dynamicEventData.SetTenantId(CurrentTenant.Id);
}
protected virtual Guid? GetTenantIdToPropagate(Type eventType, object eventData)
{
if (eventType != typeof(DynamicEventData))
{
return null;
}
return eventData is DynamicEventData dynamicEventData && dynamicEventData.IsMultiTenant(out var tenantId)
? tenantId
: CurrentTenant.Id;
}
protected virtual DynamicEventData CreateDynamicEventData(string eventName, object data, Guid? tenantId)
{
var dynamicEventData = new DynamicEventData(eventName, data);
return tenantId == null
? dynamicEventData
: dynamicEventData.SetTenantId(tenantId);
}
protected virtual DynamicEventData CreateDynamicEventData(OutgoingEventInfo outgoingEvent, object data)
{
return CreateDynamicEventData(outgoingEvent.EventName, data, outgoingEvent.GetTenantId());
}
protected virtual DynamicEventData CreateDynamicEventData(IncomingEventInfo incomingEvent, object data)
{
return CreateDynamicEventData(incomingEvent.EventName, data, incomingEvent.GetTenantId());
}
protected virtual object GetEventData(object eventData)
{
if (eventData is DynamicEventData dynamicEventData)

14
framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus.cs

@ -173,7 +173,7 @@ public class LocalDistributedEventBus : DistributedEventBusBase, ISingletonDepen
public override Task PublishAsync(string eventName, object eventData, bool onUnitOfWorkComplete = true, bool useOutbox = true)
{
var eventType = EventTypes.GetOrDefault(eventName);
var dynamicEventData = eventData as DynamicEventData ?? new DynamicEventData(eventName, eventData);
var dynamicEventData = CreateDynamicEventDataForPublishing(eventName, eventData);
if (eventType != null)
{
@ -185,7 +185,7 @@ public class LocalDistributedEventBus : DistributedEventBusBase, ISingletonDepen
protected async override Task PublishToEventBusAsync(Type eventType, object eventData)
{
if (await AddToInboxAsync(Guid.NewGuid().ToString(), GetEventName(eventType, eventData), eventType, eventData, null))
if (await AddToInboxAsync(Guid.NewGuid().ToString(), GetEventName(eventType, eventData), eventType, eventData, null, GetTenantIdToPropagate(eventType, eventData)))
{
return;
}
@ -229,16 +229,14 @@ public class LocalDistributedEventBus : DistributedEventBusBase, ISingletonDepen
object eventData;
if (eventType == typeof(DynamicEventData))
{
eventData = new DynamicEventData(
outgoingEvent.EventName,
System.Text.Json.JsonSerializer.Deserialize<object>(outgoingEvent.EventData)!);
eventData = CreateDynamicEventData(outgoingEvent, System.Text.Json.JsonSerializer.Deserialize<object>(outgoingEvent.EventData)!);
}
else
{
eventData = System.Text.Json.JsonSerializer.Deserialize(outgoingEvent.EventData, eventType)!;
}
if (await AddToInboxAsync(Guid.NewGuid().ToString(), outgoingEvent.EventName, eventType, eventData, null))
if (await AddToInboxAsync(Guid.NewGuid().ToString(), outgoingEvent.EventName, eventType, eventData, null, outgoingEvent.GetTenantId()))
{
return;
}
@ -271,9 +269,7 @@ public class LocalDistributedEventBus : DistributedEventBusBase, ISingletonDepen
object eventData;
if (eventType == typeof(DynamicEventData))
{
eventData = new DynamicEventData(
incomingEvent.EventName,
System.Text.Json.JsonSerializer.Deserialize<object>(incomingEvent.EventData)!);
eventData = CreateDynamicEventData(incomingEvent, System.Text.Json.JsonSerializer.Deserialize<object>(incomingEvent.EventData)!);
}
else
{

72
framework/test/Volo.Abp.BackgroundJobs.Tests/Volo/Abp/BackgroundJobs/DynamicBackgroundJob_MultiTenancy_Tests.cs

@ -0,0 +1,72 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.MultiTenancy;
using Xunit;
namespace Volo.Abp.BackgroundJobs;
public class DynamicBackgroundJob_MultiTenancy_Tests : BackgroundJobsTestBase
{
private readonly IDynamicBackgroundJobManager _dynamicBackgroundJobManager;
private readonly IBackgroundJobStore _backgroundJobStore;
private readonly IBackgroundJobExecuter _backgroundJobExecuter;
private readonly IBackgroundJobSerializer _backgroundJobSerializer;
private readonly ICurrentTenant _currentTenant;
public DynamicBackgroundJob_MultiTenancy_Tests()
{
_dynamicBackgroundJobManager = GetRequiredService<IDynamicBackgroundJobManager>();
_backgroundJobStore = GetRequiredService<IBackgroundJobStore>();
_backgroundJobExecuter = GetRequiredService<IBackgroundJobExecuter>();
_backgroundJobSerializer = GetRequiredService<IBackgroundJobSerializer>();
_currentTenant = GetRequiredService<ICurrentTenant>();
}
[Fact]
public async Task Dynamic_Handler_Job_Should_Run_Under_The_Enqueue_Tenant()
{
var tenantId = Guid.NewGuid();
Guid? observedTenantId = null;
var executed = false;
_dynamicBackgroundJobManager.RegisterHandler("TenantProbeJob", (ctx, _) =>
{
executed = true;
observedTenantId = ctx.ServiceProvider.GetRequiredService<ICurrentTenant>().Id;
return Task.CompletedTask;
});
try
{
string jobIdAsString;
using (_currentTenant.Change(tenantId))
{
jobIdAsString = await _dynamicBackgroundJobManager.EnqueueAsync(
"TenantProbeJob",
new { CustomerId = "C-1" });
}
var jobInfo = await _backgroundJobStore.FindAsync(Guid.Parse(jobIdAsString));
jobInfo.ShouldNotBeNull();
var jobArgs = _backgroundJobSerializer.Deserialize(jobInfo.JobArgs, typeof(DynamicBackgroundJobArgs));
_currentTenant.Id.ShouldBeNull();
await _backgroundJobExecuter.ExecuteAsync(
new JobExecutionContext(
ServiceProvider,
typeof(DynamicBackgroundJobExecutorJob),
jobArgs));
executed.ShouldBeTrue();
observedTenantId.ShouldBe(tenantId);
}
finally
{
_dynamicBackgroundJobManager.UnregisterHandler("TenantProbeJob");
}
}
}

18
framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/EventBusOutboxTestModule.cs

@ -0,0 +1,18 @@
using Volo.Abp.Modularity;
namespace Volo.Abp.EventBus.Distributed;
[DependsOn(typeof(EventBusTestModule))]
public class EventBusOutboxTestModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure<AbpDistributedEventBusOptions>(options =>
{
options.Outboxes.Configure(config =>
{
config.ImplementationType = typeof(FakeEventOutbox);
});
});
}
}

41
framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/FakeEventOutbox.cs

@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;
namespace Volo.Abp.EventBus.Distributed;
public class FakeEventOutbox : IEventOutbox, ISingletonDependency
{
public List<OutgoingEventInfo> Events { get; } = new();
public Task EnqueueAsync(OutgoingEventInfo outgoingEvent)
{
Events.Add(outgoingEvent);
return Task.CompletedTask;
}
public Task<List<OutgoingEventInfo>> GetWaitingEventsAsync(
int maxCount,
Expression<Func<IOutgoingEventInfo, bool>>? filter = null,
CancellationToken cancellationToken = default)
{
return Task.FromResult(Events.Take(maxCount).ToList());
}
public Task DeleteAsync(Guid id)
{
Events.RemoveAll(x => x.Id == id);
return Task.CompletedTask;
}
public Task DeleteManyAsync(IEnumerable<Guid> ids)
{
var idList = ids.ToList();
Events.RemoveAll(x => idList.Contains(x.Id));
return Task.CompletedTask;
}
}

113
framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_MultiTenancy_Test.cs

@ -0,0 +1,113 @@
using System;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Shouldly;
using Volo.Abp.EventBus.Local;
using Volo.Abp.Guids;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Timing;
using Volo.Abp.Tracing;
using Volo.Abp.Uow;
using Xunit;
namespace Volo.Abp.EventBus.Distributed;
public class LocalDistributedEventBus_MultiTenancy_Test : LocalDistributedEventBusTestBase
{
private readonly ICurrentTenant _currentTenant;
public LocalDistributedEventBus_MultiTenancy_Test()
{
_currentTenant = GetRequiredService<ICurrentTenant>();
}
[Fact]
public void Should_Only_Propagate_The_Tenant_Of_Dynamic_Events()
{
var tenantId = Guid.NewGuid();
var eventBus = ActivatorUtilities.CreateInstance<TestableLocalDistributedEventBus>(ServiceProvider);
using (_currentTenant.Change(tenantId))
{
eventBus.GetTenantIdToPropagatePublic(typeof(DynamicEventData), new DynamicEventData("test", new { Value = 1 })).ShouldBe(tenantId);
eventBus.GetTenantIdToPropagatePublic(typeof(MySimpleEventData), new MySimpleEventData(1)).ShouldBeNull();
}
}
[Fact]
public async Task Should_Restore_The_Publish_Tenant_When_A_Dynamic_Event_Is_Sent_From_The_Outbox()
{
var tenantId = Guid.NewGuid();
var eventName = "TestEvent-" + Guid.NewGuid().ToString("N");
Guid? observedTenantId = null;
var handled = false;
using var subscription = DistributedEventBus.Subscribe(eventName,
new SingleInstanceHandlerFactory(new ActionEventHandler<DynamicEventData>(_ =>
{
handled = true;
observedTenantId = _currentTenant.Id;
return Task.CompletedTask;
})));
var outgoingEvent = new OutgoingEventInfo(
Guid.NewGuid(),
eventName,
JsonSerializer.SerializeToUtf8Bytes(new { Value = 1 }),
DateTime.Now);
using (_currentTenant.Change(tenantId))
{
outgoingEvent.SetTenantId(_currentTenant.Id);
}
_currentTenant.Id.ShouldBeNull();
await GetRequiredService<LocalDistributedEventBus>().PublishFromOutboxAsync(outgoingEvent, new OutboxConfig("Default"));
handled.ShouldBeTrue();
observedTenantId.ShouldBe(tenantId);
}
[Fact]
public void Should_Fail_When_The_Tenant_Id_Header_Is_Not_A_Guid()
{
EventBusTenantIdHelper.Parse(null).ShouldBeNull();
EventBusTenantIdHelper.Parse(" ").ShouldBeNull();
Should.Throw<AbpException>(() => EventBusTenantIdHelper.Parse("not-a-guid"));
}
public class TestableLocalDistributedEventBus : LocalDistributedEventBus
{
public TestableLocalDistributedEventBus(
IServiceScopeFactory serviceScopeFactory,
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
IOptions<AbpDistributedEventBusOptions> abpDistributedEventBusOptions,
IGuidGenerator guidGenerator,
IClock clock,
IEventHandlerInvoker eventHandlerInvoker,
ILocalEventBus localEventBus,
ICorrelationIdProvider correlationIdProvider)
: base(
serviceScopeFactory,
currentTenant,
unitOfWorkManager,
abpDistributedEventBusOptions,
guidGenerator,
clock,
eventHandlerInvoker,
localEventBus,
correlationIdProvider)
{
}
public Guid? GetTenantIdToPropagatePublic(Type eventType, object eventData)
{
return GetTenantIdToPropagate(eventType, eventData);
}
}
}

70
framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_Outbox_MultiTenancy_Test.cs

@ -0,0 +1,70 @@
using System;
using System.Threading.Tasks;
using Shouldly;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Testing;
using Volo.Abp.Uow;
using Xunit;
namespace Volo.Abp.EventBus.Distributed;
public class LocalDistributedEventBus_Outbox_MultiTenancy_Test : AbpIntegratedTest<EventBusOutboxTestModule>
{
private readonly IDistributedEventBus _distributedEventBus;
private readonly ICurrentTenant _currentTenant;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly FakeEventOutbox _outbox;
public LocalDistributedEventBus_Outbox_MultiTenancy_Test()
{
_distributedEventBus = GetRequiredService<LocalDistributedEventBus>();
_currentTenant = GetRequiredService<ICurrentTenant>();
_unitOfWorkManager = GetRequiredService<IUnitOfWorkManager>();
_outbox = GetRequiredService<FakeEventOutbox>();
}
protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options)
{
options.UseAutofac();
}
[Fact]
public async Task Should_Write_The_Publish_Tenant_To_The_Outbox_Record()
{
var tenantId = Guid.NewGuid();
var eventName = "TestEvent-" + Guid.NewGuid().ToString("N");
using (var uow = _unitOfWorkManager.Begin(requiresNew: true))
{
using (_currentTenant.Change(tenantId))
{
await _distributedEventBus.PublishAsync(eventName, new { Value = 1 });
}
_currentTenant.Id.ShouldBeNull();
await uow.CompleteAsync();
}
var outgoingEvent = _outbox.Events.ShouldHaveSingleItem();
outgoingEvent.EventName.ShouldBe(eventName);
outgoingEvent.GetTenantId().ShouldBe(tenantId);
}
[Fact]
public async Task Should_Not_Write_A_Tenant_To_The_Outbox_Record_Of_A_Typed_Event()
{
using (var uow = _unitOfWorkManager.Begin(requiresNew: true))
{
using (_currentTenant.Change(Guid.NewGuid()))
{
await _distributedEventBus.PublishAsync(new MySimpleEventData(1));
}
await uow.CompleteAsync();
}
var outgoingEvent = _outbox.Events.ShouldHaveSingleItem();
outgoingEvent.GetTenantId().ShouldBeNull();
}
}
Loading…
Cancel
Save