using System.Text.RegularExpressions; internal sealed class TrafficGate( PlantSettings settings, IConfiguration configuration, TimeProvider timeProvider) { private static readonly Regex KeyPattern = new(@"\A[a-zA-Z0-9_.:-]{8,128}\z", RegexOptions.CultureInvariant); private static readonly TimeSpan Retention = TimeSpan.FromHours(24); private readonly object sync = new(); private readonly Dictionary minuteAttempts = new(StringComparer.Ordinal); private readonly Dictionary dailyReservations = new(StringComparer.Ordinal); private readonly Dictionary<(string Subject, string Key), PendingLookup> history = new(); private long activeMinute = long.MinValue; private long activeDay = long.MinValue; private int globalDailyReservations; private DateTimeOffset nextSweep = DateTimeOffset.MinValue; public static bool IsValidKey(string? key) => key is not null && KeyPattern.IsMatch(key); public Admission Admit(string subject, string key, FindPlantsRequest input) { lock (sync) { // Missing or malformed runtime control fails closed. if (!bool.TryParse(configuration["PlantFinder:Enabled"], out var enabled) || !enabled) { return Reject(503, "disabled", "The Plant Finder action is paused."); } var now = timeProvider.GetUtcNow(); var unixSecond = now.ToUnixTimeSeconds(); var minute = unixSecond / 60; var day = unixSecond / 86_400; if (minute > activeMinute) { minuteAttempts.Clear(); activeMinute = minute; } if (day > activeDay) { dailyReservations.Clear(); globalDailyReservations = 0; activeDay = day; } var attempts = minuteAttempts.GetValueOrDefault(subject); if (attempts >= settings.PerUserRequestsPerMinute) { return Reject(429, "rate_limit", "The request rate limit was reached.", SecondsUntil((activeMinute + 1) * 60)); } minuteAttempts[subject] = attempts + 1; if (now >= nextSweep) { foreach (var expired in history.Where(item => item.Value.HasExpired(now)).ToArray()) { history.Remove(expired.Key); } nextSweep = now.AddMinutes(1); } var lookupKey = (subject, key); if (history.TryGetValue(lookupKey, out var previous)) { if (!previous.HasExpired(now)) { return previous.Input == input ? new Admission(previous, OwnsReservation: false, Denial: null) : Reject(409, "idempotency_conflict", "Use a new key for changed input."); } history.Remove(lookupKey); } var reserved = dailyReservations.GetValueOrDefault(subject); if (reserved >= settings.PerUserDailyQuota) { return Reject(429, "per_user_quota", "The daily user lookup quota was reached.", SecondsUntil((activeDay + 1) * 86_400)); } if (globalDailyReservations >= settings.GlobalDailyQuota) { return Reject(429, "global_quota", "The daily shared lookup quota was reached.", SecondsUntil((activeDay + 1) * 86_400)); } // Publish the reservation and pending outcome together before the caller touches the catalog. var entry = new PendingLookup(input, now + Retention); history.Add(lookupKey, entry); dailyReservations[subject] = reserved + 1; globalDailyReservations++; return new Admission(entry, OwnsReservation: true, Denial: null); int SecondsUntil(long futureUnixSecond) => (int)Math.Clamp(futureUnixSecond - unixSecond, 1, int.MaxValue); } } private static Admission Reject(int status, string code, string message, int? retryAfterSeconds = null) => new(Entry: null, OwnsReservation: false, new Denial(status, code, message, retryAfterSeconds)); } internal sealed class PendingLookup(FindPlantsRequest input, DateTimeOffset expiresAt) { private readonly TaskCompletionSource completion = new(TaskCreationOptions.RunContinuationsAsynchronously); public FindPlantsRequest Input { get; } = input; public Task Result => completion.Task; public bool HasExpired(DateTimeOffset now) => now >= expiresAt && Result.IsCompleted; public void Complete(CatalogOutcome outcome) => completion.SetResult(outcome); } internal sealed record Admission(PendingLookup? Entry, bool OwnsReservation, Denial? Denial); internal sealed record Denial(int Status, string Code, string Message, int? RetryAfterSeconds); internal sealed record CatalogOutcome(PlantResponse? Response);