Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/RetentionWorker.cs
T
Pavlo Ratushnyi 2b0163aa80 A pillar that could not write kept answering with the count it had before the break
The read side got its counters last cycle; the write side was still catching
everything, logging one line and keeping the process alive. A failed write is
worse than a failed read - the row never existed and no later request brings it
back - and the surface hid it better. Measured on the shipped image with SQLite
triggers aborting every INSERT/UPDATE on source_observations and edge_alerts
while reads kept working: three new sources refused and a six-request 5xx storm
later, GET /admin-api/observations answered 200 with the same X-Total-Count it
had before the break (46), GET /admin-api/alerts still showed its one row,
/healthz and /readyz were 200, /admin-api/state had no write-side field at all,
and the log carried "flush failed, 4 entries dropped" plus two "could not
persist".

DurabilityHealth counts each writer separately; /state reports
observationWriteFailures/observationsLost/observationLastWriteError,
alertWriteFailures/alertsLost and retentionPruneFailures; /readyz answers 503
naming the pillar, the rows lost and the innermost error rather than EF's
wrapper. A counter clears only on a successful write of its own pillar, and
retention is reported without being a readiness failure - stated in code, with
the reason.

Teeth: WriteFailureVisibilityTests (5) - 5 failed / 0 passed before the fix.
Gates: compose-smoke 53 -> 63 (blocks writes with triggers, asserts the
unchanged X-Total-Count as the lie, and heals per pillar), smoke.sh 25 -> 28,
console-check 53 -> 57.
2026-10-02 08:26:45 +02:00

72 lines
2.9 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
/// <summary>
/// Retention (Q8). The edge stores aggregates, not a request log, so the
/// privacy question the reference repo left open for <c>SiteVisit</c> — 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.
/// </summary>
public sealed class RetentionWorker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly EdgePolicyProvider _policy;
private readonly DurabilityHealth _health;
private readonly ILogger<RetentionWorker> _log;
private readonly TimeSpan _interval = TimeSpan.FromMinutes(30);
public RetentionWorker(IServiceScopeFactory scopeFactory, EdgePolicyProvider policy, DurabilityHealth health, ILogger<RetentionWorker> 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<OpenWafDbContext>();
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;
}
}
}