using OpenWaf.Domain.Policy;
namespace OpenWaf.Domain.Engine;
///
/// The volume counter (OPEN-56): how often one source asked, inside a window
/// that started when that source first asked.
///
/// This is the pillar the rest of the edge cannot give, because every other
/// one reads something that already happened — the status the origin answered,
/// the country the address sits in, a list a human wrote. A source that asks
/// for a cheap path two hundred times a minute produces no refusal, so no
/// streak matures and the origin serves all two hundred. The only signal is the
/// count itself, and a count has to be kept somewhere while the requests are
/// arriving. That is what this is: the one piece of live state on the request
/// path, next to the snapshot the other pillars read.
///
/// Two protections, both copied from because they
/// are the same problem:
/// * Bounded memory. At most
/// sources are held, least-recently-touched evicted first, idle sources aged
/// out. A scanner farm with a fresh address per request cannot grow the
/// process.
/// * No I/O. The counters are in this process. The consequence is
/// stated in the README rather than hidden: the budget is per edge, so N
/// edges behind a load balancer allow N times the budget. The ban a breach
/// writes is shared, so the stop is the fleet's even when the counting is
/// not.
///
/// A fixed window, not a sliding one. A sliding counter needs one entry per
/// request, which is a map that grows at attack rate — the exact shape this
/// class exists to avoid. The cost of a fixed window is the documented edge
/// case: a source can spend the whole budget at the end of one window and the
/// whole budget again at the start of the next, so the worst sustained rate is
/// twice the limit across one boundary. A limit of 100/60s can therefore let
/// 200 through in 60 seconds straddling the seam. Accepted, and named, because
/// the alternative is unbounded memory.
///
public sealed class RateTracker
{
private readonly object _gate = new();
private readonly Dictionary _states = new(StringComparer.Ordinal);
private readonly LinkedList _lru = new();
// Read from the policy once per configuration change so the hot path never
// dereferences the policy record for a bound. Same trick, same reason as
// StreakTracker.MaxCap.
private int _maxCap = 10_000;
public void Configure(EdgePolicy policy) => _maxCap = Math.Max(1, policy.MaxTrackedSources);
///
/// Count one request and say what the budget now thinks of this source.
///
public RateObservation Record(string sourceKey, EdgePolicy policy, DateTimeOffset now)
{
if (string.IsNullOrEmpty(sourceKey))
return new RateObservation(0, false, now, now, false);
var window = policy.RateWindow > TimeSpan.Zero ? policy.RateWindow : TimeSpan.FromMinutes(1);
var limit = policy.RateLimitPerWindow;
lock (_gate)
{
var state = GetOrCreate(sourceKey, now);
Touch(state);
state.LastSeenAt = now;
// The window starts at this source's first request, not on a global
// clock. A global epoch would make every source that arrives just
// after the boundary share one short window, which turns the limit
// into a lottery on arrival time.
if (state.Count == 0 || now >= state.WindowStart + window)
{
state.WindowStart = now;
state.Count = 0;
}
state.Count++;
var end = state.WindowStart + window;
var over = limit > 0 && state.Count > limit;
return new RateObservation(
state.Count, over, state.WindowStart, end,
// Exactly one request per window gets to be the one that says
// so: the one that crossed. Everything after it in the same
// window is the same news, and an alert or a ban write per
// request is how a defence becomes a write-amplification bug.
BreachStarted: over && state.Count == limit + 1);
}
}
///
/// What is being counted right now, biggest first. A window that has
/// already run out is left out: it is about to restart at zero, and an
/// operator reading this is looking for the source that is over budget
/// now, not for a record of everyone who ever asked.
///
public IReadOnlyList LiveRates(
DateTimeOffset now, EdgePolicy policy, int limit, int offset, out int liveTotal)
=> LiveRates(now, policy, limit, offset, null, out liveTotal);
public IReadOnlyList LiveRates(
DateTimeOffset now, EdgePolicy policy, int limit, int offset, string? sourceKey,
out int liveTotal)
{
var take = Math.Max(1, limit);
var skip = Math.Max(0, offset);
var window = policy.RateWindow > TimeSpan.Zero ? policy.RateWindow : TimeSpan.FromMinutes(1);
lock (_gate)
{
EvictIdle(now, policy);
var list = new List();
foreach (var s in _states.Values)
{
if (sourceKey is not null
&& !string.Equals(s.SourceKey, sourceKey, StringComparison.Ordinal))
continue;
var end = s.WindowStart + window;
if (now >= end) continue;
list.Add(new LiveRate(s.SourceKey, s.Count, s.WindowStart, end,
policy.RateLimitPerWindow > 0 && s.Count > policy.RateLimitPerWindow));
}
// The total is the filtered set, so a page that shows one address
// cannot claim the whole map's counts — the rule every other listing
// in this project already learned.
liveTotal = list.Count;
return list
.OrderByDescending(x => x.Count)
.ThenByDescending(x => x.WindowStart)
.Skip(skip)
.Take(take)
.ToList();
}
}
public int TrackedCount
{
get { lock (_gate) return _states.Count; }
}
/// Stop counting one source — used when an operator clears it, and
/// by the tests that need a known-empty map.
public void Forget(string sourceKey)
{
lock (_gate)
{
if (_states.Remove(sourceKey, out var s)) RemoveNode(s);
}
}
public void Clear()
{
lock (_gate)
{
_states.Clear();
_lru.Clear();
}
}
private RateState GetOrCreate(string sourceKey, DateTimeOffset now)
{
if (_states.TryGetValue(sourceKey, out var existing)) return existing;
// Before insertion, so the cap is a cap and not a target the map
// drifts past.
while (_states.Count >= _maxCap) RemoveOldest();
var created = new RateState
{
SourceKey = sourceKey,
WindowStart = now,
Count = 0,
LastSeenAt = now
};
_states[sourceKey] = created;
created.LruNode = _lru.AddLast(sourceKey);
return created;
}
private void Touch(RateState state)
{
if (state.LruNode is null) return;
_lru.Remove(state.LruNode);
state.LruNode = _lru.AddLast(state.SourceKey);
}
private void RemoveOldest()
{
var oldest = _lru.First;
if (oldest is null) return;
_lru.RemoveFirst();
_states.Remove(oldest.Value);
}
private void RemoveNode(RateState s)
{
if (s.LruNode is not null)
{
_lru.Remove(s.LruNode);
s.LruNode = null;
}
}
private void EvictIdle(DateTimeOffset now, EdgePolicy policy)
{
if (_states.Count == 0) return;
List? stale = null;
foreach (var kv in _states)
{
if (now - kv.Value.LastSeenAt > policy.StateIdleTtl)
{
stale ??= [];
stale.Add(kv.Key);
}
}
if (stale is null) return;
foreach (var key in stale)
{
if (_states.Remove(key, out var s)) RemoveNode(s);
}
}
}
internal sealed class RateState
{
public required string SourceKey { get; init; }
public DateTimeOffset WindowStart { get; set; }
public int Count { get; set; }
public DateTimeOffset LastSeenAt { get; set; }
public LinkedListNode? LruNode { get; set; }
}
/// What one counted request says about its source's budget.
public sealed record RateObservation(
int Count,
bool OverBudget,
DateTimeOffset WindowStart,
DateTimeOffset WindowEnd,
/// True on exactly the request that crossed the budget in this
/// window — the one allowed to raise the alert and write the ban.
bool BreachStarted);
/// One source's live window, as the operator reads it.
public sealed record LiveRate(
string SourceKey,
int Count,
DateTimeOffset WindowStart,
DateTimeOffset WindowEnd,
bool OverBudget);