fix: resolve GlitchTip anomalies — DB retry, query filters, Sentry DSN, Workers tracking

- 🔴 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
This commit is contained in:
Arnaud Dartois committed 2026-07-18 20:31:37 +00:00
1 parent ee66cf5971
commit fdfd506977
7 files changed
+108 -34

No files matched your search

+34 -24
View File
@@ -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<ILogger<Program>>();
var db = migrationScope.ServiceProvider.GetRequiredService<AppDbContext>();
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;
}
}
}