using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
///
/// Retention (Q8). The edge stores aggregates, not a request log, so the
/// privacy question the reference repo left open for SiteVisit — how
/// long a raw IP may sit in the database — has a bounded answer here: idle
/// observations and expired engine bans age out on a timer.
///
public sealed class RetentionWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly EdgePolicyProvider _policy;
private readonly DurabilityHealth _health;
private readonly ILogger _log;
private readonly TimeSpan _interval = TimeSpan.FromMinutes(30);
public RetentionWorker(IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, DurabilityHealth health, ILogger log)
{
_scopeFactory = scopeFactory;
_policy = policy;
_health = health;
_log = log;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try { await Task.Delay(_interval, stoppingToken); }
catch (TaskCanceledException) { return; }
try { await PruneAsync(CancellationToken.None); }
catch (Exception ex) { _log.LogWarning(ex, "RetentionWorker: prune failed."); }
}
}
internal async Task PruneAsync(CancellationToken ct)
{
var policy = _policy.Current;
var now = DateTimeOffset.UtcNow;
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
try
{
await db.Observations.Where(o => o.LastSeenAt < now - policy.ObservationRetention).ExecuteDeleteAsync(ct);
await db.Blocks
.Where(b => b.Source == BlockSource.Engine && b.ExpiresAt != null && b.ExpiresAt < now - policy.BanRetention)
.ExecuteDeleteAsync(ct);
await db.Alerts.Where(a => a.CreatedAt < now - policy.BanRetention).ExecuteDeleteAsync(ct);
_health.RecordSuccess(DurabilityHealth.Retention);
}
catch (Exception ex)
{
// The retention promise is a privacy promise: aggregates age out on
// purpose. A prune that fails and only logs leaves idle sources in
// the database longer than the README says they are kept, with no
// way for an operator to tell "nothing was due" from "this has not
// run in a week". Counted here and reported on /state; deliberately
// NOT a readiness failure — see Program.cs.
_health.RecordFailure(DurabilityHealth.Retention, ex);
throw;
}
}
}