| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | |
| | | 3 | | namespace Intentum.Runtime.RateLimiting; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// In-memory rate limiter using a fixed window per key. |
| | | 7 | | /// Suitable for single-node or development; use a distributed implementation for multi-node. |
| | | 8 | | /// </summary> |
| | | 9 | | public sealed class MemoryRateLimiter : IRateLimiter |
| | | 10 | | { |
| | 10 | 11 | | private readonly ConcurrentDictionary<string, Window> _windows = new(); |
| | | 12 | | |
| | | 13 | | /// <inheritdoc /> |
| | | 14 | | public ValueTask<RateLimitResult> TryAcquireAsync( |
| | | 15 | | string key, |
| | | 16 | | int limit, |
| | | 17 | | TimeSpan window, |
| | | 18 | | CancellationToken cancellationToken = default) |
| | 19 | 19 | | { |
| | 19 | 20 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 21 | | |
| | 19 | 22 | | var now = DateTimeOffset.UtcNow; |
| | 19 | 23 | | var windowKey = $"{key}:{window.Ticks}"; |
| | 19 | 24 | | var current = _windows.AddOrUpdate( |
| | 19 | 25 | | windowKey, |
| | 9 | 26 | | _ => new Window(now, window, 1), |
| | 29 | 27 | | (_, w) => w.Tick(now)); |
| | | 28 | | |
| | 19 | 29 | | var allowed = current.Count <= limit; |
| | 19 | 30 | | TimeSpan? retryAfter = null; |
| | 19 | 31 | | if (!allowed && current.WindowEnd > now) |
| | 3 | 32 | | retryAfter = current.WindowEnd - now; |
| | | 33 | | |
| | 19 | 34 | | var result = new RateLimitResult( |
| | 19 | 35 | | Allowed: allowed, |
| | 19 | 36 | | CurrentCount: current.Count, |
| | 19 | 37 | | Limit: limit, |
| | 19 | 38 | | RetryAfter: retryAfter); |
| | | 39 | | |
| | 19 | 40 | | return ValueTask.FromResult(result); |
| | 19 | 41 | | } |
| | | 42 | | |
| | | 43 | | /// <inheritdoc /> |
| | | 44 | | public void Reset(string key) |
| | 1 | 45 | | { |
| | 2 | 46 | | var toRemove = _windows.Keys.Where(k => k.StartsWith(key + ":", StringComparison.Ordinal)).ToList(); |
| | 5 | 47 | | foreach (var k in toRemove) |
| | 1 | 48 | | _windows.TryRemove(k, out _); |
| | 1 | 49 | | } |
| | | 50 | | |
| | | 51 | | private sealed class Window |
| | | 52 | | { |
| | 10 | 53 | | public DateTimeOffset WindowStart { get; } |
| | 16 | 54 | | public DateTimeOffset WindowEnd { get; } |
| | 10 | 55 | | public TimeSpan Duration { get; } |
| | 48 | 56 | | public int Count { get; } |
| | | 57 | | |
| | 19 | 58 | | public Window(DateTimeOffset start, TimeSpan duration, int count) |
| | 19 | 59 | | { |
| | 19 | 60 | | WindowStart = start; |
| | 19 | 61 | | Duration = duration; |
| | 19 | 62 | | WindowEnd = start + duration; |
| | 19 | 63 | | Count = count; |
| | 19 | 64 | | } |
| | | 65 | | |
| | | 66 | | public Window Tick(DateTimeOffset now) |
| | 10 | 67 | | { |
| | 10 | 68 | | if (now >= WindowEnd) |
| | 0 | 69 | | return new Window(now, Duration, 1); |
| | 10 | 70 | | return new Window(WindowStart, Duration, Count + 1); |
| | 10 | 71 | | } |
| | | 72 | | } |
| | | 73 | | } |