Files
openwaf/dotnet/OpenWaf.Infrastructure/Persistence/ObservationWriter.cs
T
Pavlo Ratushnyi 3f24c5d31c A ban that could not be written was logged as a concurrency race, and nothing was in force
Measured on the shipped image with writes to block_entries aborted by SQLite
triggers while reads kept working: five refusals from one source at a threshold
of 3 answered 404 five times, no ban reached storage or /state, /readyz answered
200, and the log said "BlockStore: concurrent ban on 203.0.113.12; keeping the
winner" four times over an inner "SQLite Error 19: 'gate: ban write blocked'".
Enforcement reads the snapshot and the snapshot is built from storage, so a ban
that cannot be written is a ban that exists nowhere - and the only sentence the
log offered said the opposite.

BlockStore now asks storage which case it is: re-read the row. A live engine ban
for that source means somebody won the unique-index race and nothing is wrong;
no row, or a read that cannot run either, means the write never happened. The
second case is counted (DurabilityHealth.Bans), logged with its real reason and
its consequence, and gates /readyz - the enforcement path is the path that
gates.

That also moved the boundary drawn last cycle. Observations, alerts and retention
are reporting pillars: counted, shown on /state and on the console, and no longer
gating readiness. The measurement that forced it: with the gate in place, one
lost alert left alertWriteFailures at 3 and /readyz at 503; the triggers were
removed and the stand left idle for 120 s, and it answered 503 the whole time
with the write path healthy. An alert pillar writes only when an alert happens to
be raised, so "not yet proven healthy" had become "unready forever".

ObservationWriter now retries every tracked source while it has an outstanding
failure: the write-amplification bound protects against load, not against
retries, and without this the lost rows waited for each source to be due again a
full interval later.

Teeth: BanWriteFailureTests (3) - 3 failed / 0 passed before the fix; two
WriteFailureVisibilityTests assertions re-drawn for the new boundary. Gates:
compose-smoke 63 -> 72 (the ban scene asserts 404x5, no row in storage, 503
naming bans, race lines 0/0 and the honest line present, then the ban landing on
a later refusal), smoke.sh counters now include bans, console-check 57 -> 58.
2026-10-02 09:24:43 +02:00

149 lines
6.6 KiB
C#

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;
/// <summary>
/// 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 <c>ObservationWriteInterval</c> leaves this loop.
/// </summary>
public sealed class ObservationWriter : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly StreakTracker _tracker;
private readonly EdgePolicyProvider _policy;
private readonly DurabilityHealth _health;
private readonly ILogger<ObservationWriter> _log;
private readonly TimeSpan _flushInterval = TimeSpan.FromSeconds(15);
private readonly Dictionary<string, DateTimeOffset> _lastWrittenAt = new(StringComparer.Ordinal);
public ObservationWriter(
IServiceScopeFactory scopeFactory,
StreakTracker tracker,
EdgePolicyProvider policy,
DurabilityHealth health,
ILogger<ObservationWriter> 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<int> 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<StreakSnapshot>();
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<OpenWafDbContext>();
var keys = due.Select(d => d.SourceKey).ToList();
var existing = await db.Observations.Where(o => keys.Contains(o.SourceKey)).ToListAsync(ct);
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;
}
}
}