From 9557f842cc68eb259eacbe15d33ce09ad04dba08 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 13:18:39 -0600 Subject: add IsDictionary --- src/slskd/Common/Extensions.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 90f0b659..ebf16fce 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -18,6 +18,7 @@ namespace slskd { using System; + using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; @@ -307,6 +308,23 @@ namespace slskd return builder.ToString(); } + /// + /// Determines whether the given object is a . + /// + /// The object to check. + /// A value indicating whether the given object is a dictionary. + public static bool IsDictionary(this object obj) + { + if (obj == null) + { + return false; + } + + return obj is IDictionary && + obj.GetType().IsGenericType && + obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); + } + /// /// Redacts this instance of Options, replacing properties marked with with '*****'. /// -- cgit v1.2.3 From 963311ed00b8550933491944421f45d6a81228c0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 13:18:53 -0600 Subject: recursively validate dictionary elements --- src/slskd/Common/Validation/ValidateAttribute.cs | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Validation/ValidateAttribute.cs b/src/slskd/Common/Validation/ValidateAttribute.cs index d731eb0e..c7efaa92 100644 --- a/src/slskd/Common/Validation/ValidateAttribute.cs +++ b/src/slskd/Common/Validation/ValidateAttribute.cs @@ -17,8 +17,10 @@ namespace slskd.Validation { + using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; + using System.Linq; /// /// Indicates that attributed properties should be recursively validated. @@ -35,6 +37,30 @@ namespace slskd.Validation var results = new List(); var context = new ValidationContext(value, null, null); + if (value.IsDictionary()) + { + var compositeResults = new CompositeValidationResult(validationContext.DisplayName); + + // given the context in this application, key type should never be anything but a string + foreach (string key in ((IDictionary)value).Keys) + { + var val = ((IDictionary)value)[key]; + var result = IsValid(val, new ValidationContext(val, null, null)); + + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + } + } + + if (compositeResults.Results.Any()) + { + return compositeResults; + } + + return ValidationResult.Success; + } + Validator.TryValidateObject(value, context, results, true); if (results.Count != 0) -- cgit v1.2.3 From c586e614c7894c8791541f1526d38a989160eaa0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 18:24:39 -0600 Subject: add TokenBucket --- src/slskd/Common/TokenBucket.cs | 250 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 src/slskd/Common/TokenBucket.cs (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/TokenBucket.cs b/src/slskd/Common/TokenBucket.cs new file mode 100644 index 00000000..29fd720c --- /dev/null +++ b/src/slskd/Common/TokenBucket.cs @@ -0,0 +1,250 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Implements the 'token bucket' or 'leaky bucket' rate limiting algorithm. + /// + public interface ITokenBucket + { + /// + /// Gets the bucket capacity. + /// + public long Capacity { get; } + + /// + /// Asynchronously retrieves the specified token from the bucket. + /// + /// + /// + /// If the requested exceeds the bucket , the request is lowered to + /// the capacity of the bucket. + /// + /// If the bucket has tokens available, but fewer than the requested amount, the available tokens are returned. + /// + /// If the bucket has no tokens available, execution waits for the bucket to be replenished before servicing the request. + /// + /// + /// The number of tokens to retrieve. + /// The token to monitor for cancellation requests. + /// A Task that completes when tokens have been provided. + Task GetAsync(int count, CancellationToken cancellationToken = default); + + /// + /// Returns the specified token to the bucket. + /// + /// + /// This method should only be called if tokens were retrieved from the bucket, but were not used. + /// + /// If the specified count exceeds the bucket capacity, the count is lowered to the capacity. Effectively this + /// allows the bucket to 'burst' up to 2x capacity to 'catch up' to the desired rate if tokens were wastefully + /// retrieved. + /// + /// If the specified count is negative, no change is made to the available count. + /// + /// The number of tokens to return. + void Return(int count); + + /// + /// Sets the bucket capacity to the supplied . + /// + /// Change takes effect on the next reset. + /// The bucket capacity. + void SetCapacity(long capacity); + } + + /// + /// Implements the 'token bucket' or 'leaky bucket' rate limiting algorithm. + /// + public class TokenBucket : ITokenBucket, IDisposable + { + /// + /// Initializes a new instance of the class. + /// + /// The bucket capacity. + /// The interval at which tokens are replenished. + public TokenBucket(long capacity, int interval) + { + if (capacity < 1) + { + throw new ArgumentOutOfRangeException(nameof(capacity), "Bucket capacity must be greater than or equal to 1"); + } + + if (interval < 1) + { + throw new ArgumentOutOfRangeException(nameof(interval), "Interval must be greater than or equal to 1"); + } + + Capacity = capacity; + CurrentCount = Capacity; + + Clock = new System.Timers.Timer(interval); + Clock.Elapsed += (sender, e) => _ = Reset(); + Clock.Start(); + } + + /// + /// Gets the bucket capacity. + /// + public long Capacity { get; private set; } + + private System.Timers.Timer Clock { get; set; } + private long CurrentCount { get; set; } + private bool Disposed { get; set; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private TaskCompletionSource WaitForReset { get; set; } = new TaskCompletionSource(); + + /// + /// Disposes this instance. + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// + /// Asynchronously retrieves the specified token from the bucket. + /// + /// + /// + /// If the requested exceeds the bucket , the request is lowered to + /// the capacity of the bucket. + /// + /// If the bucket has tokens available, but fewer than the requested amount, the available tokens are returned. + /// + /// If the bucket has no tokens available, execution waits for the bucket to be replenished before servicing the request. + /// + /// + /// The number of tokens to retrieve. + /// The token to monitor for cancellation requests. + /// A Task that completes when tokens have been provided. + public Task GetAsync(int count, CancellationToken cancellationToken = default) + { + return GetInternalAsync(Math.Min(count, (int)Math.Min(int.MaxValue, Capacity)), cancellationToken); + } + + /// + /// Returns the specified token to the bucket. + /// + /// + /// This method should only be called if tokens were retrieved from the bucket, but were not used. + /// + /// If the specified count exceeds the bucket capacity, the count is lowered to the capacity. Effectively this + /// allows the bucket to 'burst' up to 2x capacity to 'catch up' to the desired rate if tokens were wastefully + /// retrieved. + /// + /// If the specified count is negative, no change is made to the available count. + /// + /// The number of tokens to return. + public void Return(int count) + { + CurrentCount += Math.Min(Math.Max(count, 0), Capacity); + } + + /// + /// Sets the bucket capacity to the supplied . + /// + /// Change takes effect on the next reset. + /// The bucket capacity. + public void SetCapacity(long capacity) + { + if (capacity < 1) + { + throw new ArgumentOutOfRangeException(nameof(capacity), "Bucket capacity must be greater than or equal to 1"); + } + + Capacity = capacity; + } + + /// + /// Disposes this instance. + /// + /// A value indicating whether disposal is in progress. + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + Clock.Dispose(); + SyncRoot.Dispose(); + } + + Disposed = true; + } + } + + private async Task GetInternalAsync(int count, CancellationToken cancellationToken = default) + { + Task waitTask = Task.CompletedTask; + + await SyncRoot.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + // if the bucket has enough tokens to fulfil the request, return them and decrement the bucket + if (CurrentCount >= count) + { + CurrentCount -= count; + return count; + } + + // if the bucket doesn't have enough tokens to fulfil the request, but has some available, return the available + // tokens and zero the bucket + if (CurrentCount > 0) + { + var availableCount = CurrentCount; + CurrentCount = 0; + return (int)availableCount; + } + + // if the bucket is empty, make the caller wait until the bucket is replenished + waitTask = WaitForReset.Task; + } + finally + { + SyncRoot.Release(); + } + + await waitTask.ConfigureAwait(false); + return await GetAsync(count, cancellationToken).ConfigureAwait(false); + } + + private async Task Reset() + { + await SyncRoot.WaitAsync().ConfigureAwait(false); + + try + { + CurrentCount = Capacity; + + WaitForReset.SetResult(true); + WaitForReset = new TaskCompletionSource(); + } + finally + { + SyncRoot.Release(); + } + } + } +} -- cgit v1.2.3 From 6df03a2dbe92c84309553661bec24873f5b5d204 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Feb 2022 09:37:04 -0600 Subject: add ToSHA1 --- src/slskd/Common/Extensions.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index ebf16fce..736d8863 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -25,6 +25,7 @@ namespace slskd using System.Net.Sockets; using System.Numerics; using System.Reflection; + using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; @@ -325,6 +326,17 @@ namespace slskd obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); } + /// + /// Returns the SHA1 hash of the input string. + /// + /// The string to hash. + /// The computed SHA1 hash. + public static string ToSHA1(this string str) + { + using var sha = SHA1.Create(); + return BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); + } + /// /// Redacts this instance of Options, replacing properties marked with with '*****'. /// -- cgit v1.2.3 From 9a3358c52c9f31c15c9675d94e4ff2057b6c8e22 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Feb 2022 15:02:10 -0600 Subject: remove redundant sha1 method --- src/slskd/Common/Extensions.cs | 11 ----------- src/slskd/Transfers/Governor.cs | 4 ++-- 2 files changed, 2 insertions(+), 13 deletions(-) (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 736d8863..8b1ead8c 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -326,17 +326,6 @@ namespace slskd obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); } - /// - /// Returns the SHA1 hash of the input string. - /// - /// The string to hash. - /// The computed SHA1 hash. - public static string ToSHA1(this string str) - { - using var sha = SHA1.Create(); - return BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); - } - /// /// Redacts this instance of Options, replacing properties marked with with '*****'. /// diff --git a/src/slskd/Transfers/Governor.cs b/src/slskd/Transfers/Governor.cs index 76fbb1fb..02e0e5bb 100644 --- a/src/slskd/Transfers/Governor.cs +++ b/src/slskd/Transfers/Governor.cs @@ -136,7 +136,7 @@ namespace slskd.Transfers static TokenBucket CreateBucket(int speed) => new(ComputeBucketCapacity(speed), 100); - if (options.Groups.ToJson().ToSHA1() == LastOptionsHash && options.Global.Upload.SpeedLimit == LastGlobalSpeedLimit) + if (Compute.Sha1Hash(options.Groups.ToJson()) == LastOptionsHash && options.Global.Upload.SpeedLimit == LastGlobalSpeedLimit) { return; } @@ -161,7 +161,7 @@ namespace slskd.Transfers TokenBuckets = tokenBuckets; LastGlobalSpeedLimit = options.Global.Upload.SpeedLimit; - LastOptionsHash = options.Groups.ToJson().ToSHA1(); + LastOptionsHash = Compute.Sha1Hash(options.Groups.ToJson()); } } } \ No newline at end of file -- cgit v1.2.3 From 7dd7970bc9fcce6f4aaece6694ddbdb11eaa0f2a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Feb 2022 08:08:25 -0600 Subject: update TokenBucket implementation --- src/slskd/Common/TokenBucket.cs | 54 ++++++++++++----------------------------- 1 file changed, 16 insertions(+), 38 deletions(-) (limited to 'src/slskd/Common') diff --git a/src/slskd/Common/TokenBucket.cs b/src/slskd/Common/TokenBucket.cs index 29fd720c..51a0281b 100644 --- a/src/slskd/Common/TokenBucket.cs +++ b/src/slskd/Common/TokenBucket.cs @@ -77,6 +77,8 @@ namespace slskd /// public class TokenBucket : ITokenBucket, IDisposable { + private TaskCompletionSource waitForReset = new(); + /// /// Initializes a new instance of the class. /// @@ -98,7 +100,7 @@ namespace slskd CurrentCount = Capacity; Clock = new System.Timers.Timer(interval); - Clock.Elapsed += (sender, e) => _ = Reset(); + Clock.Elapsed += (sender, e) => Reset(); Clock.Start(); } @@ -111,7 +113,6 @@ namespace slskd private long CurrentCount { get; set; } private bool Disposed { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private TaskCompletionSource WaitForReset { get; set; } = new TaskCompletionSource(); /// /// Disposes this instance. @@ -196,55 +197,32 @@ namespace slskd private async Task GetInternalAsync(int count, CancellationToken cancellationToken = default) { - Task waitTask = Task.CompletedTask; - await SyncRoot.WaitAsync(cancellationToken).ConfigureAwait(false); try { - // if the bucket has enough tokens to fulfil the request, return them and decrement the bucket - if (CurrentCount >= count) - { - CurrentCount -= count; - return count; - } - - // if the bucket doesn't have enough tokens to fulfil the request, but has some available, return the available - // tokens and zero the bucket - if (CurrentCount > 0) + // if the bucket is empty, wait for a reset, then replenish it before continuing + // this ensures tokens are distributed in the order in which callers obtain the semaphore, + // which is as close to a FIFO as .NET synchronization primitives will allow + if (CurrentCount == 0) { - var availableCount = CurrentCount; - CurrentCount = 0; - return (int)availableCount; + await waitForReset.Task.ConfigureAwait(false); + CurrentCount = Capacity; } - // if the bucket is empty, make the caller wait until the bucket is replenished - waitTask = WaitForReset.Task; + // take the minimum of requested count or CurrentCount, deduct it from + // CurrentCount (potentially zeroing the bucket), and return it + var availableCount = Math.Min(CurrentCount, count); + CurrentCount -= availableCount; + return (int)availableCount; } finally { SyncRoot.Release(); } - - await waitTask.ConfigureAwait(false); - return await GetAsync(count, cancellationToken).ConfigureAwait(false); } - private async Task Reset() - { - await SyncRoot.WaitAsync().ConfigureAwait(false); - - try - { - CurrentCount = Capacity; - - WaitForReset.SetResult(true); - WaitForReset = new TaskCompletionSource(); - } - finally - { - SyncRoot.Release(); - } - } + private void Reset() + => Interlocked.Exchange(ref waitForReset, new TaskCompletionSource()).SetResult(true); } } -- cgit v1.2.3