diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs index bac7a57..e22d35f 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs @@ -42,6 +42,7 @@ public static class DependencyInjection 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 3da8498..723fde6 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -26,5 +26,10 @@ public static class JobSetup "weekly-digest", job => job.ExecuteAsync(CancellationToken.None), "0 8 * * 1"); // Monday at 8:00 + + manager.AddOrUpdate( + "agent-log-cleanup", + job => job.ExecuteAsync(CancellationToken.None), + "0 4 * * *"); // Daily at 4:00 — purge logs > retention (7 j par défaut) } } diff --git a/src/Heimdall.Infrastructure/Jobs/AgentLogCleanupJob.cs b/src/Heimdall.Infrastructure/Jobs/AgentLogCleanupJob.cs new file mode 100644 index 0000000..d675e14 --- /dev/null +++ b/src/Heimdall.Infrastructure/Jobs/AgentLogCleanupJob.cs @@ -0,0 +1,70 @@ +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); + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/AgentLogCleanupJobTests.cs b/tests/Heimdall.Infrastructure.Tests/AgentLogCleanupJobTests.cs new file mode 100644 index 0000000..0fd07f4 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/AgentLogCleanupJobTests.cs @@ -0,0 +1,113 @@ +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.Configuration; +using Microsoft.Extensions.Logging; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests; + +public class AgentLogCleanupJobTests : IDisposable +{ + private readonly SqliteConnection _connection; + private readonly TestDbContextFactory _dbFactory; + private readonly ILogger _logger = Substitute.For>(); + + public AgentLogCleanupJobTests() + { + _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 SeedAgentAsync() + { + await using var db = await _dbFactory.CreateDbContextAsync(); + var site = new Site("Site A"); + db.Sites.Add(site); + await db.SaveChangesAsync(); + var agent = new Agent(site.Id, "Agent 1", "host1", "1.0.0"); + db.Agents.Add(agent); + await db.SaveChangesAsync(); + return agent.Id; + } + + private AgentLogCleanupJob CreateJob(int retentionDays = 7) + { + var config = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Logs:RetentionDays"] = retentionDays.ToString(System.Globalization.CultureInfo.InvariantCulture), + }) + .Build(); + return new AgentLogCleanupJob(_dbFactory, _logger, config); + } + + [Fact] + public async Task ExecuteAsync_DeletesOnlyOldEntries() + { + var agentId = await SeedAgentAsync(); + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + db.AgentLogEntries.Add(new AgentLogEntry(agentId, DateTime.UtcNow.AddDays(-30), AgentLogLevel.Warning, "old")); + db.AgentLogEntries.Add(new AgentLogEntry(agentId, DateTime.UtcNow.AddDays(-3), AgentLogLevel.Information, "recent")); + await db.SaveChangesAsync(); + } + + await CreateJob(retentionDays: 7).ExecuteAsync(CancellationToken.None); + + await using var verify = await _dbFactory.CreateDbContextAsync(); + var remaining = await verify.AgentLogEntries.ToListAsync(); + remaining.Count.ShouldBe(1); + remaining[0].Message.ShouldBe("recent"); + } + + [Fact] + public async Task ExecuteAsync_NoOldEntries_NothingDeleted() + { + var agentId = await SeedAgentAsync(); + await using (var db = await _dbFactory.CreateDbContextAsync()) + { + db.AgentLogEntries.Add(new AgentLogEntry(agentId, DateTime.UtcNow.AddHours(-1), AgentLogLevel.Information, "fresh")); + await db.SaveChangesAsync(); + } + + await CreateJob(retentionDays: 7).ExecuteAsync(CancellationToken.None); + + await using var verify = await _dbFactory.CreateDbContextAsync(); + (await verify.AgentLogEntries.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)); + } +}