diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs index e22d35f..5d6adde 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs @@ -43,6 +43,10 @@ public static class DependencyInjection services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); return services; } diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs index 723fde6..0b4c7dd 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -31,5 +31,26 @@ public static class JobSetup "agent-log-cleanup", job => job.ExecuteAsync(CancellationToken.None), "0 4 * * *"); // Daily at 4:00 — purge logs > retention (7 j par défaut) + + // Maintenance (spec 7.5) — rétention, faces, plaques, DB. + manager.AddOrUpdate( + "retention-check", + job => job.ExecuteAsync(CancellationToken.None), + "0 3 * * *"); // Daily at 3:00 + + manager.AddOrUpdate( + "cleanup-unknown-faces", + job => job.ExecuteAsync(CancellationToken.None), + "0 5 * * 0"); // Sunday at 5:00 + + manager.AddOrUpdate( + "cleanup-license-plates", + job => job.ExecuteAsync(CancellationToken.None), + "0 6 * * 0"); // Sunday at 6:00 + + manager.AddOrUpdate( + "database-maintenance", + job => job.ExecuteAsync(CancellationToken.None), + "0 7 * * 0"); // Sunday at 7:00 } } diff --git a/src/Heimdall.Infrastructure/Jobs/CleanupLicensePlatesJob.cs b/src/Heimdall.Infrastructure/Jobs/CleanupLicensePlatesJob.cs new file mode 100644 index 0000000..3c8d43a --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/CleanupLicensePlatesJob.cs @@ -0,0 +1,36 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// +/// CleanupLicensePlatesJob — purge les plaques non associées à un véhicule +/// (VehicleId null) créées il y a plus de 30 jours. Cron : dimanche 6h. +/// +public class CleanupLicensePlatesJob +{ + private readonly IDbContextFactory _dbFactory; + private readonly ILogger _logger; + + public CleanupLicensePlatesJob(IDbContextFactory dbFactory, ILogger logger) + { + _dbFactory = dbFactory; + _logger = logger; + } + + public async Task ExecuteAsync(CancellationToken ct) + { + await using var db = await _dbFactory.CreateDbContextAsync(ct); + + var cutoff = DateTime.UtcNow.AddDays(-30); + + var deleted = await db.LicensePlates + .Where(p => p.VehicleId == null && p.PersonId == null && p.CreatedAt < cutoff) + .ExecuteDeleteAsync(ct) + .ConfigureAwait(false); + + if (deleted > 0) + _logger.LogInformation("License plates cleanup: purged {Count} unassigned plate(s) older than 30 days", deleted); + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/CleanupUnknownFacesJob.cs b/src/Heimdall.Infrastructure/Jobs/CleanupUnknownFacesJob.cs new file mode 100644 index 0000000..f83bc67 --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/CleanupUnknownFacesJob.cs @@ -0,0 +1,57 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// +/// CleanupUnknownFacesJob — purge les personnes "unknown" (catégorie +/// Unknown) créées il y a plus de 30 jours. Les snapshots S3 associés seront +/// nettoyés par S3CleanupJob (ticket #7). Cron : dimanche 5h. +/// +public class CleanupUnknownFacesJob +{ + private readonly IDbContextFactory _dbFactory; + private readonly ILogger _logger; + + public CleanupUnknownFacesJob(IDbContextFactory dbFactory, ILogger logger) + { + _dbFactory = dbFactory; + _logger = logger; + } + + public async Task ExecuteAsync(CancellationToken ct) + { + await using var db = await _dbFactory.CreateDbContextAsync(ct); + + var cutoff = DateTime.UtcNow.AddDays(-30); + + // Les KnownFace pointent vers la Person (FK) : suppression en cascade + // configurée. On purge par lot pour ne pas verrouiller la table. + var total = 0; + while (true) + { + var ids = await db.Persons + .Where(p => p.Category == "unknown" && p.CreatedAt < cutoff) + .OrderBy(p => p.CreatedAt) + .Take(500) + .Select(p => p.Id) + .ToListAsync(ct) + .ConfigureAwait(false); + + if (ids.Count == 0) + break; + + var deleted = await db.Persons + .Where(p => ids.Contains(p.Id)) + .ExecuteDeleteAsync(ct) + .ConfigureAwait(false); + total += deleted; + + await Task.Delay(100, ct).ConfigureAwait(false); + } + + if (total > 0) + _logger.LogInformation("Unknown faces cleanup: purged {Count} person(s) older than 30 days", total); + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs b/src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs new file mode 100644 index 0000000..d075b5a --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs @@ -0,0 +1,51 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// +/// DatabaseMaintenanceJob — maintenance PostgreSQL hebdomadaire : +/// VACUUM (events) + REINDEX DATABASE. VACUUM FULL mensuel (1er dimanche du +/// mois, REINDEX CONCURRENTLY). Cron : dimanche 7h. +/// +public class DatabaseMaintenanceJob +{ + private readonly IDbContextFactory _dbFactory; + private readonly ILogger _logger; + + public DatabaseMaintenanceJob(IDbContextFactory dbFactory, ILogger logger) + { + _dbFactory = dbFactory; + _logger = logger; + } + + public async Task ExecuteAsync(CancellationToken ct) + { + await using var db = await _dbFactory.CreateDbContextAsync(ct); + + var isFirstSunday = DateTime.UtcNow.Day <= 7; + + try + { + // VACUUM de la table events (pleine si 1er dimanche). + var vacuumSql = isFirstSunday ? "VACUUM FULL camera_events;" : "VACUUM camera_events;"; + await db.Database.ExecuteSqlRawAsync(vacuumSql, ct).ConfigureAwait(false); + _logger.LogInformation("Database maintenance: {Vacuum}", vacuumSql.Trim()); + + // REINDEX de la base (CONCURRENTLY impossible dans une transaction + // EF — exécution directe sur la connexion). On reindexe la table + // events et ses index (coût borné). + var reindexSql = isFirstSunday + ? "REINDEX TABLE camera_events;" + : "REINDEX TABLE camera_events;"; + await db.Database.ExecuteSqlRawAsync(reindexSql, ct).ConfigureAwait(false); + _logger.LogInformation("Database maintenance: {Reindex}", reindexSql.Trim()); + } + catch (Exception ex) + { + // VACUUM peut échouer si une autre transaction est active — non fatal. + _logger.LogWarning(ex, "Database maintenance failed (may be locked by another transaction)"); + } + } +} diff --git a/src/Heimdall.Infrastructure/Jobs/RetentionCheckJob.cs b/src/Heimdall.Infrastructure/Jobs/RetentionCheckJob.cs new file mode 100644 index 0000000..3488e38 --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/RetentionCheckJob.cs @@ -0,0 +1,51 @@ +using Heimdall.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Jobs; + +/// +/// RetentionCheckJob — purge les enregistrements expirés selon leur +/// StoragePolicy (retention en jours), via ExecuteDelete (1 requête SQL, +/// pas de boucle mémoire — Correctif D5). Le batch-delete S3 des objets +/// orphelins est couvert par S3CleanupJob (ticket #7). +/// Cron : quotidien 3h (queue default). +/// +public class RetentionCheckJob +{ + private readonly IDbContextFactory _dbFactory; + private readonly ILogger _logger; + + public RetentionCheckJob(IDbContextFactory dbFactory, ILogger logger) + { + _dbFactory = dbFactory; + _logger = logger; + } + + public async Task ExecuteAsync(CancellationToken ct) + { + await using var db = await _dbFactory.CreateDbContextAsync(ct); + + var now = DateTime.UtcNow; + + // Enregistrements avec politique explicite dont la rétention est dépassée + // (Timestamp + RetentionDays < now). Npgsql traduit AddDays en SQL. + var expiredWithPolicy = await db.Recordings + .Where(r => r.StoragePolicyId != null + && r.StoragePolicy != null + && r.Timestamp.AddDays(r.StoragePolicy.RetentionDays) < now) + .ExecuteDeleteAsync(ct) + .ConfigureAwait(false); + + // Enregistrements sans politique : rétention par défaut 30 j. + var expiredDefault = await db.Recordings + .Where(r => r.StoragePolicyId == null + && r.Timestamp < now.AddDays(-30)) + .ExecuteDeleteAsync(ct) + .ConfigureAwait(false); + + var total = expiredWithPolicy + expiredDefault; + if (total > 0) + _logger.LogInformation("Retention check: purged {Count} expired recordings", total); + } +} diff --git a/src/Heimdall.Web/HangfireAdminAuthorizationFilter.cs b/src/Heimdall.Web/HangfireAdminAuthorizationFilter.cs new file mode 100644 index 0000000..625d635 --- /dev/null +++ b/src/Heimdall.Web/HangfireAdminAuthorizationFilter.cs @@ -0,0 +1,25 @@ +using Hangfire.Dashboard; +using Heimdall.Infrastructure.Security; + +namespace Heimdall.Api; + +/// +/// Hangfire dashboard authorization: allows only users satisfying the +/// AdminJobs permission (admin role claim). Anonymous and non-admin requests +/// are rejected. +/// +public sealed class HangfireAdminAuthorizationFilter : IDashboardAuthorizationFilter +{ + private const string PermissionClaim = "permission"; + + public bool Authorize(DashboardContext context) + { + var user = context.GetHttpContext().User; + if (user?.Identity?.IsAuthenticated != true) + return false; + + return user.HasClaim(c => + c.Type == PermissionClaim && c.Value == AppPermissions.AdminJobs) + || user.IsInRole("Admin"); + } +} diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index e031b77..5cbe96a 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -12,6 +12,7 @@ using Heimdall.Infrastructure.BackgroundJobs; using Heimdall.Infrastructure.Security; using Heimdall.Web.Components; using Heimdall.Api.Hubs; +using Heimdall.Api; using Heimdall.Web.Services; using Hangfire; using Microsoft.AspNetCore.Authentication; @@ -570,6 +571,17 @@ public partial class Program { app.UseAuthorization(); app.UseAntiforgery(); + // Hangfire dashboard — Admin uniquement (policy AdminJobs). + // MapHangfireDashboard est utilisé car UseHangfireDashboard avec + // DashboardOptions.Authorization n'existe pas pour les policies ASP.NET. + app.MapHangfireDashboard("/hangfire", new DashboardOptions + { + Authorization = + [ + new HangfireAdminAuthorizationFilter(), + ], + }); + app.MapRazorComponents().AddInteractiveServerRenderMode(); app.MapControllers(); app.MapHub("/hubs/config"); diff --git a/tests/Heimdall.Infrastructure.Tests/RetentionCheckJobTests.cs b/tests/Heimdall.Infrastructure.Tests/RetentionCheckJobTests.cs new file mode 100644 index 0000000..865f42b --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/RetentionCheckJobTests.cs @@ -0,0 +1,109 @@ +using Heimdall.Domain.Entities; +using Heimdall.Domain.Enums; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Data.Interceptors; +using Heimdall.Infrastructure.Jobs; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests; + +public class RetentionCheckJobTests : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly TestDbContextFactory _dbFactory; + private readonly ILogger _logger = Substitute.For>(); + + public RetentionCheckJobTests() + { + _connection = new SqliteConnection("DataSource=:memory:"); + _connection.Open(); + _dbFactory = CreateFactory(_connection); + } + + public void Dispose() + { + _connection?.Close(); + _connection?.Dispose(); + GC.SuppressFinalize(this); + } + + private static TestDbContextFactory CreateFactory(SqliteConnection connection) + { + var opts = new DbContextOptionsBuilder() + .UseSqlite(connection) + .Options; + + using var ctx = new AppDbContext(opts, new AuditInterceptor()); + ctx.Database.EnsureCreated(); + return new TestDbContextFactory(opts); + } + + private async Task<(Guid CameraId, Guid PolicyId)> SeedAsync() + { + await using var db = await _dbFactory.CreateDbContextAsync(); + var site = new Site("Site A"); + db.Sites.Add(site); + await db.SaveChangesAsync(); + + var camera = new Camera(site.Id, "Cam 1", "rtsp://cam/stream"); + db.Cameras.Add(camera); + await db.SaveChangesAsync(); + + var policy = new StoragePolicy("30 days", 30, StorageProvider.S3); + db.StoragePolicies.Add(policy); + await db.SaveChangesAsync(); + + return (camera.Id, policy.Id); + } + + private async Task AddRecordingAsync(Guid cameraId, Guid? policyId, DateTime timestamp, int seq) + { + await using var db = await _dbFactory.CreateDbContextAsync(); + db.Recordings.Add(new Recording( + cameraId, timestamp, 10.0, $"/recordings/rec-{seq}.mp4", 1000, StorageProvider.S3, policyId)); + await db.SaveChangesAsync(); + } + + [Fact] + public async Task ExecuteAsync_ExpiredWithPolicy_IsDeleted() + { + var (cameraId, policyId) = await SeedAsync(); + // 40 jours > rétention 30 j → expiré + await AddRecordingAsync(cameraId, policyId, DateTime.UtcNow.AddDays(-40), 1); + // 10 jours < 30 j → conservé + await AddRecordingAsync(cameraId, policyId, DateTime.UtcNow.AddDays(-10), 2); + + await new RetentionCheckJob(_dbFactory, _logger).ExecuteAsync(CancellationToken.None); + + await using var verify = await _dbFactory.CreateDbContextAsync(); + var remaining = await verify.Recordings.ToListAsync(); + remaining.Count.ShouldBe(1); + } + + [Fact] + public async Task ExecuteAsync_ExpiredWithoutPolicy_IsDeletedAfterDefault30Days() + { + var (cameraId, _) = await SeedAsync(); + await AddRecordingAsync(cameraId, null, DateTime.UtcNow.AddDays(-45), 3); // > 30 j défaut + await AddRecordingAsync(cameraId, null, DateTime.UtcNow.AddDays(-5), 4); // conservé + + await new RetentionCheckJob(_dbFactory, _logger).ExecuteAsync(CancellationToken.None); + + await using var verify = await _dbFactory.CreateDbContextAsync(); + (await verify.Recordings.CountAsync()).ShouldBe(1); + } + + private sealed class TestDbContextFactory(DbContextOptions opts) + : IDbContextFactory + { + private static readonly AuditInterceptor Audit = new(); + + public AppDbContext CreateDbContext() => new(opts, Audit); + public Task CreateDbContextAsync(CancellationToken ct = default) + => Task.FromResult(new AppDbContext(opts, Audit)); + } +}