Browse Source

Skip database migration events of a tenant that no longer exists

A tenant can be deleted before the services handle its TenantCreated event. EfCoreDatabaseMigrationEventHandlerBase then dereferenced the null tenant configuration, and every service logged a NullReferenceException, re-queued the event and finally cancelled it. Skip TenantCreated, TenantConnectionStringUpdated and ApplyDatabaseMigrations events of a tenant the tenant store no longer finds, and make MigrateDatabaseSchemaAsync null-safe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/26500/head
oykuermann 4 days ago
parent
commit
03df4dfa40
  1. 45
      framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase.cs
  2. 118
      framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase_Tests.cs

45
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase.cs

@ -76,6 +76,13 @@ public abstract class EfCoreDatabaseMigrationEventHandlerBase<TDbContext> :
return;
}
if (eventData.TenantId.HasValue && !await TenantExistsAsync(eventData.TenantId.Value))
{
Logger.LogInformation(
$"Skipping the database migrations: the tenant no longer exists. TenantId = {eventData.TenantId}, Database Name = {DatabaseName}.");
return;
}
var schemaMigrated = false;
try
{
@ -108,6 +115,13 @@ public abstract class EfCoreDatabaseMigrationEventHandlerBase<TDbContext> :
public virtual async Task HandleEventAsync(TenantCreatedEto eventData)
{
if (!await TenantExistsAsync(eventData.Id))
{
Logger.LogInformation(
$"Skipping the tenant created event: the tenant no longer exists. TenantId = {eventData.Id}, TenantName = {eventData.Name}, Database Name = {DatabaseName}.");
return;
}
var schemaMigrated = false;
try
{
@ -147,6 +161,13 @@ public abstract class EfCoreDatabaseMigrationEventHandlerBase<TDbContext> :
return;
}
if (!await TenantExistsAsync(eventData.Id))
{
Logger.LogInformation(
$"Skipping the tenant connection string updated event: the tenant no longer exists. TenantId = {eventData.Id}, TenantName = {eventData.Name}, Database Name = {DatabaseName}.");
return;
}
var schemaMigrated = false;
try
{
@ -183,6 +204,20 @@ public abstract class EfCoreDatabaseMigrationEventHandlerBase<TDbContext> :
return Task.CompletedTask;
}
/// <summary>
/// A tenant can be deleted before an event about it is handled (the events are handled asynchronously,
/// and each service handles them on its own). Such an event has nothing to migrate or seed.
/// </summary>
protected virtual async Task<bool> TenantExistsAsync(Guid tenantId)
{
using (var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: false))
{
var tenantConfiguration = await TenantStore.FindAsync(tenantId);
await uow.CompleteAsync();
return tenantConfiguration != null;
}
}
/// <summary>
/// Apply pending EF Core schema migrations to the database.
/// Returns true if any migration has applied.
@ -238,8 +273,14 @@ public abstract class EfCoreDatabaseMigrationEventHandlerBase<TDbContext> :
else
{
var tenantConfiguration = await TenantStore.FindAsync(tenantId.Value);
if (!tenantConfiguration!.ConnectionStrings!.Default.IsNullOrWhiteSpace() ||
!tenantConfiguration.ConnectionStrings.GetOrDefault(DatabaseName).IsNullOrWhiteSpace())
if (tenantConfiguration == null)
{
Logger.LogInformation(
$"The tenant no longer exists, its database is not migrated. Database Name = {DatabaseName}, TenantId = {tenantId}");
}
else if (tenantConfiguration.ConnectionStrings != null &&
(!tenantConfiguration.ConnectionStrings.Default.IsNullOrWhiteSpace() ||
!tenantConfiguration.ConnectionStrings.GetOrDefault(DatabaseName).IsNullOrWhiteSpace()))
{
//Migrating the tenant database (only if tenant has a separate database)
Logger.LogInformation(

118
framework/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Migrations/EfCoreDatabaseMigrationEventHandlerBase_Tests.cs

@ -0,0 +1,118 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Shouldly;
using Volo.Abp.Data;
using Volo.Abp.DistributedLocking;
using Volo.Abp.EventBus.Distributed;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Uow;
using Xunit;
namespace Volo.Abp.EntityFrameworkCore.Migrations;
public class EfCoreDatabaseMigrationEventHandlerBase_Tests : EntityFrameworkCoreTestBase
{
// A tenant can be deleted before the services handle the events about it: the tenant store then returns null.
[Fact]
public async Task Should_Skip_The_Tenant_Created_Event_Of_A_Deleted_Tenant()
{
var handler = CreateHandler();
await handler.HandleEventAsync(new TenantCreatedEto { Id = Guid.NewGuid(), Name = "deleted-tenant" });
handler.SeededTenantIds.ShouldBeEmpty();
handler.Errors.ShouldBeEmpty();
}
[Fact]
public async Task Should_Skip_The_Connection_String_Updated_Event_Of_A_Deleted_Tenant()
{
var handler = CreateHandler();
await handler.HandleEventAsync(new TenantConnectionStringUpdatedEto
{
Id = Guid.NewGuid(),
Name = "deleted-tenant",
ConnectionStringName = TestDatabaseMigrationEventHandler.TestDatabaseName,
NewValue = "Data Source=deleted-tenant.db"
});
handler.SeededTenantIds.ShouldBeEmpty();
handler.Errors.ShouldBeEmpty();
}
[Fact]
public async Task Should_Skip_The_Apply_Database_Migrations_Event_Of_A_Deleted_Tenant()
{
var handler = CreateHandler();
await handler.HandleEventAsync(new ApplyDatabaseMigrationsEto
{
TenantId = Guid.NewGuid(),
DatabaseName = TestDatabaseMigrationEventHandler.TestDatabaseName
});
handler.SeededTenantIds.ShouldBeEmpty();
handler.Errors.ShouldBeEmpty();
}
private TestDatabaseMigrationEventHandler CreateHandler()
{
return new TestDatabaseMigrationEventHandler(
GetRequiredService<ICurrentTenant>(),
GetRequiredService<IUnitOfWorkManager>(),
GetRequiredService<ITenantStore>(),
GetRequiredService<IAbpDistributedLock>(),
GetRequiredService<IDistributedEventBus>(),
GetRequiredService<ILoggerFactory>()
);
}
private class TestDatabaseMigrationEventHandler : EfCoreDatabaseMigrationEventHandlerBase<TestMigrationsDbContext>
{
public const string TestDatabaseName = "TestMigrations";
public List<Guid?> SeededTenantIds { get; } = new();
public List<Exception> Errors { get; } = new();
public TestDatabaseMigrationEventHandler(
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager,
ITenantStore tenantStore,
IAbpDistributedLock abpDistributedLock,
IDistributedEventBus distributedEventBus,
ILoggerFactory loggerFactory)
: base(TestDatabaseName, currentTenant, unitOfWorkManager, tenantStore, abpDistributedLock, distributedEventBus, loggerFactory)
{
}
protected override Task SeedAsync(Guid? tenantId)
{
SeededTenantIds.Add(tenantId);
return Task.CompletedTask;
}
// Recorded instead of re-queued, so that a failure shows up at once.
protected override Task HandleErrorTenantCreatedAsync(TenantCreatedEto eventData, Exception exception)
{
Errors.Add(exception);
return Task.CompletedTask;
}
protected override Task HandleErrorTenantConnectionStringUpdatedAsync(TenantConnectionStringUpdatedEto eventData, Exception exception)
{
Errors.Add(exception);
return Task.CompletedTask;
}
protected override Task HandleErrorOnApplyDatabaseMigrationAsync(ApplyDatabaseMigrationsEto eventData, Exception exception)
{
Errors.Add(exception);
return Task.CompletedTask;
}
}
}
Loading…
Cancel
Save