fix(db): migrate DB inline before seeding to prevent startup crash

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)
This commit is contained in:
Arnaud Dartois committed 2026-07-18 19:28:16 +00:00
1 parent cca6ab6f46
commit cb1e4d61b8
2 files changed
+41 -86

No files matched your search

+41 -12
View File
@@ -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<MigrationHostedService>();
}
// ── 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<ILogger<Program>>();
var db = migrationScope.ServiceProvider.GetRequiredService<AppDbContext>();
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<Microsoft.AspNetCore.Identity.RoleManager<Heimdall.Domain.Entities.AppRole>>();
var userManager = scope.ServiceProvider
var userManager = seedScope.ServiceProvider
.GetRequiredService<Microsoft.AspNetCore.Identity.UserManager<Heimdall.Domain.Entities.AppUser>>();
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<AppDbContext>();
var demoDb = seedScope.ServiceProvider.GetRequiredService<AppDbContext>();
var demoSite = await demoDb.Sites.FirstOrDefaultAsync(s => s.Name == "Site Démo");
if (demoSite is null)
{