diff --git a/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreRuntimeDatabaseMigratorBase.cs b/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreRuntimeDatabaseMigratorBase.cs index ff557a2a73..35fd761813 100644 --- a/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreRuntimeDatabaseMigratorBase.cs +++ b/framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreRuntimeDatabaseMigratorBase.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.DistributedLocking; @@ -16,6 +17,8 @@ namespace Volo.Abp.EntityFrameworkCore.Migrations; public abstract class EfCoreRuntimeDatabaseMigratorBase : ITransientDependency where TDbContext : DbContext, IEfCoreDbContext { + private bool _isAppliedDatabaseMigrationsEventPending; + protected int MinValueToWaitOnFailure { get; set; } = 5000; protected int MaxValueToWaitOnFailure { get; set; } = 15000; @@ -56,6 +59,8 @@ public abstract class EfCoreRuntimeDatabaseMigratorBase : ITransient public virtual async Task CheckAndApplyDatabaseMigrationsAsync() { + // The pending event is only retried within this call. + _isAppliedDatabaseMigrationsEventPending = false; await TryAsync(LockAndApplyDatabaseMigrationsAsync); } @@ -69,6 +74,12 @@ public abstract class EfCoreRuntimeDatabaseMigratorBase : ITransient { if (handle is null) { + if (_isAppliedDatabaseMigrationsEventPending) + { + // Throw to retry, so the pending event is not silently lost. + throw new AbpException($"Distributed lock could not be acquired to save the {nameof(AppliedDatabaseMigrationsEto)} for database migration: {DatabaseName}."); + } + Logger.LogInformation($"Distributed lock could not be acquired for database migration: {DatabaseName}. Operation cancelled."); return; } @@ -100,21 +111,51 @@ public abstract class EfCoreRuntimeDatabaseMigratorBase : ITransient await SeedAsync(); - if (schemaMigrated || AlwaysSeedTenantDatabases) + if (schemaMigrated || AlwaysSeedTenantDatabases || _isAppliedDatabaseMigrationsEventPending) { - await DistributedEventBus.PublishAsync( - new AppliedDatabaseMigrationsEto - { - DatabaseName = DatabaseName, - TenantId = null - } - ); + await PublishAppliedDatabaseMigrationsEventAsync(); } } Logger.LogInformation($"Distributed lock has been released for database migration: {DatabaseName}..."); } + protected virtual async Task PublishAppliedDatabaseMigrationsEventAsync() + { + var eventData = new AppliedDatabaseMigrationsEto + { + DatabaseName = DatabaseName, + TenantId = null + }; + + if (UnitOfWorkManager.Current != null || !IsOutboxConfiguredFor(typeof(AppliedDatabaseMigrationsEto))) + { + await DistributedEventBus.PublishAsync(eventData); + return; + } + + // Saving to the outbox lets the application start without waiting for the message broker. + // Not transactional, to work with retrying execution strategies. The pending flag makes TryAsync save it again if it fails. + _isAppliedDatabaseMigrationsEventPending = true; + + using (CurrentTenant.Change(null)) + { + using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: false)) + { + await DistributedEventBus.PublishAsync(eventData); + await uow.CompleteAsync(); + } + } + + _isAppliedDatabaseMigrationsEventPending = false; + } + + protected virtual bool IsOutboxConfiguredFor(Type eventType) + { + var options = ServiceProvider.GetRequiredService>().Value; + return options.Outboxes.Values.Any(outboxConfig => outboxConfig.Selector == null || outboxConfig.Selector(eventType)); + } + protected virtual Task SeedAsync() { return Task.CompletedTask; diff --git a/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreRuntimeDatabaseMigratorBase_Tests.cs b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreRuntimeDatabaseMigratorBase_Tests.cs new file mode 100644 index 0000000000..bd333200c1 --- /dev/null +++ b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreRuntimeDatabaseMigratorBase_Tests.cs @@ -0,0 +1,159 @@ +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Volo.Abp.Modularity; +using Volo.Abp.TestApp.Testing; +using Volo.Abp.Uow; +using Xunit; + +namespace Volo.Abp.EntityFrameworkCore.Migrations; + +// The migration lock (LocalAbpDistributedLock) is process wide, so the migrator tests can not run in parallel. +[Collection(nameof(EfCoreRuntimeDatabaseMigratorBase_Tests))] +public class EfCoreRuntimeDatabaseMigratorBase_Tests : EfCoreRuntimeDatabaseMigratorBase_Tests +{ + [Fact] + public async Task Should_Save_The_Event_To_The_Outbox() + { + await CheckAndApplyDatabaseMigrationsAsync(); + + GetDirectlyPublishedEventCount().ShouldBe(0); + (await GetOutboxEventCountAsync()).ShouldBe(1); + } + + [Fact] + public async Task Should_Save_The_Event_To_The_Outbox_On_Retry_If_Saving_Fails() + { + GetRequiredService().RemainingFailures = 1; + + await CheckAndApplyDatabaseMigrationsAsync(); + + GetDirectlyPublishedEventCount().ShouldBe(0); + (await GetOutboxEventCountAsync()).ShouldBe(1); + } + + [Fact] + public async Task Should_Save_The_Event_To_The_Outbox_On_Retry_If_Another_Instance_Holds_The_Lock() + { + GetRequiredService().RemainingFailures = 1; + GetRequiredService().ContendedAcquisitionsAfterFirst = 1; + + await CheckAndApplyDatabaseMigrationsAsync(); + + GetDirectlyPublishedEventCount().ShouldBe(0); + (await GetOutboxEventCountAsync()).ShouldBe(1); + } + + [Fact] + public async Task Should_Throw_If_The_Event_Is_Not_Saved_Because_Another_Instance_Holds_The_Lock() + { + GetRequiredService().RemainingFailures = 1; + GetRequiredService().ContendedAcquisitionsAfterFirst = 2; + + await Should.ThrowAsync(CheckAndApplyDatabaseMigrationsAsync()); + + GetDirectlyPublishedEventCount().ShouldBe(0); + (await GetOutboxEventCountAsync()).ShouldBe(0); + } + + [Fact] + public async Task Should_Not_Keep_The_Pending_Event_For_The_Next_Call() + { + var migrator = GetRequiredService(); + var outboxSaveFailure = GetRequiredService(); + + outboxSaveFailure.RemainingFailures = 3; + await Should.ThrowAsync(migrator.CheckAndApplyDatabaseMigrationsAsync()); + + await migrator.CheckAndApplyDatabaseMigrationsAsync(); + + GetDirectlyPublishedEventCount().ShouldBe(0); + (await GetOutboxEventCountAsync()).ShouldBe(0); + } + + [Fact] + public async Task Should_Use_The_Current_Unit_Of_Work() + { + using (GetRequiredService().Begin(requiresNew: true)) + { + await CheckAndApplyDatabaseMigrationsAsync(); + + // Not completed, so the event is discarded with the unit of work. + } + + GetDirectlyPublishedEventCount().ShouldBe(0); + (await GetOutboxEventCountAsync()).ShouldBe(0); + } + + [Fact] + public async Task Should_Not_Publish_The_Event_Directly_If_It_Can_Not_Be_Saved_To_The_Outbox() + { + await WithUnitOfWorkAsync(async () => + { + var dbContext = await GetRequiredService>().GetDbContextAsync(); + await dbContext.Database.ExecuteSqlRawAsync("DROP TABLE AbpEventOutbox"); + }); + + await Should.ThrowAsync(CheckAndApplyDatabaseMigrationsAsync()); + + GetDirectlyPublishedEventCount().ShouldBe(0); + } +} + +[Collection(nameof(EfCoreRuntimeDatabaseMigratorBase_Tests))] +public class EfCoreRuntimeDatabaseMigratorBase_WithoutOutbox_Tests : EfCoreRuntimeDatabaseMigratorBase_Tests +{ + [Fact] + public async Task Should_Publish_The_Event_Directly() + { + await CheckAndApplyDatabaseMigrationsAsync(); + + GetDirectlyPublishedEventCount().ShouldBe(1); + (await GetOutboxEventCountAsync()).ShouldBe(0); + } + + [Fact] + public async Task Should_Not_Change_The_Unit_Of_Work_Of_The_Local_Handlers() + { + await CheckAndApplyDatabaseMigrationsAsync(); + + GetRequiredService().IsHandledInTransactionalUnitOfWork.ShouldBe(true); + } +} + +[Collection(nameof(EfCoreRuntimeDatabaseMigratorBase_Tests))] +public class EfCoreRuntimeDatabaseMigratorBase_ExcludedEvent_Tests : EfCoreRuntimeDatabaseMigratorBase_Tests +{ + [Fact] + public async Task Should_Publish_The_Event_Directly_If_The_Outbox_Does_Not_Accept_It() + { + await CheckAndApplyDatabaseMigrationsAsync(); + + GetDirectlyPublishedEventCount().ShouldBe(1); + (await GetOutboxEventCountAsync()).ShouldBe(0); + GetRequiredService().IsHandledInTransactionalUnitOfWork.ShouldBe(true); + } +} + +public abstract class EfCoreRuntimeDatabaseMigratorBase_Tests : TestAppTestBase + where TStartupModule : IAbpModule +{ + protected Task CheckAndApplyDatabaseMigrationsAsync() + { + return GetRequiredService().CheckAndApplyDatabaseMigrationsAsync(); + } + + protected int GetDirectlyPublishedEventCount() + { + return GetRequiredService().Count; + } + + protected Task GetOutboxEventCountAsync() + { + return WithUnitOfWorkAsync(async () => + { + var dbContext = await GetRequiredService>().GetDbContextAsync(); + return await dbContext.OutgoingEvents.CountAsync(); + }); + } +} diff --git a/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/RuntimeDatabaseMigratorTestModule.cs b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/RuntimeDatabaseMigratorTestModule.cs new file mode 100644 index 0000000000..907df3d3ce --- /dev/null +++ b/framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/RuntimeDatabaseMigratorTestModule.cs @@ -0,0 +1,243 @@ +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Volo.Abp.Autofac; +using Volo.Abp.Data; +using Volo.Abp.DependencyInjection; +using Volo.Abp.DistributedLocking; +using Volo.Abp.EntityFrameworkCore.DistributedEvents; +using Volo.Abp.EntityFrameworkCore.Sqlite; +using Volo.Abp.EventBus.Distributed; +using Volo.Abp.Modularity; +using Volo.Abp.MultiTenancy; +using Volo.Abp.Uow; + +namespace Volo.Abp.EntityFrameworkCore.Migrations; + +[DependsOn(typeof(AbpEntityFrameworkCoreSqliteModule), typeof(AbpAutofacModule))] +public class RuntimeDatabaseMigratorTestModule : RuntimeDatabaseMigratorTestModuleBase +{ + protected override void ConfigureOutboxes(OutboxConfigDictionary outboxes) + { + outboxes.Configure(config => + { + config.UseDbContext(); + // Keep the events in the outbox, so the tests can check them. + config.IsSendingEnabled = false; + }); + } +} + +[DependsOn(typeof(AbpEntityFrameworkCoreSqliteModule), typeof(AbpAutofacModule))] +public class RuntimeDatabaseMigratorWithoutOutboxTestModule : RuntimeDatabaseMigratorTestModuleBase +{ +} + +[DependsOn(typeof(AbpEntityFrameworkCoreSqliteModule), typeof(AbpAutofacModule))] +public class RuntimeDatabaseMigratorWithExcludedEventTestModule : RuntimeDatabaseMigratorTestModuleBase +{ + protected override void ConfigureOutboxes(OutboxConfigDictionary outboxes) + { + outboxes.Configure(config => + { + config.UseDbContext(); + config.IsSendingEnabled = false; + config.Selector = eventType => eventType != typeof(AppliedDatabaseMigrationsEto); + }); + } +} + +public abstract class RuntimeDatabaseMigratorTestModuleBase : AbpModule +{ + private readonly AbpUnitTestSqliteDatabase _database = new(); + private readonly RuntimeDatabaseMigratorTestOutboxSaveFailure _outboxSaveFailure = new(); + + protected virtual void ConfigureOutboxes(OutboxConfigDictionary outboxes) + { + } + + public override void ConfigureServices(ServiceConfigurationContext context) + { + context.Services.AddAbpDbContext(); + context.Services.AddSingleton(_outboxSaveFailure); + context.Services.Replace(ServiceDescriptor.Singleton()); + context.Services.AddSingleton(provider => (RuntimeDatabaseMigratorTestDistributedLock)provider.GetRequiredService()); + + _database.CreateTables(new RuntimeDatabaseMigratorTestDbContext( + new DbContextOptionsBuilder().UseSqlite(_database.ConnectionString).Options)); + + Configure(options => + { + options.ConnectionStrings[RuntimeDatabaseMigratorTestDbContext.DatabaseName] = _database.ConnectionString; + }); + + Configure(options => + { + options.Configure(configuration => + { + configuration.UseSqlite(sqlite => + { + sqlite.ExecutionStrategy(dependencies => new RuntimeDatabaseMigratorTestRetryingExecutionStrategy(dependencies)); + }); + configuration.DbContextOptions.AddInterceptors(_outboxSaveFailure); + }); + }); + + Configure(options => ConfigureOutboxes(options.Outboxes)); + } + + public override void OnApplicationShutdown(ApplicationShutdownContext context) + { + _database.Dispose(); + } +} + +[ConnectionStringName(DatabaseName)] +public class RuntimeDatabaseMigratorTestDbContext : AbpDbContext, IHasEventOutbox +{ + public const string DatabaseName = "RuntimeDatabaseMigratorTest"; + + public DbSet OutgoingEvents { get; set; } + + public RuntimeDatabaseMigratorTestDbContext(DbContextOptions options) + : base(options) + { + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.ConfigureEventOutbox(); + } +} + +// A real pending migration, so the migrator publishes the event like after a deployment. +[DbContext(typeof(RuntimeDatabaseMigratorTestDbContext))] +[Migration("20261017000000_RuntimeDatabaseMigratorTest")] +public class RuntimeDatabaseMigratorTestMigration : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql("CREATE TABLE RuntimeDatabaseMigratorTestMarkers (Id INTEGER NOT NULL)"); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql("DROP TABLE RuntimeDatabaseMigratorTestMarkers"); + } +} + +public class TestRuntimeDatabaseMigrator : EfCoreRuntimeDatabaseMigratorBase +{ + public TestRuntimeDatabaseMigrator( + IUnitOfWorkManager unitOfWorkManager, + IServiceProvider serviceProvider, + ICurrentTenant currentTenant, + IAbpDistributedLock abpDistributedLock, + IDistributedEventBus distributedEventBus, + ILoggerFactory loggerFactory) + : base( + RuntimeDatabaseMigratorTestDbContext.DatabaseName, + unitOfWorkManager, + serviceProvider, + currentTenant, + abpDistributedLock, + distributedEventBus, + loggerFactory) + { + MinValueToWaitOnFailure = 0; + MaxValueToWaitOnFailure = 1; + } +} + +public class AppliedDatabaseMigrationsRecorder : IDistributedEventHandler, ISingletonDependency +{ + private readonly IUnitOfWorkManager _unitOfWorkManager; + private int _count; + + public int Count => _count; + + public bool? IsHandledInTransactionalUnitOfWork { get; private set; } + + public AppliedDatabaseMigrationsRecorder(IUnitOfWorkManager unitOfWorkManager) + { + _unitOfWorkManager = unitOfWorkManager; + } + + [UnitOfWork(isTransactional: true)] + public virtual Task HandleEventAsync(AppliedDatabaseMigrationsEto eventData) + { + IsHandledInTransactionalUnitOfWork = _unitOfWorkManager.Current?.Options.IsTransactional; + Interlocked.Increment(ref _count); + return Task.CompletedTask; + } +} + +public class RuntimeDatabaseMigratorTestOutboxSaveFailure : SaveChangesInterceptor +{ + public int RemainingFailures { get; set; } + + public override ValueTask> SavingChangesAsync( + DbContextEventData eventData, + InterceptionResult result, + CancellationToken cancellationToken = default) + { + if (RemainingFailures > 0 && + eventData.Context.ChangeTracker.Entries().Any(x => x.State == EntityState.Added)) + { + RemainingFailures--; + throw new DbUpdateException("Could not save the outbox event."); + } + + return base.SavingChangesAsync(eventData, result, cancellationToken); + } +} + +// Simulates another instance that holds the lock after the first acquisition. +public class RuntimeDatabaseMigratorTestDistributedLock : IAbpDistributedLock +{ + private readonly LocalAbpDistributedLock _localDistributedLock; + private int _acquisitionCount; + + public int ContendedAcquisitionsAfterFirst { get; set; } + + public RuntimeDatabaseMigratorTestDistributedLock(LocalAbpDistributedLock localDistributedLock) + { + _localDistributedLock = localDistributedLock; + } + + public Task TryAcquireAsync(string name, TimeSpan timeout = default, CancellationToken cancellationToken = default) + { + if (++_acquisitionCount > 1 && ContendedAcquisitionsAfterFirst > 0) + { + ContendedAcquisitionsAfterFirst--; + return Task.FromResult(null); + } + + return _localDistributedLock.TryAcquireAsync(name, timeout, cancellationToken); + } +} + +// Rejects user-initiated transactions, like SQL Server's EnableRetryOnFailure. +public class RuntimeDatabaseMigratorTestRetryingExecutionStrategy : ExecutionStrategy +{ + public RuntimeDatabaseMigratorTestRetryingExecutionStrategy(ExecutionStrategyDependencies dependencies) + : base(dependencies, maxRetryCount: 3, maxRetryDelay: TimeSpan.FromMilliseconds(10)) + { + } + + protected override bool ShouldRetryOn(Exception exception) + { + return false; + } +}