A host-side token bucket rate limiter keyed by connection GUID and action name. Bumps a per-key bucket on each Allow call and can drop all buckets for a connection.
using System;
using System.Collections.Generic;
namespace RoleplayFramework.Net;
/// <summary>Token bucket per (connection, action). Host-side only.</summary>
public sealed class RateLimiter
{
struct Bucket
{
public double Tokens;
public double Last;
}
readonly Dictionary<(Guid, string), Bucket> _buckets = new();
/// <summary>
/// Returns true if the action is allowed. <paramref name="burst"/> is the bucket size,
/// <paramref name="perSecond"/> the refill rate.
/// </summary>
public bool Allow( Guid connection, string action, double burst, double perSecond )
{
double now = RealTime.NowDouble;
var key = (connection, action);
if ( !_buckets.TryGetValue( key, out var b ) )
b = new Bucket { Tokens = burst, Last = now };
b.Tokens = Math.Min( burst, b.Tokens + (now - b.Last) * perSecond );
b.Last = now;
bool allowed = b.Tokens >= 1;
if ( allowed ) b.Tokens -= 1;
_buckets[key] = b;
return allowed;
}
public void Forget( Guid connection )
{
var remove = new List<(Guid, string)>();
foreach ( var k in _buckets.Keys )
if ( k.Item1 == connection ) remove.Add( k );
foreach ( var k in remove ) _buckets.Remove( k );
}
public void Clear() => _buckets.Clear();
}