feat(jobs): jobs Hangfire rétention/cleanup + dashboard admin (Fixes #8)

- RetentionCheckJob (quotidien 3h) : purge enregistrements expirés par
  StoragePolicy via ExecuteDelete (1 requête, pas de boucle), défaut 30 j
- CleanupUnknownFacesJob (dim 5h) : personnes 'unknown' > 30 j
- CleanupLicensePlatesJob (dim 6h) : plaques non associées > 30 j
- DatabaseMaintenanceJob (dim 7h) : VACUUM events + REINDEX (VACUUM FULL
  1er dimanche)
- Dashboard Hangfire /hangfire protégé AdminJobs (filtre custom)
- S3CleanupJob dépend du ticket #7 (stockage S3) — non inclus ici
- Tests : 2 (rétention avec/sans politique)
This commit is contained in:
Arnaud Dartois committed 2026-08-12 09:43:45 +02:00
1 parent 2ee12a39f8
commit e3d14eec04
9 files changed
+366

No files matched your search

@@ -43,6 +43,10 @@ public static class DependencyInjection
services.AddScoped<DailyDigestJob>();
services.AddScoped<WeeklyDigestJob>();
services.AddScoped<AgentLogCleanupJob>();
services.AddScoped<RetentionCheckJob>();
services.AddScoped<CleanupUnknownFacesJob>();
services.AddScoped<CleanupLicensePlatesJob>();
services.AddScoped<DatabaseMaintenanceJob>();
return services;
}
@@ -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<RetentionCheckJob>(
"retention-check",
job => job.ExecuteAsync(CancellationToken.None),
"0 3 * * *"); // Daily at 3:00
manager.AddOrUpdate<CleanupUnknownFacesJob>(
"cleanup-unknown-faces",
job => job.ExecuteAsync(CancellationToken.None),
"0 5 * * 0"); // Sunday at 5:00
manager.AddOrUpdate<CleanupLicensePlatesJob>(
"cleanup-license-plates",
job => job.ExecuteAsync(CancellationToken.None),
"0 6 * * 0"); // Sunday at 6:00
manager.AddOrUpdate<DatabaseMaintenanceJob>(
"database-maintenance",
job => job.ExecuteAsync(CancellationToken.None),
"0 7 * * 0"); // Sunday at 7:00
}
}
@@ -0,0 +1,36 @@
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// CleanupLicensePlatesJob — purge les plaques non associées à un véhicule
/// (VehicleId null) créées il y a plus de 30 jours. Cron : dimanche 6h.
/// </summary>
public class CleanupLicensePlatesJob
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<CleanupLicensePlatesJob> _logger;
public CleanupLicensePlatesJob(IDbContextFactory<AppDbContext> dbFactory, ILogger<CleanupLicensePlatesJob> 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);
}
}
@@ -0,0 +1,57 @@
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// 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.
/// </summary>
public class CleanupUnknownFacesJob
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<CleanupUnknownFacesJob> _logger;
public CleanupUnknownFacesJob(IDbContextFactory<AppDbContext> dbFactory, ILogger<CleanupUnknownFacesJob> 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);
}
}
@@ -0,0 +1,51 @@
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// DatabaseMaintenanceJob — maintenance PostgreSQL hebdomadaire :
/// VACUUM (events) + REINDEX DATABASE. VACUUM FULL mensuel (1er dimanche du
/// mois, REINDEX CONCURRENTLY). Cron : dimanche 7h.
/// </summary>
public class DatabaseMaintenanceJob
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<DatabaseMaintenanceJob> _logger;
public DatabaseMaintenanceJob(IDbContextFactory<AppDbContext> dbFactory, ILogger<DatabaseMaintenanceJob> 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)");
}
}
}
@@ -0,0 +1,51 @@
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// 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).
/// </summary>
public class RetentionCheckJob
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<RetentionCheckJob> _logger;
public RetentionCheckJob(IDbContextFactory<AppDbContext> dbFactory, ILogger<RetentionCheckJob> 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);
}
}
@@ -0,0 +1,25 @@
using Hangfire.Dashboard;
using Heimdall.Infrastructure.Security;
namespace Heimdall.Api;
/// <summary>
/// Hangfire dashboard authorization: allows only users satisfying the
/// AdminJobs permission (admin role claim). Anonymous and non-admin requests
/// are rejected.
/// </summary>
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");
}
}
+12
View File
@@ -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<App>().AddInteractiveServerRenderMode();
app.MapControllers();
app.MapHub<ConfigHub>("/hubs/config");
@@ -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<RetentionCheckJob> _logger = Substitute.For<ILogger<RetentionCheckJob>>();
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<AppDbContext>()
.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<AppDbContext> opts)
: IDbContextFactory<AppDbContext>
{
private static readonly AuditInterceptor Audit = new();
public AppDbContext CreateDbContext() => new(opts, Audit);
public Task<AppDbContext> CreateDbContextAsync(CancellationToken ct = default)
=> Task.FromResult(new AppDbContext(opts, Audit));
}
}