From fdfd506977819b043a12682bea719de8e258b4ce Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Sat, 18 Jul 2026 20:31:37 +0000 Subject: [PATCH] =?UTF-8?q?fix:=20resolve=20GlitchTip=20anomalies=20?= =?UTF-8?q?=E2=80=94=20DB=20retry,=20query=20filters,=20Sentry=20DSN,=20Wo?= =?UTF-8?q?rkers=20tracking?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 🔴 Fix startup crash when DB is temporarily unavailable: add 5x retry with exponential backoff to Database.MigrateAsync() in API and Workers - 🔴 Fix EF Core 'required navigation with query filter' warnings: add matching soft-delete query filters to AgentSetting, CameraCredentials, CameraDetectionProfile, UserSite - 🔴 Add Sentry error tracking to Workers (Hangfire background jobs) - 🟡 Make Sentry/GlitchTip DSN configurable via SENTRY_DSN env var (applies to API, Web, Agent, Workers) - 🟡 Suppress EF Core RedundantIndexRemoved informational messages Closes GlitchTip #538 --- .env.example | 3 + src/Heimdall.Agent/Program.cs | 7 ++- src/Heimdall.Api/Program.cs | 58 +++++++++++-------- .../Data/AppDbContext.cs | 21 ++++++- src/Heimdall.Web/Program.cs | 7 ++- src/Heimdall.Workers/Heimdall.Workers.csproj | 1 + src/Heimdall.Workers/Program.cs | 45 +++++++++++++- 7 files changed, 108 insertions(+), 34 deletions(-) diff --git a/.env.example b/.env.example index d357594..f128d35 100644 --- a/.env.example +++ b/.env.example @@ -23,6 +23,9 @@ ALARIK_ADMIN_USERNAME=heimdall ALARIK_ADMIN_PASSWORD=heimdall123 ALARIK_JWT=ChangeMeAtLeast32BytesLongKeyInProd! +# Sentry / GlitchTip (error tracking) +# SENTRY_DSN=https://key@glitchtip.tordais.cc/6 + # Agent (set per agent instance) Agent__CentralUrl=http://heimdall-central:8080 Agent__SiteToken=replace-with-actual-token diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs index 9a63ba3..7911d55 100644 --- a/src/Heimdall.Agent/Program.cs +++ b/src/Heimdall.Agent/Program.cs @@ -4,15 +4,16 @@ using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Options; -// ── Sentry (GlitchTip) — hardcoded DSN, not overridable by env ──── -const string SentryDsn = "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6"; +// ── Sentry (GlitchTip) — DSN from env var, with hardcoded fallback ─ +var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN") + ?? "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6"; var builder = WebApplication.CreateSlimBuilder(args); // ── Sentry ──────────────────────────────────────────────────────── builder.WebHost.UseSentry(options => { - options.Dsn = SentryDsn; + options.Dsn = sentryDsn; options.MinimumBreadcrumbLevel = LogLevel.Debug; options.MinimumEventLevel = LogLevel.Error; options.TracesSampleRate = 0.1; diff --git a/src/Heimdall.Api/Program.cs b/src/Heimdall.Api/Program.cs index 63ff126..613b7ac 100644 --- a/src/Heimdall.Api/Program.cs +++ b/src/Heimdall.Api/Program.cs @@ -11,15 +11,16 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; -// ── Sentry (GlitchTip) — hardcoded DSN, not overridable by env ──── -const string SentryDsn = "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6"; +// ── Sentry (GlitchTip) — DSN from env var, with hardcoded fallback ─ +var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN") + ?? "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6"; var builder = WebApplication.CreateBuilder(args); // ── Sentry ──────────────────────────────────────────────────────── builder.WebHost.UseSentry(options => { - options.Dsn = SentryDsn; + options.Dsn = sentryDsn; options.MinimumBreadcrumbLevel = LogLevel.Debug; options.MinimumEventLevel = LogLevel.Error; options.TracesSampleRate = 0.1; @@ -143,35 +144,44 @@ var app = builder.Build(); // 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. +// independent of the seeding scope. +// Retry with exponential backoff to handle container startup races where +// PostgreSQL accepts TCP connections but isn't ready to serve queries yet +// (see GlitchTip #538 — Failed executing DbCommand on __EFMigrationsHistory). if (!app.Environment.IsEnvironment("Testing")) { 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 + var maxRetries = 5; + var retryDelay = TimeSpan.FromSeconds(2); + + for (var attempt = 1; attempt <= maxRetries; attempt++) { - 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; + try + { + migrationLogger.LogInformation("Applying pending database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries); + await db.Database.MigrateAsync(CancellationToken.None); + migrationLogger.LogInformation("Database migrations applied successfully"); + break; + } + catch (Exception ex) when (attempt < maxRetries) + { + migrationLogger.LogWarning(ex, + "Database migration attempt {Attempt}/{MaxRetries} failed. Retrying in {Delay}s...", + attempt, maxRetries, retryDelay.TotalSeconds); + await Task.Delay(retryDelay); + retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2); // Exponential backoff + } + catch (Exception ex) + { + migrationLogger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts. " + + "The application cannot start without a migrated database. " + + "Ensure the database server is running and accessible.", maxRetries); + throw; + } } } diff --git a/src/Heimdall.Infrastructure/Data/AppDbContext.cs b/src/Heimdall.Infrastructure/Data/AppDbContext.cs index 340c195..2662db0 100644 --- a/src/Heimdall.Infrastructure/Data/AppDbContext.cs +++ b/src/Heimdall.Infrastructure/Data/AppDbContext.cs @@ -3,6 +3,7 @@ using Heimdall.Infrastructure.Data.Interceptors; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; namespace Heimdall.Infrastructure.Data; @@ -28,10 +29,19 @@ public class AppDbContext : IdentityDbContext builder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly); - // Global soft-delete filter + // Global soft-delete filter — principal entities builder.Entity().HasQueryFilter(e => !e.IsDeleted); builder.Entity().HasQueryFilter(e => !e.IsDeleted); builder.Entity().HasQueryFilter(e => !e.IsDeleted); + + // Matching query filters on dependent entities to prevent + // "required navigation with query filter" EF Core warnings. + // Without these, loading an AgentSetting whose Agent was soft-deleted + // would cause a null reference on the required navigation. + builder.Entity().HasQueryFilter(e => e.Agent == null || !e.Agent.IsDeleted); + builder.Entity().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted); + builder.Entity().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted); + builder.Entity().HasQueryFilter(e => e.Site == null || !e.Site.IsDeleted); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) @@ -40,6 +50,15 @@ public class AppDbContext : IdentityDbContext new AuditInterceptor(), new SoftDeleteInterceptor()); + // Suppress informational EF Core messages that create noise in + // error tracking (GlitchTip #538). Redundant index warnings are + // automatically handled by EF Core — it simply skips creating FK + // indexes that are already covered by composite indexes/PKs. + optionsBuilder.ConfigureWarnings(warnings => + { + warnings.Ignore(CoreEventId.RedundantIndexRemoved); + }); + base.OnConfiguring(optionsBuilder); } } diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index 7b93d1b..959e433 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -4,15 +4,16 @@ using Heimdall.Web.Services; using Microsoft.AspNetCore.Components.Authorization; using MudBlazor.Services; -// ── Sentry (GlitchTip) — hardcoded DSN, not overridable by env ──── -const string SentryDsn = "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6"; +// ── Sentry (GlitchTip) — DSN from env var, with hardcoded fallback ─ +var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN") + ?? "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6"; var builder = WebApplication.CreateBuilder(args); // ── Sentry ──────────────────────────────────────────────────────── builder.WebHost.UseSentry(options => { - options.Dsn = SentryDsn; + options.Dsn = sentryDsn; options.MinimumBreadcrumbLevel = LogLevel.Debug; options.MinimumEventLevel = LogLevel.Error; options.TracesSampleRate = 0.1; diff --git a/src/Heimdall.Workers/Heimdall.Workers.csproj b/src/Heimdall.Workers/Heimdall.Workers.csproj index a6b0c47..286c934 100644 --- a/src/Heimdall.Workers/Heimdall.Workers.csproj +++ b/src/Heimdall.Workers/Heimdall.Workers.csproj @@ -12,6 +12,7 @@ + diff --git a/src/Heimdall.Workers/Program.cs b/src/Heimdall.Workers/Program.cs index ca4a111..3676b3a 100644 --- a/src/Heimdall.Workers/Program.cs +++ b/src/Heimdall.Workers/Program.cs @@ -7,9 +7,22 @@ using Hangfire.PostgreSql; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using Sentry; + +// ── Sentry (GlitchTip) — DSN from env var, with hardcoded fallback ─ +var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN") + ?? "https://db94b9fc2f36425f9eb4b9f6f347dc73@glitchtip.tordais.cc/6"; var builder = Host.CreateApplicationBuilder(args); +// ── Sentry (GlitchTip) ──────────────────────────────────────────── +builder.Logging.AddSentry(options => +{ + options.Dsn = sentryDsn; + options.MinimumBreadcrumbLevel = LogLevel.Debug; + options.MinimumEventLevel = LogLevel.Error; +}); + var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL") ?? builder.Configuration.GetConnectionString("Default") ?? "Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall"; @@ -41,13 +54,39 @@ builder.Services.AddScoped(); var host = builder.Build(); -// Apply migrations +// Apply migrations with retry (handles container startup races) using (var scope = host.Services.CreateScope()) { + var logger = scope.ServiceProvider.GetRequiredService>(); var db = scope.ServiceProvider.GetRequiredService(); - if (db.Database.GetPendingMigrations().Any()) + var maxRetries = 5; + var retryDelay = TimeSpan.FromSeconds(2); + + for (var attempt = 1; attempt <= maxRetries; attempt++) { - db.Database.Migrate(); + try + { + if (db.Database.GetPendingMigrations().Any()) + { + logger.LogInformation("Applying pending database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries); + db.Database.Migrate(); + logger.LogInformation("Database migrations applied successfully"); + } + break; + } + catch (Exception ex) when (attempt < maxRetries) + { + logger.LogWarning(ex, + "Database migration attempt {Attempt}/{MaxRetries} failed. Retrying in {Delay}s...", + attempt, maxRetries, retryDelay.TotalSeconds); + Thread.Sleep(retryDelay); + retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2); + } + catch (Exception ex) + { + logger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts.", maxRetries); + throw; + } } }