feat(logs): purge des logs agents — AgentLogCleanupJob Hangfire (Fixes #53)

- Job quotidien 4h : supprime les AgentLogEntry plus vieux que la rétention
  (Logs:RetentionDays, défaut 7 j), par lots de 5000 + pause 100 ms
  (pas de verrou long ni de transaction log explosée)
- Enregistré dans JobSetup + DI BackgroundJobs
- Tests : 2 (purge des vieux uniquement, rien si rien de vieux)
This commit is contained in:
Arnaud Dartois committed 2026-08-12 09:29:03 +02:00
1 parent 6383496ff9
commit 0c7bb86eae
4 files changed
+189

No files matched your search

@@ -42,6 +42,7 @@ public static class DependencyInjection
services.AddScoped<SendNotificationJob>();
services.AddScoped<DailyDigestJob>();
services.AddScoped<WeeklyDigestJob>();
services.AddScoped<AgentLogCleanupJob>();
return services;
}
@@ -26,5 +26,10 @@ public static class JobSetup
"weekly-digest",
job => job.ExecuteAsync(CancellationToken.None),
"0 8 * * 1"); // Monday at 8:00
manager.AddOrUpdate<AgentLogCleanupJob>(
"agent-log-cleanup",
job => job.ExecuteAsync(CancellationToken.None),
"0 4 * * *"); // Daily at 4:00 — purge logs > retention (7 j par défaut)
}
}
@@ -0,0 +1,70 @@
using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
/// <summary>
/// Purges agent log entries older than the retention window (default 7 days,
/// override <c>Logs:RetentionDays</c> or env <c>Logs__RetentionDays</c>).
/// Runs daily via Hangfire recurring job. Uses IDbContextFactory to avoid
/// sharing a DbContext across Hangfire worker threads.
/// </summary>
public class AgentLogCleanupJob
{
private readonly IDbContextFactory<AppDbContext> _dbFactory;
private readonly ILogger<AgentLogCleanupJob> _logger;
private readonly int _retentionDays;
public AgentLogCleanupJob(
IDbContextFactory<AppDbContext> dbFactory,
ILogger<AgentLogCleanupJob> logger,
IConfiguration configuration)
{
_dbFactory = dbFactory;
_logger = logger;
_retentionDays = configuration.GetValue<int?>("Logs:RetentionDays") ?? 7;
if (_retentionDays < 1)
_retentionDays = 7;
}
public async Task ExecuteAsync(CancellationToken ct)
{
await using var db = await _dbFactory.CreateDbContextAsync(ct);
var cutoff = DateTime.UtcNow.AddDays(-_retentionDays);
// Delete in bounded batches so a huge backlog does not lock the table
// for minutes or blow the transaction log.
var totalDeleted = 0;
while (true)
{
var batch = await db.AgentLogEntries
.Where(e => e.TimestampUtc < cutoff)
.OrderBy(e => e.TimestampUtc)
.Take(5000)
.Select(e => e.Id)
.ToListAsync(ct)
.ConfigureAwait(false);
if (batch.Count == 0)
break;
await db.AgentLogEntries
.Where(e => batch.Contains(e.Id))
.ExecuteDeleteAsync(ct)
.ConfigureAwait(false);
totalDeleted += batch.Count;
// Small pause between batches to avoid hammering the DB in a loop.
await Task.Delay(100, ct).ConfigureAwait(false);
}
if (totalDeleted > 0)
_logger.LogInformation(
"Agent log cleanup: deleted {Count} entries older than {RetentionDays} day(s)",
totalDeleted, _retentionDays);
}
}