From cb1e4d61b84c22e33f72c84706337bdbcdf184d2 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 18 Jul 2026 19:28:16 +0000 Subject: [PATCH] fix(db): migrate DB inline before seeding to prevent startup crash MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the background MigrationHostedService with inline db.Database.MigrateAsync() before Identity role seeding. The IHostedService started after app.Run(), but seeding ran synchronously before app.Run() — causing 42P01 when RoleManager queried the roles table that didn't exist yet. - Add await db.Database.MigrateAsync() with 120s timeout before seeding - Add structured logging (ILogger) and error handling around migration - Remove MigrationHostedService.cs (dead code — inline migration makes it permanently no-op) - Remove unused using Heimdall.Infrastructure.Services - Unify using style (using var instead of using block) --- src/Heimdall.Api/Program.cs | 53 ++++++++++--- .../Services/MigrationHostedService.cs | 74 ------------------- 2 files changed, 41 insertions(+), 86 deletions(-) delete mode 100644 src/Heimdall.Infrastructure/Services/MigrationHostedService.cs diff --git a/src/Heimdall.Api/Program.cs b/src/Heimdall.Api/Program.cs index 8b1ad2a..014d8b6 100644 --- a/src/Heimdall.Api/Program.cs +++ b/src/Heimdall.Api/Program.cs @@ -7,7 +7,6 @@ using Heimdall.Infrastructure; using Heimdall.Api.Hubs; using Heimdall.Infrastructure.Data; using Heimdall.Infrastructure.Security; -using Heimdall.Infrastructure.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; @@ -59,12 +58,6 @@ builder.Services.AddApplication(); // ── Infrastructure layer ────────────────────────────────────────── builder.Services.AddInfrastructure(builder.Configuration, builder.Environment.EnvironmentName); -// ── Background migration (replaces inline db.Database.Migrate()) ── -if (!builder.Environment.IsEnvironment("Testing")) -{ - builder.Services.AddHostedService(); -} - // ── Authentication ──────────────────────────────────────────────── var jwtKey = builder.Configuration["Jwt:Key"] ?? Environment.GetEnvironmentVariable("JWT__KEY") @@ -134,12 +127,48 @@ builder.Services.AddCors(options => var app = builder.Build(); -// Seed roles -using (var scope = app.Services.CreateScope()) +// ── Apply pending migrations before any database access ────────────── +// Migration runs inline (not as IHostedService) to guarantee the schema +// exists before Identity seeding below and before the web host starts +// serving requests. Using a separate scope keeps migration lifetime +// independent of the seeding scope. 120s timeout covers slow connections +// and large migrations on first deploy. +if (!app.Environment.IsEnvironment("Testing")) { - var roleManager = scope.ServiceProvider + using var migrationScope = app.Services.CreateScope(); + var migrationLogger = migrationScope.ServiceProvider + .GetRequiredService>(); + var db = migrationScope.ServiceProvider.GetRequiredService(); + using var migrationCts = new CancellationTokenSource(TimeSpan.FromSeconds(120)); + + try + { + migrationLogger.LogInformation("Applying pending database migrations..."); + await db.Database.MigrateAsync(migrationCts.Token); + migrationLogger.LogInformation("Database migrations applied successfully"); + } + catch (OperationCanceledException) when (!migrationCts.IsCancellationRequested) + { + migrationLogger.LogError("Database migration timed out after 120 seconds. " + + "Ensure the database server is running and accessible."); + throw new InvalidOperationException( + "Database migration timed out after 120 seconds. " + + "Check database connectivity and migration script correctness."); + } + catch (Exception ex) + { + migrationLogger.LogCritical(ex, "Failed to apply database migrations. " + + "The application cannot start without a migrated database."); + throw; + } +} + +// ── Seed Identity roles (requires roles table to exist) ────────────── +using var seedScope = app.Services.CreateScope(); +{ + var roleManager = seedScope.ServiceProvider .GetRequiredService>(); - var userManager = scope.ServiceProvider + var userManager = seedScope.ServiceProvider .GetRequiredService>(); foreach (var roleName in AppRoles.All) @@ -166,7 +195,7 @@ using (var scope = app.Services.CreateScope()) await userManager.AddToRoleAsync(testAdmin, AppRoles.Admin); } - var demoDb = scope.ServiceProvider.GetRequiredService(); + var demoDb = seedScope.ServiceProvider.GetRequiredService(); var demoSite = await demoDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo"); if (demoSite is null) { diff --git a/src/Heimdall.Infrastructure/Services/MigrationHostedService.cs b/src/Heimdall.Infrastructure/Services/MigrationHostedService.cs deleted file mode 100644 index 43ab256..0000000 --- a/src/Heimdall.Infrastructure/Services/MigrationHostedService.cs +++ /dev/null @@ -1,74 +0,0 @@ -using Heimdall.Infrastructure.Data; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; - -namespace Heimdall.Infrastructure.Services; - -/// -/// Applies pending EF Core migrations as a background service at startup. -/// Replaces the inline `db.Database.Migrate()` pattern to: -/// - Allow the web host to start quickly (migrations run in background) -/// - Enable health checks to verify migration completion -/// - Avoid holding up the startup pipeline -/// - Log migration progress clearly -/// -public class MigrationHostedService : IHostedService -{ - private readonly IServiceProvider _serviceProvider; - private readonly ILogger _logger; - - public MigrationHostedService( - IServiceProvider serviceProvider, - ILogger logger) - { - _serviceProvider = serviceProvider; - _logger = logger; - } - - public async Task StartAsync(CancellationToken cancellationToken) - { - _logger.LogInformation("Migration service starting..."); - - try - { - using var scope = _serviceProvider.CreateScope(); - var db = scope.ServiceProvider.GetRequiredService(); - - var pending = await db.Database.GetPendingMigrationsAsync(cancellationToken); - var pendingList = pending.ToList(); - - if (pendingList.Count == 0) - { - _logger.LogInformation("No pending migrations to apply"); - return; - } - - _logger.LogInformation( - "Applying {Count} pending migration(s): {Migrations}", - pendingList.Count, - string.Join(", ", pendingList)); - - // Apply with timeout to prevent indefinite blocking - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - cts.CancelAfter(TimeSpan.FromSeconds(60)); - - await db.Database.MigrateAsync(cts.Token); - - _logger.LogInformation("All migrations applied successfully"); - } - catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) - { - _logger.LogError("Migration timed out after 60 seconds. " + - "Check database connectivity and migration script correctness."); - } - catch (Exception ex) - { - _logger.LogCritical(ex, "Failed to apply database migrations. " + - "The application may not function correctly without a migrated database."); - } - } - - public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; -}