using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenWaf.Domain.Engine;
using OpenWaf.Domain.Security;
namespace OpenWaf.Infrastructure.Persistence;
///
/// Persists the in-memory streak state on a timer. This is the write
/// amplification protection the reference repo already paid for: a scanner
/// hammering thousands of paths a second must not generate matching writes a
/// second, so the tracker stays in memory and at most one durable upsert per
/// source per ObservationWriteInterval leaves this loop.
///
public sealed class ObservationWriter : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly IStreakTracker _tracker;
private readonly EdgePolicyProvider _policy;
private readonly DurabilityHealth _health;
private readonly ILogger _log;
private readonly TimeSpan _flushInterval = TimeSpan.FromSeconds(15);
private readonly Dictionary _lastWrittenAt = new(StringComparer.Ordinal);
public ObservationWriter(
IServiceScopeFactory scopeFactory,
IStreakTracker tracker,
EdgePolicyProvider policy,
DurabilityHealth health,
ILogger log)
{
_scopeFactory = scopeFactory;
_tracker = tracker;
_policy = policy;
_health = health;
_log = log;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try { await Task.Delay(_flushInterval, stoppingToken); }
catch (TaskCanceledException) { return; }
await FlushAsync(stoppingToken);
}
await FlushAsync(CancellationToken.None);
}
internal async Task FlushAsync(CancellationToken ct)
{
var policy = _policy.Current;
var now = DateTimeOffset.UtcNow;
var snapshots = _tracker.Snapshot(now, policy);
if (snapshots.Count == 0) return 0;
// The write-amplification bound protects against load, not against
// retries. While this pillar has an outstanding failure, every flush
// re-attempts every tracked source: the rows the failed flush was
// carrying would otherwise be lost until each source happened to be due
// again a full interval later, and the counter would stop being a live
// signal. The flush rate is unchanged (one per 15 s) and the source count
// is already capped by the LRU bound on the map, so retrying cannot turn
// into write amplification.
var retrying = _health.Get(DurabilityHealth.Observations).Failures > 0;
var due = new List();
foreach (var s in snapshots)
{
if (!retrying
&& _lastWrittenAt.TryGetValue(s.SourceKey, out var last) && now - last < policy.ObservationWriteInterval)
continue;
due.Add(s);
_lastWrittenAt[s.SourceKey] = now;
}
if (_lastWrittenAt.Count > policy.MaxTrackedSources)
{
foreach (var key in _lastWrittenAt.Where(kv => now - kv.Value > policy.StateIdleTtl).Select(kv => kv.Key).ToList())
_lastWrittenAt.Remove(key);
}
if (due.Count == 0) return 0;
try
{
using var scope = _scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService();
var token = ct;
var keys = due.Select(d => d.SourceKey).ToList();
var existing = await db.Observations.Where(o => keys.Contains(o.SourceKey)).ToListAsync(token);
var byKey = existing.ToDictionary(o => o.SourceKey, StringComparer.Ordinal);
foreach (var s in due)
{
if (byKey.TryGetValue(s.SourceKey, out var row))
{
row.LastSeenAt = s.LastSeenAt;
row.MaxConsecutiveRefusals = Math.Max(row.MaxConsecutiveRefusals, s.MaxConsecutiveRefusals);
row.TotalRefusals = Math.Max(row.TotalRefusals, s.TotalRefusals);
row.TotalServerErrorStreak = Math.Max(row.TotalServerErrorStreak, s.MaxConsecutiveServerErrors);
row.LastStatusCode = s.LastStatusCode ?? row.LastStatusCode;
row.LastPath = s.LastPath ?? row.LastPath;
row.LastUserAgent = s.LastUserAgent ?? row.LastUserAgent;
row.LastCountryCode = s.LastCountryCode ?? row.LastCountryCode;
row.LastCity = s.LastCity ?? row.LastCity;
row.LastRegion = s.LastRegion ?? row.LastRegion;
}
else
{
db.Observations.Add(new SourceObservation
{
SourceKey = s.SourceKey,
FirstSeenAt = s.LastSeenAt,
LastSeenAt = s.LastSeenAt,
MaxConsecutiveRefusals = s.MaxConsecutiveRefusals,
TotalRefusals = s.TotalRefusals,
TotalServerErrorStreak = s.MaxConsecutiveServerErrors,
LastStatusCode = s.LastStatusCode,
LastPath = s.LastPath,
LastUserAgent = s.LastUserAgent,
LastCountryCode = s.LastCountryCode,
LastCity = s.LastCity,
LastRegion = s.LastRegion
});
}
}
await db.SaveChangesAsync(ct);
_health.RecordSuccess(DurabilityHealth.Observations, due.Count);
return due.Count;
}
catch (Exception ex)
{
// The writer must survive: losing observations is better than
// taking the host down over a transient database error. What it may
// not do is survive quietly. Measured on the shipped image with the
// write path aborted by SQLite triggers: three new sources never
// reached source_observations, /admin-api/observations kept
// answering 200 with the same X-Total-Count as before the break,
// /readyz said "ready", and the only trace was this log line. The
// rows are not recoverable later — the streak history the operator
// reasons about is simply missing them.
_health.RecordFailure(DurabilityHealth.Observations, ex, due.Count);
_log.LogWarning(ex, "ObservationWriter: flush failed, {Count} entries dropped.", due.Count);
return 0;
}
}
}