private void Call(Limiter limiter, DateTime time, TimeSpan?expectedWaitTime) { TimeProvider.Instance = new StaticTimeProvider(time); delay.ResetCalls(); if (expectedWaitTime == null) { delay.Setup(delay => delay(It.IsAny <TimeSpan>())); } else { delay.Setup(delay => delay(It.Is <TimeSpan>(waitTime => waitTime == expectedWaitTime.Value))) .Returns <TimeSpan>(x => { var b = new StaticTimeProvider(TimeProvider.UtcNow + x); TimeProvider.Instance = b; return(Task.Delay(0)); }); } limiter.DoAsync(Do).Wait(); delay.Verify(); if (expectedWaitTime == null) { Assert.Equal(time, TimeProvider.UtcNow); } else { Assert.Equal(time + expectedWaitTime, TimeProvider.UtcNow); } }
public async Task ExistingObject_IncrementByOneAndSetExpirationDateAsync() { // Arrange var key = new SimpleThrottleKey("test", "key"); var limiter = new Limiter() .Limit(1) .Over(100); var cache = new MemoryCache(new MemoryCacheOptions()); var repository = new MemoryThrottleRepository(cache); string id = repository.CreateThrottleKey(key, limiter); var cacheItem = new MemoryThrottleRepository.ThrottleCacheItem() { Count = 1, Expiration = new DateTime(2030, 1, 1) }; cache .Set(id, cacheItem, cacheItem.Expiration); // Act await repository.AddOrIncrementWithExpirationAsync(key, limiter); // Assert var item = (MemoryThrottleRepository.ThrottleCacheItem)cache.Get(id); Assert.Equal(2L, item.Count); Assert.Equal(new DateTime(2030, 1, 1), item.Expiration); }
public async ReusableTask <int> ReadAsync(ITorrentFileInfo file, long offset, byte[] buffer, int bufferOffset, int count) { Check.File(file); Check.Buffer(buffer); if (offset < 0 || offset + count > file.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } using (await Limiter.EnterAsync()) { using var rented = await StreamCache.GetOrCreateStreamAsync(file, FileAccess.Read).ConfigureAwait(false); await MainLoop.SwitchToThreadpool(); if (rented.Stream.Length < offset + count) { return(0); } if (rented.Stream.Position != offset) { await rented.Stream.SeekAsync(offset); } ReadMonitor?.AddDelta(count); return(await rented.Stream.ReadAsync(buffer, bufferOffset, count)); } }
public void Download() { Chapter = SerieTestData.Serie.Chapters.ElementAtOrDefault(Index - 1); PageCount = -1; URL = Chapter.URL; Chapter.State = ChapterState.Waiting; Limiter.BeginChapter(Chapter); try { Chapter.DownloadPagesList(); } finally { Limiter.EndChapter(Chapter); } PageCount = Chapter.Pages.Count; Title = Chapter.Title; foreach (var page in Pages) { if (page.Index > PageCount) { page.Index = -1; page.Name += " - index out of range"; continue; } page.Download(); } }
private void beginRequest(object sender, EventArgs e) { try { string ip = HttpContext.Current.Request.UserHostAddress; //Ignore files int ind = string.IsNullOrEmpty(HttpContext.Current.Request.FilePath) || HttpContext.Current.Request.FilePath.Length > MAX_VALID_FILE_PATH_SIZE ? -1 : HttpContext.Current.Request.FilePath.LastIndexOf('.'); string ext = ind < 0 ? null : HttpContext.Current.Request.FilePath.Substring(ind).ToLower(); if (!string.IsNullOrEmpty(ext) && ext.Length > 1 && ".js,.css,.jpg,.png,.gif,.aspx,.ashx,.eot,.ttf,.woff,.otf,.svg,.woff2".IndexOf(ext) >= 0) { return; } //end of Ignore files if (!Applicants.ContainsKey(ip)) { Applicants[ip] = new Limiter(); } if (!Applicants[ip].newRequest(HttpContext.Current.Request)) { HttpContext.Current.Response.StatusCode = 403; HttpContext.Current.Response.End(); } } catch { } }
public void Download() { Page = ChapterTestData.Chapter.Pages.ElementAtOrDefault(Index - 1); URL = Page.URL; Index = -1; Limiter.BeginChapter(Page.Chapter); try { var stream = Page.GetImageStream(); Image = System.Drawing.Image.FromStream(stream); ImageURL = Page.ImageURL; stream.Position = 0; Hash = TomanuExtensions.Utils.Hash.CalculateSHA256(stream); } finally { Limiter.EndChapter(Page.Chapter); } if (Page.State == PageState.Error) { throw new Exception("Downloading page error"); } Index = Page.Index; Name = Page.Name; }
public void LimitReached_ReturnsThrottled() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { Count = 1 }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.Should().Be(true); result.IsLocked.Should().Be(false); }
public async Task RetrieveValidThrottleCountFromRepostitoryAsync() { // Arrange var key = new SimpleThrottleKey("test", "key"); var limiter = new Limiter() .Limit(1) .Over(100); var cache = new MemoryCache(new MemoryCacheOptions()); var repository = new MemoryThrottleRepository(cache); string id = repository.CreateThrottleKey(key, limiter); var cacheItem = new MemoryThrottleRepository.ThrottleCacheItem() { Count = 1, Expiration = new DateTime(2030, 1, 1) }; await repository.AddOrIncrementWithExpirationAsync(key, limiter); // Act var count = await repository.GetThrottleCountAsync(key, limiter); // Assert Assert.Equal(1, count); }
public async ReusableTask WriteAsync(ITorrentFileInfo file, long offset, byte[] buffer, int bufferOffset, int count) { Check.File(file); Check.Buffer(buffer); if (offset < 0 || offset + count > file.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } using (await Limiter.EnterAsync()) { using var rented = await StreamCache.GetOrCreateStreamAsync(file, FileAccess.ReadWrite).ConfigureAwait(false); // FileStream.WriteAsync does some work synchronously, according to the profiler. // It looks like if the file is too small it is expanded (SetLength is called) // synchronously before the asynchronous Write is performed. // // We also want the Seek operation to execute on the threadpool. await MainLoop.SwitchToThreadpool(); await rented.Stream.SeekAsync(offset).ConfigureAwait(false); await rented.Stream.WriteAsync(buffer, bufferOffset, count).ConfigureAwait(false); WriteMonitor?.AddDelta(count); } }
public ParticleEffect_A() : base(10000) { _Limiter = new Limiter(0); x = 0; y = 0; }
public void ZeroLimit_ReturnsNotThrottled() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { Count = 0 }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.ShouldBeEquivalentTo(CheckResult.NotThrottled.IsThrottled); result.IsLocked.ShouldBeEquivalentTo(CheckResult.NotThrottled.IsLocked); }
public void CallWithTimeSpan_SetPeriod() { Limiter limiter = new Limiter() .Over(TimeSpan.FromSeconds(10)); limiter.Period.ShouldBeEquivalentTo(TimeSpan.FromSeconds(10)); }
public void Throttled_ReturnsTrue() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { Count = 1, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult checkResult; bool result = policy.IsThrottled(key, out checkResult); // Assert result.Should().Be(true); }
public void ExistingObject_IncrementByOneAndSetExpirationDate() { // Arrange var key = new SimpleThrottleKey("test", "key"); var limiter = new Limiter() .Limit(1) .Over(100); var cache = new MemoryCache("testing_cache"); var repository = new MemoryThrottleRepository(cache); string id = repository.CreateThrottleKey(key, limiter); var cacheItem = new MemoryThrottleRepository.ThrottleCacheItem() { Count = 1, Expiration = new DateTime(2030, 1, 1) }; cache .Set(id, cacheItem, cacheItem.Expiration); // Act repository.AddOrIncrementWithExpiration(key, limiter); // Assert var item = (MemoryThrottleRepository.ThrottleCacheItem)cache.Get(id); Assert.Equal(2L, item.Count); Assert.Equal(new DateTime(2030, 1, 1), item.Expiration); }
public void CallWithTimeSpan_SetLockDuration() { Limiter limiter = new Limiter() .LockFor(TimeSpan.FromSeconds(1)); limiter.LockDuration.ShouldBeEquivalentTo(TimeSpan.FromSeconds(1)); }
public void StoreOriginalAngles(Limiter limits) { m_originalMinH = limits.m_minimumHorizontalAngle; m_originalMaxH = limits.m_maximumHorizontalAngle; m_originalMinV = limits.m_minimumVerticalAngle; m_originalMaxV = limits.m_maximumVerticalAngle; }
public void RetrieveValidThrottleCountFromRepostitory() { // Arrange var key = new SimpleThrottleKey("test", "key"); var limiter = new Limiter() .Limit(1) .Over(100); var cache = new MemoryCache("testing_cache"); var repository = new MemoryThrottleRepository(cache); string id = repository.CreateThrottleKey(key, limiter); var cacheItem = new MemoryThrottleRepository.ThrottleCacheItem() { Count = 1, Expiration = new DateTime(2030, 1, 1) }; repository.AddOrIncrementWithExpiration(key, limiter); // Act var count = repository.GetThrottleCount(key, limiter); // Assert Assert.Equal(count, 1); }
public void IncrementReturnsOne_ExpireKey() { // Arrange var key = new SimpleThrottleKey("test", "key"); Limiter limiter = new Limiter().Limit(1).Over(10); var db = Substitute.For <IDatabase>(); var repository = new RedisThrottleRepository(db); string id = repository.CreateThrottleKey(key, limiter); db .StringIncrement(id) .Returns(1); // Act repository.AddOrIncrementWithExpiration(key, limiter); // Assert db .Received(1) .StringIncrement(id); db .Received(1) .KeyExpire(id, limiter.Period); }
private Node MakeDecoratorNode(DecoratorNodeType decorator, uint childNodeID, uint extra = 0) { Node newNode; if (!m_nodeDic.TryGetValue(childNodeID, out Node result)) { return(null); // failed to get childNodeID } switch (decorator) { case DecoratorNodeType.Inverter: newNode = new Inverter(result); break; case DecoratorNodeType.Repeater: newNode = new Repeater(result, extra); break; case DecoratorNodeType.RepeatTillFail: newNode = new RepeatTillFail(result); break; case DecoratorNodeType.Limiter: newNode = new Limiter(result); break; default: return(null); // tried to create unknown decorator node } return(newNode); }
public void CallWithSeconds_SetPeriod() { Limiter limiter = new Limiter() .Over(10); limiter.Period.ShouldBeEquivalentTo(TimeSpan.FromSeconds(10)); }
internal override IEnumerable <Page> DownloadPages(Chapter a_chapter) { a_chapter.Token.ThrowIfCancellationRequested(); Limiter.Aquire(a_chapter); try { Sleep(); } finally { Limiter.Release(a_chapter); } a_chapter.Token.ThrowIfCancellationRequested(); a_chapter.State = ChapterState.DownloadingPagesList; var serie = m_series.First(s => s.Title == a_chapter.Serie.Title); var chapter = serie.GetChapters().First(c => c.Title == a_chapter.Title); var pages = chapter.GeneratePages().ToList(); if (a_chapter.Title.Contains("error pages none")) { throw new Exception(); } var result = from page in pages select new Page(a_chapter, "fake_page_url", pages.IndexOf(page) + 1, page); return(result); }
public void CallWithSeconds_SetLockDuration() { Limiter limiter = new Limiter() .LockFor(1); limiter.LockDuration.ShouldBeEquivalentTo(TimeSpan.FromSeconds(1)); }
public void perform(World world) { string last = "air"; for (float xl = 0; xl < world.xChunks * world.xBlocks; xl++) { for (float yl = 0; yl < world.yChunks * world.yBlocks; yl++) { for (float zl = 0; zl < world.zChunks * world.zBlocks; zl++) { float perlinX = xl / (world.xChunks * world.xBlocks) / perlinCoefX - perlinPlusX, perlinZ = zl / (world.zChunks * world.zBlocks) / perlinCoefZ - perlinPlusZ; float perlinY = Mathf.PerlinNoise(perlinX, perlinZ) * perlinCoefY + perlinPlusY; //Debug.Log(perlinX+" "+perlinZ+" "+perlinY); float x = xl, y = yl / coef * (perlinNoise && !perlinPlus ? perlinY : 1) + (perlinNoise && perlinPlus ? perlinY : 0), z = zl; foreach (GenerationElement gElem in levels) { float xc = gElem.rawX ? xl : x, yc = gElem.rawY ? yl : y, zc = gElem.rawZ ? zl : z; if (Limiter.check(gElem.xMin, xc) && Limiter.check(gElem.xMax, xc) && Limiter.check(gElem.yMin, yc) && Limiter.check(gElem.yMax, yc) && Limiter.check(gElem.zMin, zc) && Limiter.check(gElem.zMax, zc)) { last = gElem.idName; if (gElem.endFor) { break; } } } world.set(new EntityLocation((int)xl, (int)yl, (int)zl, 0, 0, 0, Random.Range(0, 2) > 0, Random.Range(0, 2) > 0, Random.Range(0, 2) > 0), new Entity().recreate(EntityId.ByName(last))); } } } }
public void Locked_ReturnsLocked() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(true); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsLocked.Should().Be(true); result.Limiter.Should().Be(limit); }
public void ReserveTellsYouHowLongToWait() { var clock = new FakeSystemClock(); var limiter = new Limiter(new Limit(10), 50, clock); var initiallyAllowed = limiter.AllowN(clock.UtcNow, 50); var thenNotAllowed1 = limiter.Allow(); var reserveOne = limiter.Reserve(); var delayOne = reserveOne.Delay(); var reserveTwoMore = limiter.Reserve(clock.UtcNow, 2); var delayTwoMore = reserveTwoMore.Delay(); clock.Advance(TimeSpan.FromMilliseconds(450)); var reserveAlreadyAvailable = limiter.Reserve(); var delayAlreadyAvailable = reserveAlreadyAvailable.Delay(); var reserveHalfAvailable = limiter.Reserve(); var delayHalfAvailable = reserveHalfAvailable.Delay(); Assert.True(initiallyAllowed); Assert.False(thenNotAllowed1); Assert.True(reserveOne.Ok); Assert.Equal(TimeSpan.FromMilliseconds(100), delayOne); Assert.True(reserveTwoMore.Ok); Assert.Equal(TimeSpan.FromMilliseconds(300), delayTwoMore); Assert.True(reserveAlreadyAvailable.Ok); Assert.Equal(TimeSpan.Zero, delayAlreadyAvailable); Assert.True(reserveHalfAvailable.Ok); Assert.Equal(TimeSpan.FromMilliseconds(50), delayHalfAvailable); }
public void IncrementReturnsOne_ExpireKey() { // Arrange var key = new SimpleThrottleKey("test", "key"); Limiter limiter = new Limiter().Limit(1).Over(10); var db = Substitute.For<IDatabase>(); var repository = new RedisThrottleRepository(db); string id = repository.CreateThrottleKey(key, limiter); db .StringIncrement(id) .Returns(1); // Act repository.AddOrIncrementWithExpiration(key, limiter); // Assert db .Received(1) .StringIncrement(id); db .Received(1) .KeyExpire(id, limiter.Period); }
public void TokensBecomeAvailableAtLimitPerSecondRate() { var clock = new FakeSystemClock(); var limiter = new Limiter(new Limit(10), 50, clock); var initiallyAllowed = limiter.AllowN(clock.UtcNow, 50); var thenNotAllowed1 = limiter.Allow(); clock.Advance(TimeSpan.FromMilliseconds(100)); var oneTokenAvailable = limiter.Allow(); var thenNotAllowed2 = limiter.Allow(); clock.Advance(TimeSpan.FromMilliseconds(200)); var twoTokensAvailable1 = limiter.Allow(); var twoTokensAvailable2 = limiter.Allow(); var thenNotAllowed3 = limiter.Allow(); Assert.True(initiallyAllowed); Assert.False(thenNotAllowed1); Assert.True(oneTokenAvailable); Assert.False(thenNotAllowed2); Assert.True(twoTokensAvailable1); Assert.True(twoTokensAvailable2); Assert.False(thenNotAllowed3); }
public void SetLock() { // Arrange var key = new SimpleThrottleKey("test", "key"); Limiter limiter = new Limiter().Limit(1).Over(1).LockFor(1); var db = Substitute.For <IDatabase>(); var repository = new RedisThrottleRepository(db); string id = repository.CreateLockKey(key, limiter); var transaction = Substitute.For <ITransaction>(); db .CreateTransaction() .Returns(transaction); // Act repository.SetLock(key, limiter); // Assert transaction .Received(1) .StringIncrementAsync(id); transaction .Received(1) .KeyExpireAsync(id, limiter.LockDuration); transaction .Received(1) .Execute(); }
public void NotThrottled_DoesNotIncrements() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { Count = 2, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act policy.Check(key, false); // Assert repo.Received(0) .AddOrIncrementWithExpiration(key, limit); }
public override List <Patron> readALL(Limiter limiter) { List <Patron> list = null; MySQL_DBManager db = new MySQL_DBManager(DBCredentials_Factory.getCredentials(typeof(Patron))); string query = "SELECT id FROM patron"; if (limiter != null) { query += " LIMIT " + limiter.ResultsOffeset + "," + limiter.ResultsCount + ";"; } else { query += ";"; } MySqlDataReader reader = db.ExceuteSQL(query); if (reader != null) { list = new List <Patron>(); while (reader.Read()) { Patron dto = read(reader.GetInt32(0)); if (dto != null) { list.Add(dto); } } reader.Close(); } db.close(); return(list); }
/// <summary> /// /// </summary> /// <param name="target">has to be in range[0, 100][%]</param> public void SetTarget(double target) { if (Limiter.LimitAndReturnTrueIfLimitted(ref target, 0, 100)) { Logger.Log(this, "target brake is not in range [0, 100]", 1); } double calculatedSteering; if (alertBrakeActive) { calculatedSteering = regulator.SetTargetValue(ALERT_BRAKE_BRAKE_SETTING); } else if (targetBrakeOverriden) { calculatedSteering = regulator.SetTargetValue(targetBrakeOverridenValue); } else { calculatedSteering = regulator.SetTargetValue(target); } //this will also invoke evNewBrakeSettingCalculated event BrakeSteering = calculatedSteering; }
public void LimitReached_ReturnsThrottled() { // Arrange var key = Substitute.For<IThrottleKey>(); var limit = new Limiter { Count = 1 }; var repo = Substitute.For<IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.ShouldBeEquivalentTo(true); result.IsLocked.ShouldBeEquivalentTo(false); }
public void CallWithTimeSpan_SetLockDuration() { Limiter limiter = new Limiter() .LockFor(TimeSpan.FromSeconds(1)); limiter.LockDuration.Should().Be(TimeSpan.FromSeconds(1)); }
public void CallWithTimeSpan_SetPeriod() { Limiter limiter = new Limiter() .Over(TimeSpan.FromSeconds(10)); limiter.Period.Should().Be(TimeSpan.FromSeconds(10)); }
public void LimitReachedWithLocking_ReturnsThrottled() { // Arrange var key = Substitute.For <IThrottleKey>(); var limit = new Limiter { Count = 1, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For <IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.Should().Be(true); result.IsLocked.Should().Be(false); repo.Received(1) .SetLock(key, limit); repo.Received(1) .RemoveThrottle(key, limit); }
public void PerMinute_SetCountAndPeriod() { Limiter limiter = new Limiter() .PerMinute(10); limiter.Count.ShouldBeEquivalentTo(10); limiter.Period.ShouldBeEquivalentTo(TimeSpan.FromMinutes(1)); }
public void CallWithNumber_SetCountReturnObject() { var limiter = new Limiter(); Limiter returned = limiter.Limit(10); limiter.Count.ShouldBeEquivalentTo(10); returned.ShouldBeEquivalentTo(limiter); }
public void PerSecond_SetCountAndPeriod() { Limiter limiter = new Limiter() .PerSecond(10); limiter.Count.ShouldBeEquivalentTo(10); limiter.Period.ShouldBeEquivalentTo(TimeSpan.FromSeconds(1)); }
public void SetLock(IThrottleKey key, Limiter limiter) { string id = CreateLockKey(key, limiter); ITransaction trans = _db.CreateTransaction(); trans.StringIncrementAsync(id); trans.KeyExpireAsync(id, limiter.LockDuration); trans.Execute(); }
void Start() { foreach (var player in FindObjectsOfType<Limiter>()) { if (!player.isLocalPlayer) continue; limiter_ = player; } text_ = GetComponent<Text>(); }
public long? GetThrottleCount(IThrottleKey key, Limiter limiter) { string id = CreateThrottleKey(key, limiter); RedisValue value = _db.StringGet(id); long convert; if (long.TryParse(value, out convert)) return convert; return null; }
public void AddOrIncrementWithExpiration(IThrottleKey key, Limiter limiter) { string id = CreateThrottleKey(key, limiter); long result = _db.StringIncrement(id); // If we get back 1, that means the key was incremented as it // was expiring or it's a new key. Ensure we set the expiration. if (result == 1) _db.KeyExpire(id, limiter.Period); }
public string CreateLockKey(IThrottleKey key, Limiter limiter) { List<object> values = CreateBaseKeyValues(key, limiter); string lockKeySuffix = TimeSpanToFriendlyString(limiter.LockDuration.Value); values.Add("lock"); values.Add(lockKeySuffix); string id = string.Join(":", values); return id; }
public string CreateThrottleKey(IThrottleKey key, Limiter limiter) { List<object> values = CreateBaseKeyValues(key, limiter); string countKey = TimeSpanToFriendlyString(limiter.Period); values.Add(countKey); // Using the Unix timestamp to the key allows for better // precision when querying a key from Redis if (limiter.Period.TotalSeconds == 1) values.Add(GetUnixTimestamp()); string id = string.Join(":", values); return id; }
public void KeyExists_ReturnsParsedValue() { // Arrange var key = new SimpleThrottleKey("test", "key"); Limiter limiter = new Limiter().Limit(1).Over(1); var db = Substitute.For<IDatabase>(); var repository = new RedisThrottleRepository(db); string id = repository.CreateThrottleKey(key, limiter); db .StringGet(id) .Returns((RedisValue)"10"); // Act long? result = repository.GetThrottleCount(key, limiter); // Assert Assert.Equal(10, result); }
public void NewObject_SetsCountToOneWithExpiration() { // Arrange var key = new SimpleThrottleKey("test", "key"); var limiter = new Limiter() .Limit(1) .Over(100); var cache = new MemoryCache("testing_cache"); var repository = new MemoryThrottleRepository(cache); repository.CurrentDate = () => new DateTime(2030, 1, 1); string id = repository.CreateThrottleKey(key, limiter); // Act repository.AddOrIncrementWithExpiration(key, limiter); // Assert var item = (MemoryThrottleRepository.ThrottleCacheItem)cache.Get(id); Assert.Equal(1L, item.Count); // We're testing a future date by 100 seconds which is 40 seconds + 1 minute Assert.Equal(new DateTime(2030, 1, 1, 0, 1, 40), item.Expiration); }
public void Locked_ReturnsLocked() { // Arrange var key = Substitute.For<IThrottleKey>(); var limit = new Limiter { LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For<IThrottleRepository>(); repo.LockExists(key, limit) .Returns(true); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsLocked.ShouldBeEquivalentTo(true); result.Limiter.ShouldBeEquivalentTo(limit); }
public ParticleEffect_B() : base() { limiter = new Limiter(1); }
private List<object> CreateBaseKeyValues(IThrottleKey key, Limiter limiter) { List<object> values = key.Values.ToList(); if (PolicyIdentityValues != null && PolicyIdentityValues.Length > 0) values.InsertRange(0, PolicyIdentityValues); return values; }
public void PerHour_SetCountAndPeriod() { Limiter limiter = new Limiter() .PerHour(10); limiter.Count.ShouldBeEquivalentTo(10); limiter.Period.ShouldBeEquivalentTo(TimeSpan.FromHours(1)); }
public void RemoveThrottle() { // Arrange var key = new SimpleThrottleKey("test", "key"); Limiter limiter = new Limiter().Limit(1).Over(1); var db = Substitute.For<IDatabase>(); var repository = new RedisThrottleRepository(db); string id = repository.CreateThrottleKey(key, limiter); // Act repository.RemoveThrottle(key, limiter); // Assert db .Received(1) .KeyDelete(id); }
public void SetLock() { // Arrange var key = new SimpleThrottleKey("test", "key"); Limiter limiter = new Limiter().Limit(1).Over(1).LockFor(1); var db = Substitute.For<IDatabase>(); var repository = new RedisThrottleRepository(db); string id = repository.CreateLockKey(key, limiter); var transaction = Substitute.For<ITransaction>(); db .CreateTransaction() .Returns(transaction); // Act repository.SetLock(key, limiter); // Assert transaction .Received(1) .StringIncrementAsync(id); transaction .Received(1) .KeyExpireAsync(id, limiter.LockDuration); transaction .Received(1) .Execute(); }
public void KeyExists_ReturnsTrue(bool keyExists, bool expected) { // Arrange var key = new SimpleThrottleKey("test", "key"); Limiter limiter = new Limiter().Limit(1).Over(1).LockFor(1); var db = Substitute.For<IDatabase>(); var repository = new RedisThrottleRepository(db); string id = repository.CreateLockKey(key, limiter); db .KeyExists(id) .Returns(keyExists); // Act bool result = repository.LockExists(key, limiter); // Assert Assert.Equal(expected, result); }
public void ThrottleCountReturnsNullWhenUsingInvalidKey() { // Arrange var key = new SimpleThrottleKey("test", "key"); var limiter = new Limiter() .Limit(1) .Over(100); var cache = new MemoryCache("testing_cache"); var repository = new MemoryThrottleRepository(cache); // Act var count = repository.GetThrottleCount(key, limiter); // Assert Assert.Equal(count, null); }
public void Throttled_ReturnsTrue() { // Arrange var key = Substitute.For<IThrottleKey>(); var limit = new Limiter { Count = 1, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For<IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult checkResult; bool result = policy.IsThrottled(key, out checkResult); // Assert result.ShouldBeEquivalentTo(true); }
public void NotThrottled_DoesNotIncrements() { // Arrange var key = Substitute.For<IThrottleKey>(); var limit = new Limiter { Count = 2, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For<IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act policy.Check(key, false); // Assert repo.Received(0) .AddOrIncrementWithExpiration(key, limit); }
public void LimitReachedWithLocking_ReturnsThrottled() { // Arrange var key = Substitute.For<IThrottleKey>(); var limit = new Limiter { Count = 1, LockDuration = TimeSpan.FromSeconds(1) }; var repo = Substitute.For<IThrottleRepository>(); repo.LockExists(key, limit) .Returns(false); repo.GetThrottleCount(key, limit) .Returns(1); var policy = new ThrottlePolicy(repo); policy.Limiters.Add(limit); // Act CheckResult result = policy.Check(key); // Assert result.IsThrottled.ShouldBeEquivalentTo(true); result.IsLocked.ShouldBeEquivalentTo(false); repo.Received(1) .SetLock(key, limit); repo.Received(1) .RemoveThrottle(key, limit); }
static void Main(string[] args) { var d = new Dispatcher(); var midgetHouse = new MidgetHouse(d); d.Subscribe<OrderPlaced>(midgetHouse); d.Subscribe<DodgyOrderPlaced>(midgetHouse); var manager = new Manager(); var cashier = new Cashier(d); var ass = new AssMan(d); var cookDispatcher = new SmartDispatcher<CookFood>(); var cookTtlGate = new TimeToLiveGate<CookFood>(cookDispatcher); var cookQueudHandler = new QueuedHandler<CookFood>(cookTtlGate, "cook ttl gate"); var cookLimiter = new Limiter<CookFood>(cookQueudHandler); //var cookScrewsUp = new ScrewsUp<CookFood>(cookLimiter); var alarmClock = new AlarmClock(d); var messageMonitor = new MessageMonitor(d); var fmm = new FilePerOrderMonitor(d); d.Subscribe(alarmClock); d.Subscribe(cookLimiter); d.Subscribe(ass); d.Subscribe(cashier); d.Subscribe(manager); d.Subscribe<OrderPlaced>(messageMonitor); d.Subscribe<DodgyOrderPlaced>(messageMonitor); d.Subscribe<OrderPlaced>(fmm); d.Subscribe<DodgyOrderPlaced>(fmm); var cookQueudHandler1 = new QueuedHandler<CookFood>(new Cook(d, 10000), "c1"); cookDispatcher.AddHandler(cookQueudHandler1); var cookQueudHandler2 = new QueuedHandler<CookFood>(new Cook(d, 5000), "c2"); cookDispatcher.AddHandler(cookQueudHandler2); var cookQueudHandler3 = new QueuedHandler<CookFood>(new Cook(d, 100), "c3"); cookDispatcher.AddHandler(cookQueudHandler3); var queueMonitor = new QueueMonitor(new IAmMonitored[] {cookQueudHandler1, cookQueudHandler2, cookQueudHandler3, cookQueudHandler,d.QueudHandler}); //Cook cook = new Cook(ass); var waiter = new Waiter(d); cookQueudHandler1.Start(); cookQueudHandler2.Start(); cookQueudHandler3.Start(); cookQueudHandler.Start(); d.Start(); alarmClock.Start(); queueMonitor.Start(); new Thread(TryPay).Start(cashier); Random r = new Random(); for (int i = 0; i < 500; i++) { Guid orderNumber; if (r.Next()%2 == 0) { orderNumber = waiter.PlaceDodgyOrder(new[] {Tuple.Create("Burger", 1)}, 15); } else { orderNumber = waiter.PlaceOrder(new[] { Tuple.Create("Burger", 1) }, 15); } if(i > 2)Thread.Sleep(2000); orders.TryAdd(orderNumber, null); } //var orderNumber = waiter.PlaceOrder(new[] {Tuple.Create("Burger", 1)}, 15); //cashier.PayForOrder(orderNumber); Console.ReadLine(); }