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:
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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user