using Heimdall.Application.Common; using Heimdall.Application.Services; using Heimdall.Domain.Entities; 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; public class AppDbContext : IdentityDbContext, IApplicationDbContext { private readonly AuditInterceptor _auditInterceptor; private readonly IServiceProvider? _serviceProvider; public AppDbContext( DbContextOptions options, AuditInterceptor auditInterceptor, IServiceProvider? serviceProvider = null) : base(options) { _auditInterceptor = auditInterceptor; _serviceProvider = serviceProvider; } // Domain entities public DbSet Sites => Set(); public DbSet SiteCredentials => Set(); public DbSet Agents => Set(); public DbSet AgentMetricSamples => Set(); public DbSet AgentLogEntries => Set(); public DbSet Cameras => Set(); public DbSet CameraCredentials => Set(); public DbSet CameraDetectionProfiles => Set(); public DbSet UserCameras => Set(); public DbSet UserCameraAccesses => Set(); public DbSet UserSites => Set(); public DbSet ApiKeys => Set(); public DbSet AuditLogs => Set(); public DbSet AppSettings => Set(); public DbSet AgentSettings => Set(); public DbSet Groups => Set(); public DbSet UserGroups => Set(); public DbSet GroupCameraAccesses => Set(); // Discovery entities public DbSet CameraDiscoveryResults => Set(); public DbSet DiscoveredStreams => Set(); // Assignment entities public DbSet CameraAssignments => Set(); // Event entities public DbSet CameraEvents => Set(); public DbSet ManualSnapshotRequests => Set(); // Notification entities public DbSet Notifications => Set(); public DbSet NotificationDeliveries => Set(); public DbSet NotificationTemplates => Set(); public DbSet UserNotificationConfigs => Set(); // Security entities public DbSet RevokedRefreshTokens => Set(); // Person entities public DbSet Persons => Set(); public DbSet KnownFaces => Set(); // 2FA recovery codes (stored hashed) public DbSet UserRecoveryCodes => Set(); // Identity tables (for synchronous admin checks in IQueryable filters) public new DbSet Roles => Set(); // Suppress CS0114 — base IdentityDbContext.UserRoles is virtual but we need // the specific DbSet> type exposed through IApplicationDbContext. public new DbSet> UserRoles => Set>(); // Domain métier (spec 2.1) public DbSet Vehicles => Set(); public DbSet Recordings => Set(); public DbSet LicensePlates => Set(); public DbSet StoragePolicies => Set(); public DbSet StorageDestinations => Set(); // Analysis job scheduling public DbSet AnalysisJobs => Set(); public DbSet GetSet() where TEntity : class => Set(); public async Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default) { await DbContextExtensions.SaveChangesWithRetryAsync(this, maxRetries, ct).ConfigureAwait(false); } public override async Task SaveChangesAsync(CancellationToken cancellationToken = default) { ChangeTracker.DetectChanges(); // Keep history consistent for direct camera writes (including discovery). var changedCameras = ChangeTracker.Entries() .Where(e => e.State == EntityState.Added || e.Property(c => c.AgentId).IsModified).ToArray(); foreach (var entry in changedCameras) { var camera = entry.Entity; var active = await CameraAssignments.AsTracking() .Where(a => a.CameraId == camera.Id && a.ReleasedAt == null).ToListAsync(cancellationToken); foreach (var assignment in active.Where(a => a.AgentId != camera.AgentId)) assignment.Release(); var pending = CameraAssignments.Local.Any(a => a.CameraId == camera.Id && a.AgentId == camera.AgentId && a.ReleasedAt == null); if (camera.AgentId is { } agentId && !pending) CameraAssignments.Add(new CameraAssignment(camera.Id, agentId, "camera-config")); } var invalidate = ChangeTracker.Entries().Any(e => e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted && e.Entity is Camera or CameraAssignment or CameraDetectionProfile); var result = await base.SaveChangesAsync(cancellationToken).ConfigureAwait(false); if (invalidate) { // Resolve only after this DbContext is fully constructed. The broadcast service // depends on IApplicationDbContext, which maps back to this scoped instance. // Resolving it in the constructor creates a circular dependency during startup. try { var configBroadcast = _serviceProvider?.GetService(typeof(IConfigBroadcastService)) as IConfigBroadcastService; if (configBroadcast is not null) { // Payload-free invalidation: each agent refetches its authorized full snapshot. // Delivery is best effort; reconnect and periodic resync recover a missed notification. await configBroadcast.NotifyAllAgentsReload(cancellationToken).ConfigureAwait(false); } } catch (Exception ex) when (ex is not OutOfMemoryException) { System.Diagnostics.Trace.TraceError("Config invalidation delivery failed: {0}", ex.GetType().Name); } } return result; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly); // 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); builder.Entity().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted); // Matching query filters for dependent entities sharing required // navigations to soft-deletable entities. These prevent EF Core // warnings (10622) about required ends with global query filters. builder.Entity().HasQueryFilter(e => e.Agent == null || !e.Agent.IsDeleted); builder.Entity().HasQueryFilter(e => e.Site == null || !e.Site.IsDeleted); builder.Entity().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted); builder.Entity().HasQueryFilter(e => e.DiscoveryResult == null || e.DiscoveryResult.Site == null || !e.DiscoveryResult.Site.IsDeleted); builder.Entity().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted); // Group soft-delete filters builder.Entity().HasQueryFilter(e => !e.IsDeleted); builder.Entity().HasQueryFilter(e => e.Group == null || !e.Group.IsDeleted); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.AddInterceptors( _auditInterceptor); // 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. // Also suppress PendingModelChangesWarning because matching query filters // (used for soft-delete) cause this warning to be promoted to an exception. optionsBuilder.ConfigureWarnings(warnings => { warnings.Ignore(CoreEventId.RedundantIndexRemoved); warnings.Ignore(RelationalEventId.PendingModelChangesWarning); }); base.OnConfiguring(optionsBuilder); } }