Vote budgets: at the cap a new key evicts the least recently used key with permits left
Ruling budget-table-evict-oldest. FixedWindowBudget keeps two linked lists (window start, last use among keys with permits left) so eviction and expiry are O(1); a spent key is never evicted, and a table full of spent keys refuses a new key as TableFull with the true wait. Accounts get their own cast table. The vote page checks the subject before spending any key, and the refusal names its reason: cast budget, mint budget, or a busy table. Not verified by a build yet at this commit. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8f57dc89f0
commit
436a02864f
6 changed files with 374 additions and 96 deletions
|
|
@ -36,9 +36,10 @@ public sealed class ConceptVoteOptions
|
|||
|
||||
public TimeSpan MintWindow { get; init; } = TimeSpan.FromHours(1);
|
||||
|
||||
// The most partitions each budget holds at once. At the cap a partition not yet held is refused with a 429 until
|
||||
// the oldest window ends; held partitions are never evicted, so a rotating caller cannot escape a spent budget.
|
||||
// 100000 partitions is a few tens of MB; a real audience is far below it.
|
||||
// The most partitions each budget table holds at once (cast by account, cast by network prefix, mint). At the cap a
|
||||
// partition not yet held evicts the least recently used one that still has permits left; a partition that has
|
||||
// spent its permits is never evicted, so rotating sources can at most win back a forgotten partition's partial
|
||||
// budget. 100000 partitions is a few tens of MB; a real audience is far below it.
|
||||
public int MaxTrackedKeys { get; init; } = 100_000;
|
||||
|
||||
// The origins whose pages may read the public tally export from a browser (CORS). Each entry is exactly
|
||||
|
|
|
|||
|
|
@ -6,23 +6,24 @@ using Microsoft.Extensions.Options;
|
|||
namespace Bifrost.Web.Features.ConceptVotes;
|
||||
|
||||
// The one owner of the vote budgets. Cast is spent by every cast and retract; mint is spent additionally by a cast that
|
||||
// is about to mint a device cookie. A denial returns how long to wait and writes nothing. The partition is the account
|
||||
// when the voter is signed in, otherwise the network prefix (NetworkPrefix.Of) of the address the forwarded-headers
|
||||
// middleware left on the connection. No header and no client input ever becomes a key.
|
||||
// is about to mint a device cookie. A denial says why and how long to wait, and writes nothing. The partition is the
|
||||
// account when the voter is signed in, otherwise the network prefix (NetworkPrefix.Of) of the address the
|
||||
// forwarded-headers middleware left on the connection. No header and no client input ever becomes a key. Accounts
|
||||
// have a table of their own, so a flood of anonymous sources cannot crowd a signed-in voter out of it.
|
||||
public sealed class ConceptVoteRateLimits(IOptions<ConceptVoteOptions> options, TimeProvider clock)
|
||||
{
|
||||
private readonly ConceptVoteOptions opts = options.Value;
|
||||
private readonly FixedWindowBudget cast = new(options.Value.CastPermits, options.Value.CastWindow, options.Value.MaxTrackedKeys, clock);
|
||||
private readonly FixedWindowBudget castAccounts = new(options.Value.CastPermits, options.Value.CastWindow, options.Value.MaxTrackedKeys, clock);
|
||||
private readonly FixedWindowBudget castNetworks = new(options.Value.CastPermits, options.Value.CastWindow, options.Value.MaxTrackedKeys, clock);
|
||||
private readonly FixedWindowBudget mint = new(options.Value.MintPermits, options.Value.MintWindow, options.Value.MaxTrackedKeys, clock);
|
||||
|
||||
public TimeSpan? DenyCast(IPAddress? client, VoterIdentity? known) =>
|
||||
cast.TryAcquire(known?.UserAccountId is { } account ? "account:" + account.ToString("N") : NetKey(client), out var wait)
|
||||
? null
|
||||
: wait;
|
||||
public BudgetDenial? DenyCast(IPAddress? client, VoterIdentity? known) =>
|
||||
known?.UserAccountId is { } account
|
||||
? castAccounts.Spend(account.ToString("N"))
|
||||
: castNetworks.Spend(NetKey(client));
|
||||
|
||||
public TimeSpan? DenyMint(IPAddress? client) =>
|
||||
mint.TryAcquire(NetKey(client), out var wait) ? null : wait;
|
||||
public BudgetDenial? DenyMint(IPAddress? client) => mint.Spend(NetKey(client));
|
||||
|
||||
private string NetKey(IPAddress? client) =>
|
||||
"net:" + (client is null ? "unknown" : NetworkPrefix.Of(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength));
|
||||
client is null ? "unknown" : NetworkPrefix.Of(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,18 @@
|
|||
namespace Bifrost.Web.Features.Shared;
|
||||
|
||||
// Why a permit was refused and how long until the answer can change. TableFull is not the caller's own spending: the
|
||||
// table holds only spent windows and has no room for a key it does not know.
|
||||
public readonly record struct BudgetDenial(TimeSpan RetryAfter, bool TableFull);
|
||||
|
||||
// The one rate-limit mechanism: a fixed-window permit budget per caller-chosen partition key, timed on the injected
|
||||
// clock's monotonic timestamps (never its wall time, which can step), so a clock adjustment cannot stretch or reset a
|
||||
// window. Windows all have one length, so they end in the order they began: a queue of window starts expires them from
|
||||
// the front and the table never holds a key past its window. The table holds at most maxKeys keys; a new key arriving
|
||||
// at the cap is denied until the oldest window ends, with the true wait, so a rotating caller cannot evict a spent key
|
||||
// to escape its budget and the refusal is a 429 that says when to retry, never a silent drop.
|
||||
// window. Windows all have one length, so they end in the order they began: a list of entries in start order expires
|
||||
// them from the front and the table never holds a key past its window.
|
||||
// The table holds at most maxKeys keys. A new key arriving at the cap evicts the least recently used key that still
|
||||
// has permits left (nginx limit_req_zone does the same); a key that has spent all its permits is never evicted, so a
|
||||
// rotating caller can at most win back a forgotten key's partial budget and never a spent one, and nobody fresh is
|
||||
// refused because the table is full. Only when every held key is spent is a new key refused, with the true wait.
|
||||
// Every step is O(1): two linked lists, one by window start and one by last use among keys with permits left.
|
||||
// System.Threading.RateLimiting is not used because its limiters time themselves on Stopwatch and timers, which a
|
||||
// test cannot move.
|
||||
public sealed class FixedWindowBudget
|
||||
|
|
@ -16,7 +23,8 @@ public sealed class FixedWindowBudget
|
|||
private readonly TimeProvider clock;
|
||||
private readonly long origin;
|
||||
private readonly Dictionary<string, Entry> entries = new(StringComparer.Ordinal);
|
||||
private readonly Queue<string> byStart = new();
|
||||
private readonly LinkedList<Entry> byStart = new();
|
||||
private readonly LinkedList<Entry> byUse = new();
|
||||
private readonly object gate = new();
|
||||
|
||||
public FixedWindowBudget(int permits, TimeSpan window, int maxKeys, TimeProvider clock)
|
||||
|
|
@ -43,48 +51,81 @@ public sealed class FixedWindowBudget
|
|||
}
|
||||
}
|
||||
|
||||
// Takes one permit for the key. When none is left, or the table is full and the key is new, returns false and how
|
||||
// long until a window ends and the answer can change.
|
||||
public bool TryAcquire(string key, out TimeSpan retryAfter)
|
||||
// Takes one permit for the key and returns null, or returns why it could not.
|
||||
public BudgetDenial? Spend(string key)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var now = clock.GetElapsedTime(origin);
|
||||
while (byStart.TryPeek(out var oldest) && entries[oldest].Start + window <= now)
|
||||
while (byStart.First is { Value: var oldest } && oldest.Start + window <= now)
|
||||
{
|
||||
entries.Remove(byStart.Dequeue());
|
||||
Remove(oldest);
|
||||
}
|
||||
|
||||
if (entries.TryGetValue(key, out var entry))
|
||||
{
|
||||
if (entry.Count >= permits)
|
||||
{
|
||||
retryAfter = entry.Start + window - now;
|
||||
return false;
|
||||
return new BudgetDenial(entry.Start + window - now, false);
|
||||
}
|
||||
|
||||
entry.Count++;
|
||||
retryAfter = TimeSpan.Zero;
|
||||
return true;
|
||||
if (entry.Count >= permits)
|
||||
{
|
||||
byUse.Remove(entry.UseNode!);
|
||||
entry.UseNode = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
byUse.Remove(entry.UseNode!);
|
||||
byUse.AddLast(entry.UseNode!);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if (entries.Count >= maxKeys)
|
||||
{
|
||||
retryAfter = entries[byStart.Peek()].Start + window - now;
|
||||
return false;
|
||||
if (byUse.First is not { Value: var forgotten })
|
||||
{
|
||||
return new BudgetDenial(byStart.First!.Value.Start + window - now, true);
|
||||
}
|
||||
|
||||
Remove(forgotten);
|
||||
}
|
||||
|
||||
entries[key] = new Entry(now);
|
||||
byStart.Enqueue(key);
|
||||
retryAfter = TimeSpan.Zero;
|
||||
return true;
|
||||
var added = new Entry(key, now);
|
||||
entries[key] = added;
|
||||
added.StartNode = byStart.AddLast(added);
|
||||
if (added.Count < permits)
|
||||
{
|
||||
added.UseNode = byUse.AddLast(added);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Entry(TimeSpan start)
|
||||
private void Remove(Entry entry)
|
||||
{
|
||||
entries.Remove(entry.Key);
|
||||
byStart.Remove(entry.StartNode!);
|
||||
if (entry.UseNode is not null)
|
||||
{
|
||||
byUse.Remove(entry.UseNode);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Entry(string key, TimeSpan start)
|
||||
{
|
||||
public string Key { get; } = key;
|
||||
|
||||
public TimeSpan Start { get; } = start;
|
||||
|
||||
public int Count { get; set; } = 1;
|
||||
|
||||
public LinkedListNode<Entry>? StartNode { get; set; }
|
||||
|
||||
public LinkedListNode<Entry>? UseNode { get; set; }
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -77,16 +77,16 @@ public sealed class VoteModel(
|
|||
{
|
||||
var actor = await actorAccessor.GetAsync(cancellationToken);
|
||||
var voter = ResolveVoter(actor);
|
||||
if (Throttled(limits.DenyCast(HttpContext.Connection.RemoteIpAddress, voter), CastRefusal) is { } throttled)
|
||||
{
|
||||
return throttled;
|
||||
}
|
||||
|
||||
if (await appraisals.GetSubjectAsync(collection, key, null, cancellationToken) is null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
if (Throttled(limits.DenyCast(HttpContext.Connection.RemoteIpAddress, voter), CastRefusal) is { } throttled)
|
||||
{
|
||||
return throttled;
|
||||
}
|
||||
|
||||
await appraisals.RetractAsync(collection, key, voter, cancellationToken);
|
||||
return RedirectToPage(new { collection, key });
|
||||
}
|
||||
|
|
@ -100,16 +100,16 @@ public sealed class VoteModel(
|
|||
var actor = await actorAccessor.GetAsync(cancellationToken);
|
||||
var client = HttpContext.Connection.RemoteIpAddress;
|
||||
var voter = ResolveVoter(actor);
|
||||
if (Throttled(limits.DenyCast(client, voter), CastRefusal) is { } throttled)
|
||||
{
|
||||
return throttled;
|
||||
}
|
||||
|
||||
if (await appraisals.GetSubjectAsync(collection, key, null, cancellationToken) is null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
if (Throttled(limits.DenyCast(client, voter), CastRefusal) is { } throttled)
|
||||
{
|
||||
return throttled;
|
||||
}
|
||||
|
||||
if (voter is null)
|
||||
{
|
||||
if (Throttled(limits.DenyMint(client), MintRefusal) is { } mintThrottled)
|
||||
|
|
@ -133,20 +133,25 @@ public sealed class VoteModel(
|
|||
VoterIdentity.For(actor, null) ?? VoterIdentity.For(actor, deviceCookie.TryRead(HttpContext));
|
||||
|
||||
// A denied budget is a 429 that says when to retry, in words a voter can read; it writes no row, sets no cookie and
|
||||
// repeats nothing of the request. A refused new device is told it can sign in, which has a budget of its own.
|
||||
// repeats nothing of the request. The subject is checked before any budget is spent, so a request for a concept that
|
||||
// does not exist costs the sender nothing and the table nothing. A refused new device is told it can sign in, which
|
||||
// has a budget of its own. A table full of spent windows is not the visitor's doing and says so.
|
||||
private const string CastRefusal = "You are voting too fast. Please wait a little before voting again.";
|
||||
|
||||
private const string MintRefusal =
|
||||
"Too many new voters have voted from your network recently. You can sign in to vote now, or try again later.";
|
||||
|
||||
private IActionResult? Throttled(TimeSpan? retryAfter, string refusal)
|
||||
private const string BusyRefusal = "Voting is very busy right now. Please try again in a little while.";
|
||||
|
||||
private IActionResult? Throttled(BudgetDenial? denial, string spentRefusal)
|
||||
{
|
||||
if (retryAfter is not { } wait)
|
||||
if (denial is not { } refused)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
Response.Headers.RetryAfter = ((int)Math.Ceiling(wait.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
var refusal = refused.TableFull ? BusyRefusal : spentRefusal;
|
||||
Response.Headers.RetryAfter = ((int)Math.Ceiling(refused.RetryAfter.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
return new ContentResult
|
||||
{
|
||||
StatusCode = StatusCodes.Status429TooManyRequests,
|
||||
|
|
|
|||
Loading…
Reference in a new issue