public override async Task <bool> ShouldThrottle(ThrottleRequest throttleRequest) { if (throttleRequest is null) { throw new System.ArgumentNullException(nameof(throttleRequest)); } var configOption = throttleRequest.AppliedConfig; var userId = throttleRequest.UserId; var perMinLimit = configOption.PerMinLimit; var perSecLimit = configOption.PerSecLimit; Console.WriteLine($"perMinLimit: {perMinLimit}"); var userRateLimitConfigCacheKey = Utils.GetPerUserPerRateLimitConfigCacheKey(userId, configOption); var now = DateTime.Now; var currMin = now.AddSeconds(-1 * now.Second); var prevMin = currMin.AddMinutes(-1); var hashFields = new string[] { prevMin.ToString(), currMin.ToString() }; var values = await _cacheManager.HashGet(userRateLimitConfigCacheKey, hashFields); if (values == null || values.Length < 2) { Console.WriteLine("some error while retriving date from redis. Allowing the request to not throttle. But look into this"); return(false); } var currMinValue = values[1]; if (currMinValue.IsNull) { return(await HandleCaseWhenCurrMinValueIsNull(throttleRequest, userRateLimitConfigCacheKey, currMin)); } currMinValue.TryParse(out int currMinIntegerValue); var prevMinValue = values[0]; if (prevMinValue.IsNull) { return(await HandleCaseWhenPrevMinValueIsNull(throttleRequest, userRateLimitConfigCacheKey, currMin, currMinIntegerValue)); } prevMinValue.TryParse(out int prevMinIntergerValue); return(await HandleCaseWhenPrevAndCurrMinHasValue(throttleRequest, userRateLimitConfigCacheKey, now, currMin, currMinIntegerValue, prevMinIntergerValue)); }
public override async Task <bool> ShouldThrottle(ThrottleRequest throttleRequest) { if (throttleRequest is null) { throw new System.ArgumentNullException(nameof(throttleRequest)); } var config = throttleRequest.AppliedConfig; var userId = throttleRequest.UserId; var now = DateTime.Now; var currSec = now.AddMilliseconds(-1 * now.Millisecond); var prevSec = currSec.AddSeconds(-1); var userRateLimitConfigCacheKey = Utils.GetPerUserPerRateLimitConfigCacheKey(userId, config); var hashFields = new string[] { prevSec.ToString(), currSec.ToString() }; var hashFieldValues = await _redisCacheManager.HashGet(userRateLimitConfigCacheKey, hashFields); if (hashFieldValues == null || hashFieldValues.Length < 2) { Console.WriteLine("some error while fetching values from redis"); return(false); } var currSecValue = hashFieldValues[1]; if (currSecValue.IsNull) { return(await HandleCaseWhenCurrSecValueIsNull(throttleRequest, userRateLimitConfigCacheKey, currSec)); } currSecValue.TryParse(out int currSecIntVal); var prevSecValue = hashFieldValues[0]; if (prevSecValue.IsNull) { return(await HandleCaseWhenPrevSecValueIsNull(throttleRequest, userRateLimitConfigCacheKey, currSec, currSecIntVal)); } prevSecValue.TryParse(out int prevSecIntVal); return(await HandleCaseWhenPrevAndCurrSecHasValue(throttleRequest, userRateLimitConfigCacheKey, now, currSec, currSecIntVal, prevSecIntVal)); }