Browse Source

Merge pull request #26304 from abpframework/auto-merge-forward/rel-10.7-to-dev-93

Auto-merge forward rel-10.7 → dev
pull/26309/head
Volosoft Agent 1 month ago
committed by GitHub
parent
commit
054afbdade
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 57
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreRuntimeDatabaseMigratorBase.cs
  2. 159
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreRuntimeDatabaseMigratorBase_Tests.cs
  3. 243
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/RuntimeDatabaseMigratorTestModule.cs

57
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<TDbContext> : 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<TDbContext> : 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<TDbContext> : 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<TDbContext> : 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<IOptions<AbpDistributedEventBusOptions>>().Value;
return options.Outboxes.Values.Any(outboxConfig => outboxConfig.Selector == null || outboxConfig.Selector(eventType));
}
protected virtual Task SeedAsync()
{
return Task.CompletedTask;

159
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<RuntimeDatabaseMigratorTestModule>
{
[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<RuntimeDatabaseMigratorTestOutboxSaveFailure>().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<RuntimeDatabaseMigratorTestOutboxSaveFailure>().RemainingFailures = 1;
GetRequiredService<RuntimeDatabaseMigratorTestDistributedLock>().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<RuntimeDatabaseMigratorTestOutboxSaveFailure>().RemainingFailures = 1;
GetRequiredService<RuntimeDatabaseMigratorTestDistributedLock>().ContendedAcquisitionsAfterFirst = 2;
await Should.ThrowAsync<AbpException>(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<TestRuntimeDatabaseMigrator>();
var outboxSaveFailure = GetRequiredService<RuntimeDatabaseMigratorTestOutboxSaveFailure>();
outboxSaveFailure.RemainingFailures = 3;
await Should.ThrowAsync<DbUpdateException>(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<IUnitOfWorkManager>().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<IDbContextProvider<RuntimeDatabaseMigratorTestDbContext>>().GetDbContextAsync();
await dbContext.Database.ExecuteSqlRawAsync("DROP TABLE AbpEventOutbox");
});
await Should.ThrowAsync<DbUpdateException>(CheckAndApplyDatabaseMigrationsAsync());
GetDirectlyPublishedEventCount().ShouldBe(0);
}
}
[Collection(nameof(EfCoreRuntimeDatabaseMigratorBase_Tests))]
public class EfCoreRuntimeDatabaseMigratorBase_WithoutOutbox_Tests : EfCoreRuntimeDatabaseMigratorBase_Tests<RuntimeDatabaseMigratorWithoutOutboxTestModule>
{
[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<AppliedDatabaseMigrationsRecorder>().IsHandledInTransactionalUnitOfWork.ShouldBe(true);
}
}
[Collection(nameof(EfCoreRuntimeDatabaseMigratorBase_Tests))]
public class EfCoreRuntimeDatabaseMigratorBase_ExcludedEvent_Tests : EfCoreRuntimeDatabaseMigratorBase_Tests<RuntimeDatabaseMigratorWithExcludedEventTestModule>
{
[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<AppliedDatabaseMigrationsRecorder>().IsHandledInTransactionalUnitOfWork.ShouldBe(true);
}
}
public abstract class EfCoreRuntimeDatabaseMigratorBase_Tests<TStartupModule> : TestAppTestBase<TStartupModule>
where TStartupModule : IAbpModule
{
protected Task CheckAndApplyDatabaseMigrationsAsync()
{
return GetRequiredService<TestRuntimeDatabaseMigrator>().CheckAndApplyDatabaseMigrationsAsync();
}
protected int GetDirectlyPublishedEventCount()
{
return GetRequiredService<AppliedDatabaseMigrationsRecorder>().Count;
}
protected Task<int> GetOutboxEventCountAsync()
{
return WithUnitOfWorkAsync(async () =>
{
var dbContext = await GetRequiredService<IDbContextProvider<RuntimeDatabaseMigratorTestDbContext>>().GetDbContextAsync();
return await dbContext.OutgoingEvents.CountAsync();
});
}
}

243
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<RuntimeDatabaseMigratorTestDbContext>();
// 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<RuntimeDatabaseMigratorTestDbContext>();
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<RuntimeDatabaseMigratorTestDbContext>();
context.Services.AddSingleton(_outboxSaveFailure);
context.Services.Replace(ServiceDescriptor.Singleton<IAbpDistributedLock, RuntimeDatabaseMigratorTestDistributedLock>());
context.Services.AddSingleton(provider => (RuntimeDatabaseMigratorTestDistributedLock)provider.GetRequiredService<IAbpDistributedLock>());
_database.CreateTables(new RuntimeDatabaseMigratorTestDbContext(
new DbContextOptionsBuilder<RuntimeDatabaseMigratorTestDbContext>().UseSqlite(_database.ConnectionString).Options));
Configure<AbpDbConnectionOptions>(options =>
{
options.ConnectionStrings[RuntimeDatabaseMigratorTestDbContext.DatabaseName] = _database.ConnectionString;
});
Configure<AbpDbContextOptions>(options =>
{
options.Configure<RuntimeDatabaseMigratorTestDbContext>(configuration =>
{
configuration.UseSqlite(sqlite =>
{
sqlite.ExecutionStrategy(dependencies => new RuntimeDatabaseMigratorTestRetryingExecutionStrategy(dependencies));
});
configuration.DbContextOptions.AddInterceptors(_outboxSaveFailure);
});
});
Configure<AbpDistributedEventBusOptions>(options => ConfigureOutboxes(options.Outboxes));
}
public override void OnApplicationShutdown(ApplicationShutdownContext context)
{
_database.Dispose();
}
}
[ConnectionStringName(DatabaseName)]
public class RuntimeDatabaseMigratorTestDbContext : AbpDbContext<RuntimeDatabaseMigratorTestDbContext>, IHasEventOutbox
{
public const string DatabaseName = "RuntimeDatabaseMigratorTest";
public DbSet<OutgoingEventRecord> OutgoingEvents { get; set; }
public RuntimeDatabaseMigratorTestDbContext(DbContextOptions<RuntimeDatabaseMigratorTestDbContext> 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<RuntimeDatabaseMigratorTestDbContext>
{
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<AppliedDatabaseMigrationsEto>, 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<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData,
InterceptionResult<int> result,
CancellationToken cancellationToken = default)
{
if (RemainingFailures > 0 &&
eventData.Context.ChangeTracker.Entries<OutgoingEventRecord>().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<IAbpDistributedLockHandle> TryAcquireAsync(string name, TimeSpan timeout = default, CancellationToken cancellationToken = default)
{
if (++_acquisitionCount > 1 && ContendedAcquisitionsAfterFirst > 0)
{
ContendedAcquisitionsAfterFirst--;
return Task.FromResult<IAbpDistributedLockHandle>(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;
}
}
Loading…
Cancel
Save