From d7b3991d800a93b10731e08e051e2950a5d727b9 Mon Sep 17 00:00:00 2001 From: maliming Date: Thu, 10 Sep 2026 13:42:49 +0800 Subject: [PATCH 1/3] Run dynamic background jobs under the enqueue tenant --- .../DefaultDynamicBackgroundJobManager.cs | 8 ++- .../DynamicBackgroundJobArgs.cs | 10 ++- ...DynamicBackgroundJob_MultiTenancy_Tests.cs | 72 +++++++++++++++++++ 3 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 framework/test/Volo.Abp.BackgroundJobs.Tests/Volo/Abp/BackgroundJobs/DynamicBackgroundJob_MultiTenancy_Tests.cs diff --git a/framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/DefaultDynamicBackgroundJobManager.cs b/framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/DefaultDynamicBackgroundJobManager.cs index 7028e0f858..d90541d726 100644 --- a/framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/DefaultDynamicBackgroundJobManager.cs +++ b/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 Logger { get; set; } public DefaultDynamicBackgroundJobManager( IBackgroundJobManager backgroundJobManager, IDynamicBackgroundJobHandlerRegistry handlerRegistry, IOptions backgroundJobOptions, - IJsonSerializer jsonSerializer) + IJsonSerializer jsonSerializer, + ICurrentTenant currentTenant) { BackgroundJobManager = backgroundJobManager; HandlerRegistry = handlerRegistry; BackgroundJobOptions = backgroundJobOptions.Value; JsonSerializer = jsonSerializer; + CurrentTenant = currentTenant; Logger = NullLogger.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); } diff --git a/framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/DynamicBackgroundJobArgs.cs b/framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/DynamicBackgroundJobArgs.cs index 45066b7586..a9c945c5e1 100644 --- a/framework/src/Volo.Abp.BackgroundJobs.Abstractions/Volo/Abp/BackgroundJobs/DynamicBackgroundJobArgs.cs +++ b/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; } } diff --git a/framework/test/Volo.Abp.BackgroundJobs.Tests/Volo/Abp/BackgroundJobs/DynamicBackgroundJob_MultiTenancy_Tests.cs b/framework/test/Volo.Abp.BackgroundJobs.Tests/Volo/Abp/BackgroundJobs/DynamicBackgroundJob_MultiTenancy_Tests.cs new file mode 100644 index 0000000000..b1d5c8355e --- /dev/null +++ b/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(); + _backgroundJobStore = GetRequiredService(); + _backgroundJobExecuter = GetRequiredService(); + _backgroundJobSerializer = GetRequiredService(); + _currentTenant = GetRequiredService(); + } + + [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().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"); + } + } +} From 0043c9f162b174e4d7f5daaa9e8d4b8484eb5527 Mon Sep 17 00:00:00 2001 From: maliming Date: Thu, 10 Sep 2026 17:01:14 +0800 Subject: [PATCH 2/3] Carry the tenant of dynamic distributed events on the transport --- .../EventBus/Distributed/IncomingEventInfo.cs | 16 +++ .../EventBus/Distributed/OutgoingEventInfo.cs | 16 +++ .../Volo/Abp/EventBus/DynamicEventData.cs | 23 +++- .../Volo/Abp/EventBus/EventBusConsts.cs | 2 + .../Abp/EventBus/EventBusTenantIdHelper.cs | 26 ++++ .../Azure/AzureDistributedEventBus.cs | 40 +++++-- .../Kafka/KafkaDistributedEventBus.cs | 26 +++- .../Abp/EventBus/Kafka/MessageExtensions.cs | 13 +- .../RabbitMq/RabbitMqDistributedEventBus.cs | 54 +++++++-- .../Rebus/RebusDistributedEventBus.cs | 31 ++++- .../Distributed/DistributedEventBusBase.cs | 45 ++++++- .../Distributed/LocalDistributedEventBus.cs | 14 +-- .../Distributed/EventBusOutboxTestModule.cs | 18 +++ .../EventBus/Distributed/FakeEventOutbox.cs | 41 +++++++ ...alDistributedEventBus_MultiTenancy_Test.cs | 113 ++++++++++++++++++ ...ibutedEventBus_Outbox_MultiTenancy_Test.cs | 70 +++++++++++ 16 files changed, 506 insertions(+), 42 deletions(-) create mode 100644 framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/EventBusTenantIdHelper.cs create mode 100644 framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/EventBusOutboxTestModule.cs create mode 100644 framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/FakeEventOutbox.cs create mode 100644 framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_MultiTenancy_Test.cs create mode 100644 framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_Outbox_MultiTenancy_Test.cs diff --git a/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/IncomingEventInfo.cs b/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/IncomingEventInfo.cs index 23e59ad61a..46b836b37c 100644 --- a/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/IncomingEventInfo.cs +++ b/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()); + } } diff --git a/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/OutgoingEventInfo.cs b/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/OutgoingEventInfo.cs index 74b5bca7d4..1259f2e435 100644 --- a/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/Distributed/OutgoingEventInfo.cs +++ b/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()); + } } diff --git a/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/DynamicEventData.cs b/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/DynamicEventData.cs index 1af2f600a3..fae485faab 100644 --- a/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/DynamicEventData.cs +++ b/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/DynamicEventData.cs @@ -1,17 +1,38 @@ +using System; + namespace Volo.Abp.EventBus; /// /// Wraps arbitrary event data with a string-based event name for dynamic (type-less) event handling. /// -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)); } + + /// + /// is user data, so the tenant id can only come from the transport. + /// + public DynamicEventData SetTenantId(Guid? tenantId) + { + _tenantId = tenantId; + _hasTenantId = true; + return this; + } + + public bool IsMultiTenant(out Guid? tenantId) + { + tenantId = _tenantId; + return _hasTenantId; + } } diff --git a/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/EventBusConsts.cs b/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/EventBusConsts.cs index f1fa920670..a9436272cd 100644 --- a/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/EventBusConsts.cs +++ b/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"; } diff --git a/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/EventBusTenantIdHelper.cs b/framework/src/Volo.Abp.EventBus.Abstractions/Volo/Abp/EventBus/EventBusTenantIdHelper.cs new file mode 100644 index 0000000000..ff8a16f259 --- /dev/null +++ b/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 +{ + /// + /// Throws for an unparsable value so the provider can fail the message + /// instead of silently handling it in the host context. + /// + 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; + } +} diff --git a/framework/src/Volo.Abp.EventBus.Azure/Volo/Abp/EventBus/Azure/AzureDistributedEventBus.cs b/framework/src/Volo.Abp.EventBus.Azure/Volo/Abp/EventBus/Azure/AzureDistributedEventBus.cs index 296f353681..922ab95412 100644 --- a/framework/src/Volo.Abp.EventBus.Azure/Volo/Abp/EventBus/Azure/AzureDistributedEventBus.cs +++ b/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(rawBytes)); + tenantId = GetTenantIdFromMessage(message); + eventData = CreateDynamicEventData(eventName, Serializer.Deserialize(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(incomingEvent.EventData)); + eventData = CreateDynamicEventData(incomingEvent, Serializer.Deserialize(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, diff --git a/framework/src/Volo.Abp.EventBus.Kafka/Volo/Abp/EventBus/Kafka/KafkaDistributedEventBus.cs b/framework/src/Volo.Abp.EventBus.Kafka/Volo/Abp/EventBus/Kafka/KafkaDistributedEventBus.cs index a5b2b2869a..4ac6d4a805 100644 --- a/framework/src/Volo.Abp.EventBus.Kafka/Volo/Abp/EventBus/Kafka/KafkaDistributedEventBus.cs +++ b/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(message.Value)); + tenantId = message.GetTenantId(); + eventData = CreateDynamicEventData(eventName, Serializer.Deserialize(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 @@ -327,7 +335,7 @@ public class KafkaDistributedEventBus : DistributedEventBusBase, ISingletonDepen } else if (DynamicHandlerFactories.ContainsKey(incomingEvent.EventName)) { - eventData = new DynamicEventData(incomingEvent.EventName, Serializer.Deserialize(incomingEvent.EventData)); + eventData = CreateDynamicEventData(incomingEvent, Serializer.Deserialize(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); diff --git a/framework/src/Volo.Abp.EventBus.Kafka/Volo/Abp/EventBus/Kafka/MessageExtensions.cs b/framework/src/Volo.Abp.EventBus.Kafka/Volo/Abp/EventBus/Kafka/MessageExtensions.cs index cb487ed00f..e2a6e4d94c 100644 --- a/framework/src/Volo.Abp.EventBus.Kafka/Volo/Abp/EventBus/Kafka/MessageExtensions.cs +++ b/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(this Message message) + { + if (message.Headers.TryGetLastBytes(EventBusConsts.TenantIdHeaderName, out var tenantIdBytes)) + { + return EventBusTenantIdHelper.Parse(System.Text.Encoding.UTF8.GetString(tenantIdBytes)); + } + + return null; + } } diff --git a/framework/src/Volo.Abp.EventBus.RabbitMQ/Volo/Abp/EventBus/RabbitMq/RabbitMqDistributedEventBus.cs b/framework/src/Volo.Abp.EventBus.RabbitMQ/Volo/Abp/EventBus/RabbitMq/RabbitMqDistributedEventBus.cs index b18afd2ea8..529a16ddba 100644 --- a/framework/src/Volo.Abp.EventBus.RabbitMQ/Volo/Abp/EventBus/RabbitMq/RabbitMqDistributedEventBus.cs +++ b/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(rawBytes)); + tenantId = GetTenantIdFromHeaders(ea.BasicProperties.Headers); + eventData = CreateDynamicEventData(eventName, Serializer.Deserialize(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(incomingEvent.EventData)); + eventData = CreateDynamicEventData(incomingEvent, Serializer.Deserialize(incomingEvent.EventData)); eventType = typeof(DynamicEventData); } else @@ -338,12 +341,13 @@ public class RabbitMqDistributedEventBus : DistributedEventBusBase, IRabbitMqDis object eventData, Dictionary? 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? 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? 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(); + properties.Headers[EventBusConsts.TenantIdHeaderName] = tenantId.Value.ToString(); + } + + protected virtual Guid? GetTenantIdFromHeaders(IDictionary? 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? headersArguments) { if (headersArguments == null) diff --git a/framework/src/Volo.Abp.EventBus.Rebus/Volo/Abp/EventBus/Rebus/RebusDistributedEventBus.cs b/framework/src/Volo.Abp.EventBus.Rebus/Volo/Abp/EventBus/Rebus/RebusDistributedEventBus.cs index 42ba15a10d..b44b65bd4a 100644 --- a/framework/src/Volo.Abp.EventBus.Rebus/Volo/Abp/EventBus/Rebus/RebusDistributedEventBus.cs +++ b/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 headers, Guid? tenantId) + { + if (tenantId == null) + { + return; + } + + headers[EventBusConsts.TenantIdHeaderName] = tenantId.Value.ToString(); + } + protected virtual async Task PublishAsync( Type eventType, object eventData, diff --git a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Distributed/DistributedEventBusBase.cs b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Distributed/DistributedEventBusBase.cs index c4d186e2b3..855f859493 100644 --- a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Distributed/DistributedEventBusBase.cs +++ b/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) diff --git a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus.cs b/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus.cs index 1d8e1ed680..dbe3233ceb 100644 --- a/framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus.cs +++ b/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(outgoingEvent.EventData)!); + eventData = CreateDynamicEventData(outgoingEvent, System.Text.Json.JsonSerializer.Deserialize(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(incomingEvent.EventData)!); + eventData = CreateDynamicEventData(incomingEvent, System.Text.Json.JsonSerializer.Deserialize(incomingEvent.EventData)!); } else { diff --git a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/EventBusOutboxTestModule.cs b/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/EventBusOutboxTestModule.cs new file mode 100644 index 0000000000..f698cba883 --- /dev/null +++ b/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(options => + { + options.Outboxes.Configure(config => + { + config.ImplementationType = typeof(FakeEventOutbox); + }); + }); + } +} diff --git a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/FakeEventOutbox.cs b/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/FakeEventOutbox.cs new file mode 100644 index 0000000000..f746cf6968 --- /dev/null +++ b/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 Events { get; } = new(); + + public Task EnqueueAsync(OutgoingEventInfo outgoingEvent) + { + Events.Add(outgoingEvent); + return Task.CompletedTask; + } + + public Task> GetWaitingEventsAsync( + int maxCount, + Expression>? 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 ids) + { + var idList = ids.ToList(); + Events.RemoveAll(x => idList.Contains(x.Id)); + return Task.CompletedTask; + } +} diff --git a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_MultiTenancy_Test.cs b/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_MultiTenancy_Test.cs new file mode 100644 index 0000000000..5a35c4c4e1 --- /dev/null +++ b/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(); + } + + [Fact] + public void Should_Only_Propagate_The_Tenant_Of_Dynamic_Events() + { + var tenantId = Guid.NewGuid(); + var eventBus = ActivatorUtilities.CreateInstance(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(_ => + { + 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().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(() => EventBusTenantIdHelper.Parse("not-a-guid")); + } + + public class TestableLocalDistributedEventBus : LocalDistributedEventBus + { + public TestableLocalDistributedEventBus( + IServiceScopeFactory serviceScopeFactory, + ICurrentTenant currentTenant, + IUnitOfWorkManager unitOfWorkManager, + IOptions 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); + } + } +} diff --git a/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_Outbox_MultiTenancy_Test.cs b/framework/test/Volo.Abp.EventBus.Tests/Volo/Abp/EventBus/Distributed/LocalDistributedEventBus_Outbox_MultiTenancy_Test.cs new file mode 100644 index 0000000000..685e1ae2c2 --- /dev/null +++ b/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 +{ + private readonly IDistributedEventBus _distributedEventBus; + private readonly ICurrentTenant _currentTenant; + private readonly IUnitOfWorkManager _unitOfWorkManager; + private readonly FakeEventOutbox _outbox; + + public LocalDistributedEventBus_Outbox_MultiTenancy_Test() + { + _distributedEventBus = GetRequiredService(); + _currentTenant = GetRequiredService(); + _unitOfWorkManager = GetRequiredService(); + _outbox = GetRequiredService(); + } + + 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(); + } +} From 32c3f1ff58fa3d5b7c38e8d463d6cc2f96dd3128 Mon Sep 17 00:00:00 2001 From: maliming Date: Thu, 10 Sep 2026 17:58:11 +0800 Subject: [PATCH 3/3] Add migration guide note for the dynamic job and event tenant --- .../release-info/migration-guides/abp-10-7.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/docs/en/release-info/migration-guides/abp-10-7.md b/docs/en/release-info/migration-guides/abp-10-7.md index 81d63bdc91..079c58f3fc 100644 --- a/docs/en/release-info/migration-guides/abp-10-7.md +++ b/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**