2026-07-22 19:43:13 +00:00
|
|
|
using Heimdall.Application.Common;
|
2026-10-20 02:26:49 +02:00
|
|
|
using Heimdall.Application.Services;
|
2026-07-16 20:53:56 +00:00
|
|
|
using Heimdall.Domain.Entities;
|
|
|
|
|
using Heimdall.Infrastructure.Data.Interceptors;
|
|
|
|
|
using Microsoft.AspNetCore.Identity;
|
|
|
|
|
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2026-07-18 20:31:37 +00:00
|
|
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
2026-07-16 20:53:56 +00:00
|
|
|
|
|
|
|
|
namespace Heimdall.Infrastructure.Data;
|
|
|
|
|
|
2026-07-22 19:43:13 +00:00
|
|
|
public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>, IApplicationDbContext
|
2026-07-16 20:53:56 +00:00
|
|
|
{
|
2026-07-19 19:58:45 +00:00
|
|
|
private readonly AuditInterceptor _auditInterceptor;
|
2026-10-20 20:57:16 +02:00
|
|
|
private readonly IServiceProvider? _serviceProvider;
|
2026-07-19 19:58:45 +00:00
|
|
|
|
|
|
|
|
public AppDbContext(
|
|
|
|
|
DbContextOptions<AppDbContext> options,
|
2026-10-20 20:57:16 +02:00
|
|
|
AuditInterceptor auditInterceptor, IServiceProvider? serviceProvider = null) : base(options)
|
2026-07-19 19:58:45 +00:00
|
|
|
{
|
|
|
|
|
_auditInterceptor = auditInterceptor;
|
2026-10-20 20:57:16 +02:00
|
|
|
_serviceProvider = serviceProvider;
|
2026-07-19 19:58:45 +00:00
|
|
|
}
|
2026-07-16 20:53:56 +00:00
|
|
|
|
|
|
|
|
// Domain entities
|
|
|
|
|
public DbSet<Site> Sites => Set<Site>();
|
2026-08-11 16:15:41 +02:00
|
|
|
public DbSet<SiteCredential> SiteCredentials => Set<SiteCredential>();
|
2026-07-16 20:53:56 +00:00
|
|
|
public DbSet<Agent> Agents => Set<Agent>();
|
2026-10-25 02:19:01 +02:00
|
|
|
public DbSet<AgentMetricSample> AgentMetricSamples => Set<AgentMetricSample>();
|
2026-08-11 18:51:52 +02:00
|
|
|
public DbSet<AgentLogEntry> AgentLogEntries => Set<AgentLogEntry>();
|
2026-07-16 20:53:56 +00:00
|
|
|
public DbSet<Camera> Cameras => Set<Camera>();
|
|
|
|
|
public DbSet<CameraCredentials> CameraCredentials => Set<CameraCredentials>();
|
|
|
|
|
public DbSet<CameraDetectionProfile> CameraDetectionProfiles => Set<CameraDetectionProfile>();
|
2026-08-27 20:28:41 +02:00
|
|
|
public DbSet<UserCamera> UserCameras => Set<UserCamera>();
|
2026-08-30 09:48:47 +02:00
|
|
|
public DbSet<UserCameraAccess> UserCameraAccesses => Set<UserCameraAccess>();
|
2026-07-16 20:53:56 +00:00
|
|
|
public DbSet<UserSite> UserSites => Set<UserSite>();
|
|
|
|
|
public DbSet<ApiKey> ApiKeys => Set<ApiKey>();
|
|
|
|
|
public DbSet<AuditLog> AuditLogs => Set<AuditLog>();
|
2026-07-18 18:58:20 +00:00
|
|
|
public DbSet<AppSetting> AppSettings => Set<AppSetting>();
|
|
|
|
|
public DbSet<AgentSetting> AgentSettings => Set<AgentSetting>();
|
2026-07-19 06:49:17 +00:00
|
|
|
public DbSet<Group> Groups => Set<Group>();
|
|
|
|
|
public DbSet<UserGroup> UserGroups => Set<UserGroup>();
|
2026-10-10 22:45:36 +02:00
|
|
|
public DbSet<GroupCameraAccess> GroupCameraAccesses => Set<GroupCameraAccess>();
|
2026-07-16 20:53:56 +00:00
|
|
|
|
2026-07-18 21:15:05 +00:00
|
|
|
// Discovery entities
|
|
|
|
|
public DbSet<CameraDiscoveryResult> CameraDiscoveryResults => Set<CameraDiscoveryResult>();
|
|
|
|
|
public DbSet<DiscoveredStreamUrl> DiscoveredStreams => Set<DiscoveredStreamUrl>();
|
2026-07-19 12:20:07 +00:00
|
|
|
|
|
|
|
|
// Assignment entities
|
|
|
|
|
public DbSet<CameraAssignment> CameraAssignments => Set<CameraAssignment>();
|
2026-07-19 12:55:05 +00:00
|
|
|
|
|
|
|
|
// Event entities
|
|
|
|
|
public DbSet<CameraEvent> CameraEvents => Set<CameraEvent>();
|
2026-10-23 07:30:58 +02:00
|
|
|
public DbSet<ManualSnapshotRequest> ManualSnapshotRequests => Set<ManualSnapshotRequest>();
|
2026-07-19 15:28:38 +00:00
|
|
|
|
2026-07-26 20:45:35 +00:00
|
|
|
// Notification entities
|
|
|
|
|
public DbSet<Notification> Notifications => Set<Notification>();
|
2026-10-24 22:27:53 +02:00
|
|
|
public DbSet<NotificationDelivery> NotificationDeliveries => Set<NotificationDelivery>();
|
2026-07-26 20:45:35 +00:00
|
|
|
public DbSet<NotificationTemplate> NotificationTemplates => Set<NotificationTemplate>();
|
|
|
|
|
public DbSet<UserNotificationConfig> UserNotificationConfigs => Set<UserNotificationConfig>();
|
|
|
|
|
|
2026-07-21 08:57:53 +00:00
|
|
|
// Security entities
|
|
|
|
|
public DbSet<RevokedRefreshToken> RevokedRefreshTokens => Set<RevokedRefreshToken>();
|
|
|
|
|
|
2026-07-19 15:28:38 +00:00
|
|
|
// Person entities
|
|
|
|
|
public DbSet<Person> Persons => Set<Person>();
|
|
|
|
|
public DbSet<KnownFace> KnownFaces => Set<KnownFace>();
|
2026-07-18 21:15:05 +00:00
|
|
|
|
2026-08-11 21:35:52 +02:00
|
|
|
// 2FA recovery codes (stored hashed)
|
|
|
|
|
public DbSet<UserRecoveryCode> UserRecoveryCodes => Set<UserRecoveryCode>();
|
|
|
|
|
|
2026-08-30 09:48:47 +02:00
|
|
|
// Identity tables (for synchronous admin checks in IQueryable filters)
|
|
|
|
|
public new DbSet<AppRole> Roles => Set<AppRole>();
|
|
|
|
|
|
|
|
|
|
// Suppress CS0114 — base IdentityDbContext.UserRoles is virtual but we need
|
|
|
|
|
// the specific DbSet<IdentityUserRole<Guid>> type exposed through IApplicationDbContext.
|
|
|
|
|
public new DbSet<Microsoft.AspNetCore.Identity.IdentityUserRole<Guid>> UserRoles
|
|
|
|
|
=> Set<Microsoft.AspNetCore.Identity.IdentityUserRole<Guid>>();
|
|
|
|
|
|
2026-08-11 21:42:46 +02:00
|
|
|
// Domain métier (spec 2.1)
|
|
|
|
|
public DbSet<Vehicle> Vehicles => Set<Vehicle>();
|
|
|
|
|
public DbSet<Recording> Recordings => Set<Recording>();
|
|
|
|
|
public DbSet<LicensePlate> LicensePlates => Set<LicensePlate>();
|
|
|
|
|
public DbSet<StoragePolicy> StoragePolicies => Set<StoragePolicy>();
|
2026-10-24 17:04:57 +02:00
|
|
|
public DbSet<StorageDestination> StorageDestinations => Set<StorageDestination>();
|
2026-08-11 21:42:46 +02:00
|
|
|
|
2026-08-26 23:44:38 +02:00
|
|
|
// Analysis job scheduling
|
|
|
|
|
public DbSet<AnalysisJob> AnalysisJobs => Set<AnalysisJob>();
|
|
|
|
|
|
2026-10-10 19:47:09 +02:00
|
|
|
public DbSet<TEntity> GetSet<TEntity>() where TEntity : class => Set<TEntity>();
|
|
|
|
|
|
2026-07-22 19:43:13 +00:00
|
|
|
public async Task SaveChangesWithRetryAsync(int maxRetries = 3, CancellationToken ct = default)
|
|
|
|
|
{
|
2026-07-27 18:59:12 +00:00
|
|
|
await DbContextExtensions.SaveChangesWithRetryAsync(this, maxRetries, ct).ConfigureAwait(false);
|
2026-07-22 19:43:13 +00:00
|
|
|
}
|
|
|
|
|
|
2026-10-20 02:26:49 +02:00
|
|
|
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
|
|
|
|
ChangeTracker.DetectChanges();
|
2026-10-20 07:27:31 +02:00
|
|
|
// Keep history consistent for direct camera writes (including discovery).
|
|
|
|
|
var changedCameras = ChangeTracker.Entries<Camera>()
|
|
|
|
|
.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"));
|
|
|
|
|
}
|
2026-10-20 02:26:49 +02:00
|
|
|
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);
|
2026-10-20 20:57:16 +02:00
|
|
|
if (invalidate)
|
2026-10-20 02:26:49 +02:00
|
|
|
{
|
2026-10-20 20:57:16 +02:00
|
|
|
// 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);
|
|
|
|
|
}
|
2026-10-20 02:26:49 +02:00
|
|
|
}
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
protected override void OnModelCreating(ModelBuilder builder)
|
|
|
|
|
{
|
|
|
|
|
base.OnModelCreating(builder);
|
|
|
|
|
|
|
|
|
|
builder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
|
|
|
|
|
|
2026-07-18 20:31:37 +00:00
|
|
|
// Global soft-delete filter — principal entities
|
2026-07-16 20:53:56 +00:00
|
|
|
builder.Entity<Site>().HasQueryFilter(e => !e.IsDeleted);
|
|
|
|
|
builder.Entity<Agent>().HasQueryFilter(e => !e.IsDeleted);
|
|
|
|
|
builder.Entity<Camera>().HasQueryFilter(e => !e.IsDeleted);
|
2026-07-18 20:31:37 +00:00
|
|
|
|
|
|
|
|
// 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<AgentSetting>().HasQueryFilter(e => e.Agent == null || !e.Agent.IsDeleted);
|
|
|
|
|
builder.Entity<CameraCredentials>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
|
|
|
|
|
builder.Entity<CameraDetectionProfile>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
|
|
|
|
|
builder.Entity<UserSite>().HasQueryFilter(e => e.Site == null || !e.Site.IsDeleted);
|
2026-08-27 20:28:41 +02:00
|
|
|
builder.Entity<UserCamera>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
|
2026-07-19 06:49:17 +00:00
|
|
|
|
2026-07-20 14:02:07 +00:00
|
|
|
// 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<CameraAssignment>().HasQueryFilter(e => e.Agent == null || !e.Agent.IsDeleted);
|
|
|
|
|
builder.Entity<CameraDiscoveryResult>().HasQueryFilter(e => e.Site == null || !e.Site.IsDeleted);
|
|
|
|
|
builder.Entity<CameraEvent>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
|
2026-07-20 19:58:32 +00:00
|
|
|
builder.Entity<DiscoveredStreamUrl>().HasQueryFilter(e => e.DiscoveryResult == null || e.DiscoveryResult.Site == null || !e.DiscoveryResult.Site.IsDeleted);
|
2026-08-26 23:44:38 +02:00
|
|
|
builder.Entity<AnalysisJob>().HasQueryFilter(e => e.Camera == null || !e.Camera.IsDeleted);
|
2026-07-20 14:02:07 +00:00
|
|
|
|
2026-07-19 06:49:17 +00:00
|
|
|
// Group soft-delete filters
|
|
|
|
|
builder.Entity<Group>().HasQueryFilter(e => !e.IsDeleted);
|
|
|
|
|
builder.Entity<UserGroup>().HasQueryFilter(e => e.Group == null || !e.Group.IsDeleted);
|
2026-07-16 20:53:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
|
|
|
|
{
|
2026-07-18 20:05:22 +00:00
|
|
|
optionsBuilder.AddInterceptors(
|
2026-07-20 09:50:43 +00:00
|
|
|
_auditInterceptor);
|
2026-07-16 20:53:56 +00:00
|
|
|
|
2026-07-18 20:31:37 +00:00
|
|
|
// 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.
|
2026-09-01 10:18:43 +02:00
|
|
|
// Also suppress PendingModelChangesWarning because matching query filters
|
|
|
|
|
// (used for soft-delete) cause this warning to be promoted to an exception.
|
2026-07-18 20:31:37 +00:00
|
|
|
optionsBuilder.ConfigureWarnings(warnings =>
|
|
|
|
|
{
|
|
|
|
|
warnings.Ignore(CoreEventId.RedundantIndexRemoved);
|
2026-10-10 18:45:58 +02:00
|
|
|
warnings.Ignore(RelationalEventId.PendingModelChangesWarning);
|
2026-07-18 20:31:37 +00:00
|
|
|
});
|
|
|
|
|
|
2026-07-16 20:53:56 +00:00
|
|
|
base.OnConfiguring(optionsBuilder);
|
|
|
|
|
}
|
|
|
|
|
}
|