using Heimdall.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Jobs;
///
/// Purges agent log entries older than the retention window (default 7 days,
/// override Logs:RetentionDays or env Logs__RetentionDays).
/// Runs daily via Hangfire recurring job. Uses IDbContextFactory to avoid
/// sharing a DbContext across Hangfire worker threads.
///
public class AgentLogCleanupJob
{
private readonly IDbContextFactory _dbFactory;
private readonly ILogger _logger;
private readonly int _retentionDays;
public AgentLogCleanupJob(
IDbContextFactory dbFactory,
ILogger logger,
IConfiguration configuration)
{
_dbFactory = dbFactory;
_logger = logger;
_retentionDays = configuration.GetValue("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);
}
}