diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2022-02-18 07:05:03 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-02-18 07:05:03 -0600 |
| commit | fccc9c6440af11fd400f3d1dee243d2d18ea1651 (patch) | |
| tree | 0ba68479205c192e630c985f5025c67d2ca4c715 | |
| parent | dee1b7315ff56194f7868803b876cabe4ab165d7 (diff) | |
| parent | 58e865993eb507e31dca3771fac0ea3829880d02 (diff) | |
| download | slskd-fccc9c6440af11fd400f3d1dee243d2d18ea1651.tar.gz | |
Merge pull request #346 from slskd/groups
Add upload slot and bandwidth limiting for user groups
24 files changed, 2949 insertions, 30 deletions
@@ -4,4 +4,5 @@ logs/ src/slskd/bin/ src/slskd/obj/ src/slskd/wwwroot/ -src/slskd/slskd.csproj.user
\ No newline at end of file +src/slskd/slskd.csproj.user +TestResults/
\ No newline at end of file diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 96671e96..2bf0863b 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -11,9 +11,34 @@ # downloads: ~ # shared: # - ~ -# limits: -# queue: +# global: +# upload: # slots: 20 +# speed_limit: 1000 +# download: +# slots: 500 +# speed_limit: 1000 +# groups: +# default: +# upload: +# priority: 500 +# strategy: roundrobin +# slots: 10 +# leechers: +# upload: +# priority: 999 +# strategy: roundrobin +# slots: 1 +# speed_limit: 100 +# user_defined: +# my_buddies: +# upload: +# priority: 250 +# queue_strategy: firstinfirstout +# slots: 10 +# members: +# - alice +# - bob # filters: # share: # - \.ini$ diff --git a/docs/config.md b/docs/config.md index 47b4bf68..ec682b43 100644 --- a/docs/config.md +++ b/docs/config.md @@ -144,6 +144,142 @@ directories: - ~ ``` +# Limits and User Groups + +## Global + +Global limits behave as a hard limit, additive across all groups. These values should be set as high as practical for the environment in which the application is running; more granular controls should be defined at the group level. + +A change to slot limits require an application restart to take effect, while speed limits can be adjusted at runtime. + +|Command Line|Environment Variable|Description| +|----|-----|-----------| +|`--upload-slots`|`UPLOAD_SLOTS`|The limit for the total number of upload slots| +|`--upload-speed-limit`|`UPLOAD_SPEED_LIMIT`|The total upload speed limit| +|`--download-slots`|`DOWNLOAD_SLOTS`|The limit for the total number of download slots| +|`--download-speed-limit`|`DOWNLOAD_SPEED_LIMIT`|The total download speed limit| + +#### **YAML** +```yaml +global: + upload: + slots: 20 + speed_limit: 1000 + download: + slots: 500 + speed_limit: 1000 +``` + +## Groups + +User groups are used to control upload slots, speed limits and queue behavior on a per-user basis. + +Each group has a priority, starting from 1, that determines the order in which groups are prioritized in the upload queue. A lower number translates to higher priority. Upload slots are granted to higher priority groups before lower priority groups. + +Groups have a queue strategy, which can be either `FirstInFirstOut`, or `RoundRobin`. This setting determines how uploads from multiple users in the same group are processed; `FirstInFirstOut` processes uploads in the order in which they were enqueued, while `RoundRobin` processes uploads in the order in which the user was ready to receive the upload. + +Upload slots and speed limits configured at the group level can be used to create constraints in addition to global settings. If group-level limits exceed global settings, global settings become the constraint. Slots and speed limit settings default to `int.MaxValue`, effectively deferring to the global limits. + +The general configuration for a group is as follows: + +#### **YAML** +```yaml +upload: + priority: 500 # 1 to int.MaxValue + strategy: roundrobin # roundrobin or firstinfirstout + slots: 10 # 1 to int.MaxValue + speed_limit: 100 # in KiB/s, 1 to int.MaxValue +``` + +## Built-In Groups + +The `default` built-in group contains all users that have not been explicitly added to a user defined group, are not priviledged, and that haven't been identified as leechers. + +The `leechers` built-in group contains users that have been identified as leechers. + +The `priviledged` built-in is used to prioritize users who have purchased priviledges on the Soulseek network. This groups is not configurable, has a priority of 0 (the highest), a strategy of `FirstInFirstOut`, and can use any number of slots, up to the global limit. + +It is not possible to explicitly assign users to built-in groups, but the priority, number of slots, speed and queue strategy can be adjusted (excluding `priviledged`). + +#### **YAML** +```yaml +groups: + default: + upload: + priority: 1 + strategy: roundrobin + slots: 10 + speed_limit: 50000 + leechers: + upload: + priority: 99 + strategy: roundrobin + slots: 1 + speed_limit: 100 +``` + +## User Defined Groups + +Any number of user defined groups can be added under the `user_defined` key in the group configuration. + +User defined groups use the same configuration as built-in groups, but additionally allow a list of `members` containing the usernames of the users assigned to the group. + +Users can be assigned to multiple groups, with their effective group being the highest priority (lowest numbered) group. If a user has priviledges on the network, any explicit group membership is superceded, and their effective group is the built-in `priviledged` group. If a user is explcitly assigned to a group, they will not be identified as a leecher. + +#### **YAML*** +```yaml +groups: + user_defined: + my_custom_group_name: + upload: + priority: 500 + strategy: roundrobin + slots: 10 + speed_limit: 100 + members: + - bob + - alice +``` + +## Example + +In the following example: + +* All leechers share 1 slot among them, and can download at a maximum speed of 100 KiB/s. Leechers can only download if there are fewer than 20 other uploads in progress to other users. +* Users that aren't leechers and that aren't in the `my_buddies` group (`default` users) share 10 slots among them and can download at the global maximum speed of 1000 KiB/s, but only if fewer than 20 upload slots are being used by users in the `my_buddies` group. +* Users that are in the `my_buddies` group share 20 slots among them and can download at the global maximum speed. 10 upload slots are reserved for users in this group, and users `alice` and `bob` are members. + +```yaml +global: + upload: + slots: 20 + speed_limit: 1000 + download: + slots: 500 + speed_limit: 1000 +groups: + default: + upload: + priority: 500 + strategy: roundrobin + slots: 10 + leechers: + upload: + priority: 999 + strategy: roundrobin + slots: 1 + speed_limit: 100 + user_defined: + my_buddies: + upload: + priority: 250 + queue_strategy: firstinfirstout + slots: 20 + members: + - alice + - bob +``` + # Soulseek Configuration The Soulseek configuration determines how slskd will interact with the Soulseek network and underlying [Soulseek.NET](https://github.com/jpdillingham/Soulseek.NET) library. diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index f7510f2a..b03f1abd 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -54,6 +54,21 @@ namespace slskd public sealed class Application : IApplication { + /// <summary> + /// The name of the default user group. + /// </summary> + public static readonly string DefaultGroup = "default"; + + /// <summary> + /// The name of the priviledged user group. + /// </summary> + public static readonly string PriviledgedGroup = "priviledged"; + + /// <summary> + /// The name of the leecher user group. + /// </summary> + public static readonly string LeecherGroup = "leechers"; + private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes public Application( @@ -62,6 +77,7 @@ namespace slskd IManagedState<State> state, ISoulseekClient soulseekClient, ITransferTracker transferTracker, + ITransferService transferService, IBrowseTracker browseTracker, IConversationTracker conversationTracker, IRoomTracker roomTracker, @@ -85,6 +101,7 @@ namespace slskd SharedFileCache.StateMonitor.OnChange(state => SharedFileCacheState_OnChange(state)); TransferTracker = transferTracker; + Transfers = transferService; BrowseTracker = browseTracker; ConversationTracker = conversationTracker; Pushbullet = pushbulletService; @@ -137,6 +154,7 @@ namespace slskd private DateTime SharesRefreshStarted { get; set; } private IManagedState<State> State { get; } private ITransferTracker TransferTracker { get; set; } + private ITransferService Transfers { get; init; } private IHubContext<ApplicationHub> ApplicationHub { get; set; } private IHubContext<LogsHub> LogHub { get; set; } @@ -255,6 +273,8 @@ namespace slskd distributedChildLimit: OptionsAtStartup.Soulseek.DistributedNetwork.ChildLimit, enableDistributedNetwork: !OptionsAtStartup.Soulseek.DistributedNetwork.Disabled, acceptDistributedChildren: !OptionsAtStartup.Soulseek.DistributedNetwork.DisableChildren, + maximumUploadSpeed: OptionsAtStartup.Global.Upload.SpeedLimit, + maximumDownloadSpeed: OptionsAtStartup.Global.Download.SpeedLimit, autoAcknowledgePrivateMessages: false, acceptPrivateRoomInvitations: true, serverConnectionOptions: serverOptions, @@ -530,6 +550,8 @@ namespace slskd var fileInfo = new FileInfo(localFilename); + Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]"); + if (!fileInfo.Exists) { Console.WriteLine($"[UPLOAD REJECTED] File {localFilename} not found."); @@ -545,7 +567,21 @@ namespace slskd // create a new cancellation token source so that we can cancel the upload from the UI. var cts = new CancellationTokenSource(); - var topts = new TransferOptions(stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts)); + var topts = new TransferOptions( + stateChanged: (e) => + { + tracker.AddOrUpdate(e, cts); + + if (e.Transfer.State.HasFlag(TransferStates.Queued)) + { + Transfers.Uploads.Queue.Enqueue(e.Transfer); + } + }, + progressUpdated: (e) => tracker.AddOrUpdate(e, cts), + governor: (tx, req, ct) => Transfers.Uploads.Governor.GetBytesAsync(tx, req, ct), + reporter: (tx, att, grant, act) => Transfers.Uploads.Governor.ReturnBytes(tx, att, grant, act), + slotAwaiter: (tx, ct) => Transfers.Uploads.Queue.AwaitStartAsync(tx), + slotReleased: (tx) => Transfers.Uploads.Queue.Complete(tx)); // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and // uploads would be handled separately. @@ -619,8 +655,9 @@ namespace slskd // determine whether any Soulseek options changed. if so, we need to construct a patch and invoke ReconfigureOptionsAsync(). var slskDiff = PreviousOptions.Soulseek.DiffWith(newOptions.Soulseek); + var globalDiff = PreviousOptions.Global.DiffWith(newOptions.Global); - if (slskDiff.Any()) + if (slskDiff.Any() || globalDiff.Any()) { var old = PreviousOptions.Soulseek; var update = newOptions.Soulseek; @@ -681,6 +718,8 @@ namespace slskd enableDistributedNetwork: old.DistributedNetwork.Disabled == update.DistributedNetwork.Disabled ? null : !update.DistributedNetwork.Disabled, distributedChildLimit: old.DistributedNetwork.ChildLimit == update.DistributedNetwork.ChildLimit ? null : update.DistributedNetwork.ChildLimit, acceptDistributedChildren: old.DistributedNetwork.DisableChildren == update.DistributedNetwork.DisableChildren ? null : !update.DistributedNetwork.DisableChildren, + maximumUploadSpeed: newOptions.Global.Upload.SpeedLimit, + maximumDownloadSpeed: newOptions.Global.Download.SpeedLimit, serverConnectionOptions: serverPatch, peerConnectionOptions: connectionPatch, transferConnectionOptions: transferPatch, diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 90f0b659..8b1ead8c 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -18,12 +18,14 @@ namespace slskd { using System; + using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; 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; @@ -308,6 +310,23 @@ namespace slskd } /// <summary> + /// Determines whether the given object is a <see cref="Dictionary{TKey, TValue}"/>. + /// </summary> + /// <param name="obj">The object to check.</param> + /// <returns>A value indicating whether the given object is a dictionary.</returns> + 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<,>)); + } + + /// <summary> /// Redacts this instance of Options, replacing properties marked with <see cref="SecretAttribute"/> with '*****'. /// </summary> /// <remarks> diff --git a/src/slskd/Common/TokenBucket.cs b/src/slskd/Common/TokenBucket.cs new file mode 100644 index 00000000..51a0281b --- /dev/null +++ b/src/slskd/Common/TokenBucket.cs @@ -0,0 +1,228 @@ +// <copyright file="TokenBucket.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd +{ + using System; + using System.Threading; + using System.Threading.Tasks; + + /// <summary> + /// Implements the 'token bucket' or 'leaky bucket' rate limiting algorithm. + /// </summary> + public interface ITokenBucket + { + /// <summary> + /// Gets the bucket capacity. + /// </summary> + public long Capacity { get; } + + /// <summary> + /// Asynchronously retrieves the specified token <paramref name="count"/> from the bucket. + /// </summary> + /// <remarks> + /// <para> + /// If the requested <paramref name="count"/> exceeds the bucket <see cref="Capacity"/>, the request is lowered to + /// the capacity of the bucket. + /// </para> + /// <para>If the bucket has tokens available, but fewer than the requested amount, the available tokens are returned.</para> + /// <para> + /// If the bucket has no tokens available, execution waits for the bucket to be replenished before servicing the request. + /// </para> + /// </remarks> + /// <param name="count">The number of tokens to retrieve.</param> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + /// <returns>A Task that completes when tokens have been provided.</returns> + Task<int> GetAsync(int count, CancellationToken cancellationToken = default); + + /// <summary> + /// Returns the specified token <paramref name="count"/> to the bucket. + /// </summary> + /// <remarks> + /// <para>This method should only be called if tokens were retrieved from the bucket, but were not used.</para> + /// <para> + /// 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. + /// </para> + /// <para>If the specified count is negative, no change is made to the available count.</para> + /// </remarks> + /// <param name="count">The number of tokens to return.</param> + void Return(int count); + + /// <summary> + /// Sets the bucket capacity to the supplied <paramref name="capacity"/>. + /// </summary> + /// <remarks>Change takes effect on the next reset.</remarks> + /// <param name="capacity">The bucket capacity.</param> + void SetCapacity(long capacity); + } + + /// <summary> + /// Implements the 'token bucket' or 'leaky bucket' rate limiting algorithm. + /// </summary> + public class TokenBucket : ITokenBucket, IDisposable + { + private TaskCompletionSource<bool> waitForReset = new(); + + /// <summary> + /// Initializes a new instance of the <see cref="TokenBucket"/> class. + /// </summary> + /// <param name="capacity">The bucket capacity.</param> + /// <param name="interval">The interval at which tokens are replenished.</param> + 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(); + } + + /// <summary> + /// Gets the bucket capacity. + /// </summary> + 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); + + /// <summary> + /// Disposes this instance. + /// </summary> + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// <summary> + /// Asynchronously retrieves the specified token <paramref name="count"/> from the bucket. + /// </summary> + /// <remarks> + /// <para> + /// If the requested <paramref name="count"/> exceeds the bucket <see cref="Capacity"/>, the request is lowered to + /// the capacity of the bucket. + /// </para> + /// <para>If the bucket has tokens available, but fewer than the requested amount, the available tokens are returned.</para> + /// <para> + /// If the bucket has no tokens available, execution waits for the bucket to be replenished before servicing the request. + /// </para> + /// </remarks> + /// <param name="count">The number of tokens to retrieve.</param> + /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> + /// <returns>A Task that completes when tokens have been provided.</returns> + public Task<int> GetAsync(int count, CancellationToken cancellationToken = default) + { + return GetInternalAsync(Math.Min(count, (int)Math.Min(int.MaxValue, Capacity)), cancellationToken); + } + + /// <summary> + /// Returns the specified token <paramref name="count"/> to the bucket. + /// </summary> + /// <remarks> + /// <para>This method should only be called if tokens were retrieved from the bucket, but were not used.</para> + /// <para> + /// 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. + /// </para> + /// <para>If the specified count is negative, no change is made to the available count.</para> + /// </remarks> + /// <param name="count">The number of tokens to return.</param> + public void Return(int count) + { + CurrentCount += Math.Min(Math.Max(count, 0), Capacity); + } + + /// <summary> + /// Sets the bucket capacity to the supplied <paramref name="capacity"/>. + /// </summary> + /// <remarks>Change takes effect on the next reset.</remarks> + /// <param name="capacity">The bucket capacity.</param> + 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; + } + + /// <summary> + /// Disposes this instance. + /// </summary> + /// <param name="disposing">A value indicating whether disposal is in progress.</param> + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + Clock.Dispose(); + SyncRoot.Dispose(); + } + + Disposed = true; + } + } + + private async Task<int> GetInternalAsync(int count, CancellationToken cancellationToken = default) + { + await SyncRoot.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + // 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) + { + await waitForReset.Task.ConfigureAwait(false); + CurrentCount = Capacity; + } + + // 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(); + } + } + + private void Reset() + => Interlocked.Exchange(ref waitForReset, new TaskCompletionSource<bool>()).SetResult(true); + } +} 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; /// <summary> /// Indicates that attributed properties should be recursively validated. @@ -35,6 +37,30 @@ namespace slskd.Validation var results = new List<ValidationResult>(); 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) diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 900f2cd4..2313ce69 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -228,10 +228,16 @@ namespace slskd public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions(); /// <summary> - /// Gets limits. + /// Gets global options. /// </summary> [Validate] - public LimitsOptions Limits { get; init; } = new LimitsOptions(); + public GlobalOptions Global { get; init; } = new GlobalOptions(); + + /// <summary> + /// Gets user groups. + /// </summary> + [Validate] + public GroupsOptions Groups { get; init; } = new GroupsOptions(); /// <summary> /// Gets filter options. @@ -385,30 +391,173 @@ namespace slskd } /// <summary> - /// Limits. + /// Global options. /// </summary> - public class LimitsOptions + public class GlobalOptions { /// <summary> - /// Gets queue limits. + /// Gets global upload options. + /// </summary> + [Validate] + public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions(); + + /// <summary> + /// Gets global download options. /// </summary> [Validate] - public LimitsQueueOptions Queue { get; init; } = new LimitsQueueOptions(); + public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions(); /// <summary> - /// Queue limits. + /// Global upload options. /// </summary> - public class LimitsQueueOptions + public class GlobalUploadOptions { /// <summary> - /// Gets the limit for the total number of queue slots. + /// Gets the limit for the total number of upload slots. /// </summary> - [Argument(default, "queue-slot-limit")] - [EnvironmentVariable("QUEUE_SLOT_LIMIT")] - [Description("the limit for the total number of queue slots")] + [Argument(default, "upload-slots")] + [EnvironmentVariable("UPLOAD_SLOTS")] + [Description("the total number of upload slots")] [RequiresRestart] [Range(1, int.MaxValue)] public int Slots { get; init; } = 10; + + /// <summary> + /// Gets the total upload speed limit. + /// </summary> + [Argument(default, "upload-speed-limit")] + [EnvironmentVariable("UPLOAD_SPEED_LIMIT")] + [Description("the total upload speed limit")] + [Range(1, int.MaxValue)] + public int SpeedLimit { get; init; } = int.MaxValue; + } + + /// <summary> + /// Gets global download options. + /// </summary> + public class GlobalDownloadOptions + { + /// <summary> + /// Gets the limit for the total number of download slots. + /// </summary> + [Argument(default, "download-slots")] + [EnvironmentVariable("DOWNLOAD_SLOTS")] + [Description("the total number of download slots")] + [RequiresRestart] + [Range(1, int.MaxValue)] + public int Slots { get; init; } = int.MaxValue; + + /// <summary> + /// Gets the total download speed limit. + /// </summary> + [Argument(default, "download-speed-limit")] + [EnvironmentVariable("DOWNLOAD_SPEED_LIMIT")] + [Description("the total download speed limit")] + [Range(1, int.MaxValue)] + public int SpeedLimit { get; init; } = int.MaxValue; + } + } + + /// <summary> + /// User groups. + /// </summary> + public class GroupsOptions : IValidatableObject + { + /// <summary> + /// Gets options for the default user group. + /// </summary> + /// <remarks> + /// These options apply to users that are not priviledged, have not been identified as leechers, + /// and have not been added as a member of any group. + /// </remarks> + [Validate] + public BuiltInOptions Default { get; init; } = new BuiltInOptions(); + + /// <summary> + /// Gets options for the leecher user group. + /// </summary> + /// <remarks> + /// These options apply to users that have been identified as leechers, and have not been added as a member of any group. + /// </remarks> + [Validate] + public BuiltInOptions Leechers { get; init; } = new BuiltInOptions(); + + /// <summary> + /// Gets user defined groups and options. + /// </summary> + [Validate] + public Dictionary<string, UserDefinedOptions> UserDefined { get; init; } = new Dictionary<string, UserDefinedOptions>(); + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var builtInGroups = new[] { Application.PriviledgedGroup, Application.DefaultGroup, Application.LeecherGroup }; + var intersection = UserDefined.Keys.Intersect(builtInGroups); + + return intersection.Select(group => new ValidationResult($"User defined group '{group}' collides with a built in group. Choose a different name.")); + } + + /// <summary> + /// Built in user group options. + /// </summary> + public class BuiltInOptions + { + /// <summary> + /// Gets upload options. + /// </summary> + [Validate] + public UploadOptions Upload { get; init; } = new UploadOptions(); + } + + /// <summary> + /// User defined user group options. + /// </summary> + public class UserDefinedOptions + { + /// <summary> + /// Gets upload options. + /// </summary> + [Validate] + public UploadOptions Upload { get; init; } = new UploadOptions(); + + /// <summary> + /// Gets the list of group member usernames. + /// </summary> + public string[] Members { get; init; } = Array.Empty<string>(); + } + + /// <summary> + /// User group upload options. + /// </summary> + public class UploadOptions + { + /// <summary> + /// Gets the priority of the group. + /// </summary> + [Range(1, int.MaxValue)] + public int Priority { get; init; } = 1; + + /// <summary> + /// Gets the queue strategy for the group. + /// </summary> + [Enum(typeof(QueueStrategy))] + public string Strategy { get; init; } = QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); + + /// <summary> + /// Gets the limit for the total number of upload slots for the group. + /// </summary> + [Range(1, int.MaxValue)] + public int Slots { get; init; } = int.MaxValue; + + /// <summary> + /// Gets the total upload speed limit for the group. + /// </summary> + [Range(1, int.MaxValue)] + public int SpeedLimit { get; init; } = int.MaxValue; } } @@ -972,7 +1121,7 @@ namespace slskd [EnvironmentVariable("FTP_ENCRYPTION_MODE")] [Description("FTP encryption mode; none, implicit, explicit, auto")] [Enum(typeof(FtpEncryptionMode))] - public string EncryptionMode { get; init; } = "auto"; + public string EncryptionMode { get; init; } = FtpEncryptionMode.Auto.ToString().ToLowerInvariant(); /// <summary> /// Gets a value indicating whether FTP certificate errors should be ignored. diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 200a23fc..b1af2482 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -235,7 +235,8 @@ namespace slskd // complete configuration at startup. services.AddSingleton<ISoulseekClient, SoulseekClient>(_ => new SoulseekClient(options: new SoulseekClientOptions( - maximumConcurrentUploads: OptionsAtStartup.Limits.Queue.Slots, + maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, + maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots, minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel))); // add the core application service to DI as well as a hosted service so that other services can @@ -253,6 +254,7 @@ namespace slskd services.AddSingleton<ISearchService, SearchService>(); services.AddSingleton<IUserService, UserService>(); services.AddSingleton<IRoomService, RoomService>(); + services.AddSingleton<ITransferService, TransferService>(); services.AddSingleton<IFTPClientFactory, FTPClientFactory>(); services.AddSingleton<IFTPService, FTPService>(); diff --git a/src/slskd/Transfers/TransferService.cs b/src/slskd/Transfers/TransferService.cs new file mode 100644 index 00000000..714d85be --- /dev/null +++ b/src/slskd/Transfers/TransferService.cs @@ -0,0 +1,70 @@ +// <copyright file="TransferService.cs" company="slskd Team"> +// 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/. +// </copyright> + +using Microsoft.Extensions.Options; + +namespace slskd.Transfers +{ + using slskd.Transfers.Uploads; + using slskd.Users; + + /// <summary> + /// Manages transfers. + /// </summary> + public interface ITransferService + { + /// <summary> + /// Gets the upload service. + /// </summary> + IUploadService Uploads { get; } + } + + /// <summary> + /// Manages transfers. + /// </summary> + public class TransferService : ITransferService + { + /// <summary> + /// Initializes a new instance of the <see cref="TransferService"/> class. + /// </summary> + /// <param name="userService">The UserService instance to use.</param> + /// <param name="optionsMonitor">The OptionsMonitor instance to use.</param> + /// <param name="uploadService">The optional UploadService instance to use.</param> + public TransferService( + IUserService userService, + IOptionsMonitor<Options> optionsMonitor, + IUploadService uploadService = null) + { + Users = userService; + OptionsMonitor = optionsMonitor; + + Uploads = uploadService ?? new UploadService() + { + Governor = new UploadGovernor(userService: Users, optionsMonitor: OptionsMonitor), + Queue = new UploadQueue(userService: Users, optionsMonitor: OptionsMonitor), + }; + } + + /// <summary> + /// Gets the upload service. + /// </summary> + public IUploadService Uploads { get; init; } + + private IOptionsMonitor<Options> OptionsMonitor { get; init; } + private IUserService Users { get; init; } + } +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadGovernor.cs b/src/slskd/Transfers/Uploads/UploadGovernor.cs new file mode 100644 index 00000000..9221d686 --- /dev/null +++ b/src/slskd/Transfers/Uploads/UploadGovernor.cs @@ -0,0 +1,169 @@ +// <copyright file="UploadGovernor.cs" company="slskd Team"> +// 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/. +// </copyright> + +using Microsoft.Extensions.Options; + +namespace slskd.Transfers +{ + using System; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using slskd.Users; + using Soulseek; + + /// <summary> + /// Governs upload transfer speed. + /// </summary> + public interface IUploadGovernor + { + /// <summary> + /// Asynchronously obtains a grant of <paramref name="requestedBytes"/> for the specified <paramref name="transfer"/>. + /// </summary> + /// <remarks> + /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the + /// requested amount. + /// </remarks> + /// <param name="transfer">The transfer for which the grant is requested.</param> + /// <param name="requestedBytes">The number of requested bytes.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</param> + /// <returns>The operation context, including the number of bytes granted.</returns> + Task<int> GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken); + + /// <summary> + /// Returns wasted bytes for redistribution. + /// </summary> + /// <param name="transfer">The transfer which generated the waste.</param> + /// <param name="attemptedBytes">The number of bytes that were attempted to be transferred.</param> + /// <param name="grantedBytes">The number of bytes granted by all governors in the system.</param> + /// <param name="actualBytes">The actual number of bytes transferred.</param> + public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes); + } + + /// <summary> + /// Governs upload transfer speed. + /// </summary> + public class UploadGovernor : IUploadGovernor + { + /// <summary> + /// Initializes a new instance of the <see cref="UploadGovernor"/> class. + /// </summary> + /// <param name="userService">The UserService instance to use.</param> + /// <param name="optionsMonitor">The OptionsMonitor instance to use.</param> + public UploadGovernor( + IUserService userService, + IOptionsMonitor<Options> optionsMonitor) + { + Users = userService; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(Configure); + + Configure(OptionsMonitor.CurrentValue); + } + + private IOptionsMonitor<Options> OptionsMonitor { get; } + private string LastOptionsHash { get; set; } + private int LastGlobalSpeedLimit { get; set; } + private Dictionary<string, ITokenBucket> TokenBuckets { get; set; } = new Dictionary<string, ITokenBucket>(); + private IUserService Users { get; } + + /// <summary> + /// Asynchronously obtains a grant of <paramref name="requestedBytes"/> for the specified <paramref name="transfer"/>. + /// </summary> + /// <remarks> + /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the + /// requested amount. + /// </remarks> + /// <param name="transfer">The transfer for which the grant is requested.</param> + /// <param name="requestedBytes">The number of requested bytes.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</param> + /// <returns>The operation context, including the number of bytes granted.</returns> + public Task<int> GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) + { + var group = Users.GetGroup(transfer.Username); + var bucket = TokenBuckets.GetValueOrDefault(group ?? string.Empty, TokenBuckets[Application.DefaultGroup]); + + return bucket.GetAsync(requestedBytes, cancellationToken); + } + + /// <summary> + /// Returns wasted bytes for redistribution. + /// </summary> + /// <param name="transfer">The transfer which generated the waste.</param> + /// <param name="attemptedBytes">The number of bytes that were attempted to be transferred.</param> + /// <param name="grantedBytes">The number of bytes granted by all governors in the system.</param> + /// <param name="actualBytes">The actual number of bytes transferred.</param> + public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes) + { + var waste = Math.Max(0, grantedBytes - actualBytes); + + if (waste == 0) + { + return; + } + + var group = Users.GetGroup(transfer.Username); + var bucket = TokenBuckets.GetValueOrDefault(group ?? string.Empty, TokenBuckets[Application.DefaultGroup]); + + // we don't have enough information to tell whether grantedBytes was reduced by the global limiter within + // Soulseek.NET, so we just return the bytes that we know for sure that were wasted, which is grantedBytes - actualBytes. + // example: we grant 1000 bytes. Soulseek.NET grants only 500. 250 bytes are written. ideally we would return 750 + // bytes, but instead we return 250. this discrepancy doesn't really matter because Soulseek.NET is the constraint in + // this scenario and the additional tokens we would return would never be used. + bucket.Return(waste); + } + + private void Configure(Options options) + { + static long ComputeBucketCapacity(int speed) + => speed * 1024L / 10; + + static TokenBucket CreateBucket(int speed) + => new(ComputeBucketCapacity(speed), 100); + + var optionsHash = Compute.Sha1Hash(options.Groups.ToJson()); + + if (optionsHash == LastOptionsHash && options.Global.Upload.SpeedLimit == LastGlobalSpeedLimit) + { + return; + } + + // build a new dictionary of token buckets based on the current groups, then + // swap it in for the existing dictionary. there's risk of inaccuracy here if + // groups are deleted or users are moved around, as bytes may be taken from or returned + // to the wrong bucket. this is acceptable. reconfiguring buckets replenishes them, + // also, so transfers in progress will briefly exceed the intended speeds. + var tokenBuckets = new Dictionary<string, ITokenBucket>() + { + { Application.PriviledgedGroup, CreateBucket(options.Global.Upload.SpeedLimit) }, + { Application.DefaultGroup, CreateBucket(options.Groups.Default.Upload.SpeedLimit) }, + { Application.LeecherGroup, CreateBucket(options.Groups.Leechers.Upload.SpeedLimit) }, + }; + + foreach (var group in options.Groups.UserDefined) + { + tokenBuckets.Add(group.Key, CreateBucket(group.Value.Upload.SpeedLimit)); + } + + TokenBuckets = tokenBuckets; + + LastGlobalSpeedLimit = options.Global.Upload.SpeedLimit; + LastOptionsHash = optionsHash; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs new file mode 100644 index 00000000..44aa8af4 --- /dev/null +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -0,0 +1,370 @@ +// <copyright file="UploadQueue.cs" company="slskd Team"> +// 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/. +// </copyright> + +using Microsoft.Extensions.Options; + +namespace slskd.Transfers +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using Serilog; + using slskd.Users; + using Soulseek; + + /// <summary> + /// Orchestrates uploads. + /// </summary> + public interface IUploadQueue + { + /// <summary> + /// Enqueues an upload. + /// </summary> + /// <param name="transfer">The upload to enqueue.</param> + void Enqueue(Transfer transfer); + + /// <summary> + /// Awaits the start of an upload. + /// </summary> + /// <param name="transfer">The upload for which to wait.</param> + /// <returns>The operation context.</returns> + Task AwaitStartAsync(Transfer transfer); + + /// <summary> + /// Signals the completion of an upload. + /// </summary> + /// <param name="transfer">The completed upload.</param> + void Complete(Transfer transfer); + } + + /// <summary> + /// Orchestrates uploads. + /// </summary> + public class UploadQueue : IUploadQueue + { + /// <summary> + /// Initializes a new instance of the <see cref="UploadQueue"/> class. + /// </summary> + /// <param name="userService">The UserService instance to use.</param> + /// <param name="optionsMonitor">The OptionsMonitor instance to use.</param> + public UploadQueue( + IUserService userService, + IOptionsMonitor<Options> optionsMonitor) + { + Users = userService; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(Configure); + + Configure(OptionsMonitor.CurrentValue); + } + + private ILogger Log { get; } = Serilog.Log.ForContext<UploadQueue>(); + private IUserService Users { get; } + private IOptionsMonitor<Options> OptionsMonitor { get; } + private string LastOptionsHash { get; set; } + private int LastGlobalSlots { get; set; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private int MaxSlots { get; set; } = 0; + private Dictionary<string, Group> Groups { get; set; } = new Dictionary<string, Group>(); + private ConcurrentDictionary<string, List<Upload>> Uploads { get; set; } = new ConcurrentDictionary<string, List<Upload>>(); + + /// <summary> + /// Enqueues an upload. + /// </summary> + /// <param name="transfer">The upload to enqueue.</param> + public void Enqueue(Transfer transfer) + { + SyncRoot.Wait(); + + try + { + var upload = new Upload() { Username = transfer.Username, Filename = transfer.Filename }; + + Uploads.AddOrUpdate( + key: transfer.Username, + addValue: new List<Upload>(new[] { upload }), + updateValueFactory: (key, list) => + { + list.Add(upload); + return list; + }); + + Log.Debug("Enqueued: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + /// <summary> + /// Awaits the start of an upload. + /// </summary> + /// <param name="transfer">The upload for which to wait.</param> + /// <returns>The operation context.</returns> + public Task AwaitStartAsync(Transfer transfer) + { + SyncRoot.Wait(); + + try + { + if (!Uploads.TryGetValue(transfer.Username, out var list)) + { + throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); + } + + var upload = list.FirstOrDefault(e => e.Filename == transfer.Filename); + + if (upload == default) + { + throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + } + + upload.Ready = DateTime.UtcNow; + Log.Debug("Ready: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); + + return upload.TaskCompletionSource.Task; + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + /// <summary> + /// Signals the completion of an upload. + /// </summary> + /// <param name="transfer">The completed upload.</param> + public void Complete(Transfer transfer) + { + SyncRoot.Wait(); + + try + { + if (!Uploads.TryGetValue(transfer.Username, out var list)) + { + throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); + } + + var upload = list.FirstOrDefault(e => e.Filename == transfer.Filename); + + if (upload == default) + { + throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + } + + list.Remove(upload); + Log.Debug("Complete: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); + + // ensure the slot is returned to the group from which it was acquired + // the group may have been removed during the transfer. if so, do nothing. + if (Groups.ContainsKey(upload.Group ?? string.Empty)) + { + var group = Groups[upload.Group]; + + group.UsedSlots = Math.Max(0, group.UsedSlots - 1); + Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); + } + + if (!list.Any() && Uploads.TryRemove(transfer.Username, out _)) + { + Log.Debug("Cleaned up tracking list for {User}; no more queued uploads to track", transfer.Username); + } + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + private Upload Process() + { + SyncRoot.Wait(); + + try + { + if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots) + { + return null; + } + + // flip the uploads dictionary so that it is keyed by group instead of user. + // wait until just before we process the queue to do this, and fetch each user's + // group as we do, to allow users to move between groups at run time. we delay + // "pinning" an upload to a group (via UsedSlots, below) for the same reason. + var readyUploadsByGroup = Uploads.Aggregate( + seed: new ConcurrentDictionary<string, List<Upload>>(), + func: (groups, user) => + { + var ready = user.Value.Where(u => u.Ready.HasValue && !u.Started.HasValue); + + if (ready.Any()) + { + var group = Users.GetGroup(user.Key); + + groups.AddOrUpdate( + key: group, + addValue: new List<Upload>(ready), + updateValueFactory: (group, list) => + { + list.AddRange(ready); + return list; + }); + } + + return groups; + }); + + // process each group in ascending order of priority, and stop after the first + // ready upload is released. + foreach (var group in Groups.Values.OrderBy(g => g.Priority).ThenBy(g => g.Name)) + { + if (group.UsedSlots >= group.Slots || !readyUploadsByGroup.TryGetValue(group.Name, out var uploads) || !uploads.Any()) + { + continue; + } + + var upload = uploads + .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) + .First(); + + // mark the upload as started, and "pin" it to the group from which + // the slot is obtained, so the slot can be returned to the proper place + // upon completion + upload.Started = DateTime.UtcNow; + upload.Group = group.Name; + group.UsedSlots++; + + // release the upload + upload.TaskCompletionSource.SetResult(); + Log.Debug("Started: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); + Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); + + return upload; + } + + return null; + } + finally + { + SyncRoot.Release(); + } + } + + private void Configure(Options options) + { + int GetExistingUsedSlotsOrDefault(string group) + => Groups.ContainsKey(group) ? Groups[group].UsedSlots : 0; + + SyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(options.Groups.ToJson()); + + if (optionsHash == LastOptionsHash && options.Global.Upload.Slots == LastGlobalSlots) + { + return; + } + + MaxSlots = options.Global.Upload.Slots; + + // statically add built-in groups + var groups = new List<Group>() + { + // the priority group is hard-coded with priority 0, slot count equivalent to the overall max, + // and a FIFO strategy. all other groups have a minimum priority of 1 (enforced by options validation) + // to ensure that priviledged users always take priority, regardless of user configuration. + // the strategy is fixed to FIFO because that gives priviledged users the closest experience + // to the official client, as well as the appearance of fairness once the first upload begins. + new Group() + { + Name = Application.PriviledgedGroup, + Priority = 0, + Slots = MaxSlots, + UsedSlots = GetExistingUsedSlotsOrDefault(Application.PriviledgedGroup), + Strategy = QueueStrategy.FirstInFirstOut, + }, + new Group() + { + Name = Application.DefaultGroup, + Priority = options.Groups.Default.Upload.Priority, + Slots = options.Groups.Default.Upload.Slots, + UsedSlots = GetExistingUsedSlotsOrDefault(Application.DefaultGroup), + Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Default.Upload.Strategy, true), + }, + new Group() + { + Name = Application.LeecherGroup, + Priority = options.Groups.Leechers.Upload.Priority, + Slots = options.Groups.Leechers.Upload.Slots, + UsedSlots = GetExistingUsedSlotsOrDefault(Application.LeecherGroup), + Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Leechers.Upload.Strategy, true), + }, + }; + + // dynamically add user-defined groups + groups.AddRange(options.Groups.UserDefined.Select(kvp => new Group() + { + Name = kvp.Key, + Priority = kvp.Value.Upload.Priority, + Slots = kvp.Value.Upload.Slots, + UsedSlots = GetExistingUsedSlotsOrDefault(kvp.Key), + Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), kvp.Value.Upload.Strategy, true), + })); + + Groups = groups.ToDictionary(g => g.Name); + + LastGlobalSlots = options.Global.Upload.Slots; + LastOptionsHash = optionsHash; + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + public sealed class Group + { + public string Name { get; set; } + public int Slots { get; set; } + public int Priority { get; set; } + public QueueStrategy Strategy { get; set; } + public int UsedSlots { get; set; } + } + + public sealed class Upload + { + public string Username { get; set; } + public string Filename { get; set; } + public string Group { get; set; } + public DateTime Enqueued { get; set; } = DateTime.UtcNow; + public DateTime? Ready { get; set; } = null; + public DateTime? Started { get; set; } = null; + public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource(); + } + } +} diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs new file mode 100644 index 00000000..99f12df4 --- /dev/null +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -0,0 +1,34 @@ +namespace slskd.Transfers.Uploads +{ + /// <summary> + /// Manages uploads. + /// </summary> + public interface IUploadService + { + /// <summary> + /// Gets the upload governor. + /// </summary> + IUploadGovernor Governor { get; } + + /// <summary> + /// Gets the upload queue. + /// </summary> + IUploadQueue Queue { get; } + } + + /// <summary> + /// Manages uploads. + /// </summary> + public class UploadService : IUploadService + { + /// <summary> + /// Gets the upload governor. + /// </summary> + public IUploadGovernor Governor { get; init; } + + /// <summary> + /// Gets the upload queue. + /// </summary> + public IUploadQueue Queue { get; init; } + } +} diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index 469acef6..ad368c65 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -26,6 +26,13 @@ namespace slskd.Users public interface IUserService { /// <summary> + /// Gets the name of the group for the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>The group for the specified username.</returns> + string GetGroup(string username); + + /// <summary> /// Retrieves peer <see cref="Info"/>. /// </summary> /// <param name="username">The username of the peer.</param> diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index f52f19f1..cb56e6dd 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -15,13 +15,18 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using Microsoft.Extensions.Options; + namespace slskd.Users { using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Logging; + using Serilog; using Soulseek; /// <summary> @@ -36,20 +41,37 @@ namespace slskd.Users /// </summary> /// <param name="soulseekClient"></param> /// <param name="contextFactory">The database context to use.</param> - /// <param name="log">The logger.</param> + /// <param name="optionsMonitor"></param> public UserService( ISoulseekClient soulseekClient, IDbContextFactory<UserDbContext> contextFactory, - ILogger<UserService> log) + IOptionsMonitor<Options> optionsMonitor) { Client = soulseekClient; ContextFactory = contextFactory; - Log = log; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(Configure); + + Configure(OptionsMonitor.CurrentValue); } private ISoulseekClient Client { get; } private IDbContextFactory<UserDbContext> ContextFactory { get; } - private ILogger<UserService> Log { get; set; } + private string LastOptionsHash { get; set; } + private ILogger Log { get; set; } = Serilog.Log.ForContext<UserService>(); + private ConcurrentDictionary<string, string> Map { get; set; } = new ConcurrentDictionary<string, string>(); + private IOptionsMonitor<Options> OptionsMonitor { get; } + + /// <summary> + /// Gets the name of the group for the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of the peer.</param> + /// <returns>The group for the specified username.</returns> + public string GetGroup(string username) + { + return Map.GetValueOrDefault(username ?? string.Empty, Application.DefaultGroup); + } /// <summary> /// Retrieves peer <see cref="Info"/>. @@ -134,5 +156,31 @@ namespace slskd.Users { await Client.AddUserAsync(username); } + + private void Configure(Options options) + { + var optionsHash = Compute.Sha1Hash(options.Groups.UserDefined.ToJson()); + + if (optionsHash == LastOptionsHash) + { + return; + } + + var map = new ConcurrentDictionary<string, string>(); + + // sort by priority, ascending + foreach (var group in options.Groups.UserDefined.OrderBy(kvp => kvp.Value.Upload.Priority)) + { + foreach (var user in group.Value.Members) + { + // if the key already exists, leave the existing entry. if a user appears in more than one group, the higher + // priority (lower numbered) group is their effective group. + map.TryAdd(user, group.Key); + } + } + + Map = map; + LastOptionsHash = optionsHash; + } } }
\ No newline at end of file diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index f826d013..e04859ff 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -69,7 +69,7 @@ <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Soulseek" Version="4.4.2" /> + <PackageReference Include="Soulseek" Version="4.4.3" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.354"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> diff --git a/tests/slskd.Tests.Unit/Common/ComputeTests.cs b/tests/slskd.Tests.Unit/Common/ComputeTests.cs index 5a7922f6..021d4faa 100644 --- a/tests/slskd.Tests.Unit/Common/ComputeTests.cs +++ b/tests/slskd.Tests.Unit/Common/ComputeTests.cs @@ -1,4 +1,4 @@ -namespace slskd.Tests.Unit +namespace slskd.Tests.Unit.Common { using Xunit; diff --git a/tests/slskd.Tests.Unit/Common/TokenBucketTests.cs b/tests/slskd.Tests.Unit/Common/TokenBucketTests.cs new file mode 100644 index 00000000..fcd6c290 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/TokenBucketTests.cs @@ -0,0 +1,207 @@ +namespace slskd.Tests.Unit.Common +{ + using System; + using System.Threading.Tasks; + using AutoFixture.Xunit2; + using Xunit; + + public class TokenBucketTests + { + [Trait("Category", "Instantiation")] + [Fact(DisplayName = "Throws ArgumentOutOfRangeException given 0 count")] + public void Throws_ArgumentOutOfRangeException_Given_0_Count() + { + var ex = Record.Exception(() => new TokenBucket(0, 1000)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentOutOfRangeException>(ex); + Assert.Equal("capacity", ((ArgumentOutOfRangeException)ex).ParamName); + } + + [Trait("Category", "Instantiation")] + [Fact(DisplayName = "Throws ArgumentOutOfRangeException given negative count")] + public void Throws_ArgumentOutOfRangeException_Given_Negative_Count() + { + var ex = Record.Exception(() => new TokenBucket(-1, 1000)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentOutOfRangeException>(ex); + Assert.Equal("capacity", ((ArgumentOutOfRangeException)ex).ParamName); + } + + [Trait("Category", "Instantiation")] + [Fact(DisplayName = "Throws ArgumentOutOfRangeException given 0 interval")] + public void Throws_ArgumentOutOfRangeException_Given_0_Interval() + { + var ex = Record.Exception(() => new TokenBucket(1000, 0)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentOutOfRangeException>(ex); + Assert.Equal("interval", ((ArgumentOutOfRangeException)ex).ParamName); + } + + [Trait("Category", "Instantiation")] + [Fact(DisplayName = "Throws ArgumentOutOfRangeException given negative interval")] + public void Throws_ArgumentOutOfRangeException_Given_Negative_Interval() + { + var ex = Record.Exception(() => new TokenBucket(1000, -1)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentOutOfRangeException>(ex); + Assert.Equal("interval", ((ArgumentOutOfRangeException)ex).ParamName); + } + + [Trait("Category", "Instantiation")] + [Theory(DisplayName = "Sets properties"), AutoData] + public void Sets_Properties(int count, int interval) + { + using (var t = new TokenBucket(count, interval)) + { + Assert.Equal(count, t.Capacity); + Assert.Equal(interval, t.GetProperty<System.Timers.Timer>("Clock").Interval); + Assert.Equal(count, t.GetProperty<long>("CurrentCount")); + } + } + + [Trait("Category", "SetCount")] + [Fact(DisplayName = "SetCount throws ArgumentOutOfRangeException given 0 count")] + public void SetCount_Throws_ArgumentOutOfRangeException_Given_0_Count() + { + using (var t = new TokenBucket(10, 1000)) + { + var ex = Record.Exception(() => t.SetCapacity(0)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentOutOfRangeException>(ex); + Assert.Equal("capacity", ((ArgumentOutOfRangeException)ex).ParamName); + } + } + + [Trait("Category", "SetCount")] + [Fact(DisplayName = "SetCount throws ArgumentOutOfRangeException given negative count")] + public void SetCount_Throws_ArgumentOutOfRangeException_Given_Negative_Count() + { + using (var t = new TokenBucket(10, 1000)) + { + var ex = Record.Exception(() => t.SetCapacity(-1)); + + Assert.NotNull(ex); + Assert.IsType<ArgumentOutOfRangeException>(ex); + Assert.Equal("capacity", ((ArgumentOutOfRangeException)ex).ParamName); + } + } + + [Trait("Category", "SetCapacity")] + [Theory(DisplayName = "SetCapacity sets capacity"), AutoData] + public void SetCapacity_Sets_Capacity(int count) + { + using (var t = new TokenBucket(10, 1000)) + { + t.SetCapacity(count); + + Assert.Equal(count, t.Capacity); + } + } + + [Trait("Category", "GetAsync")] + [Fact(DisplayName = "GetAsync decrements count by requested count")] + public async Task GetAsync_Decrements_Count_By_Requested_Count() + { + using (var t = new TokenBucket(10, 10000)) + { + await t.GetAsync(5); + + Assert.Equal(5, t.GetProperty<long>("CurrentCount")); + } + } + + [Trait("Category", "GetAsync")] + [Fact(DisplayName = "GetAsync returns capacity if request exceeds capacity")] + public async Task GetAsync_Returns_Capacity_If_Request_Exceeds_Capacity() + { + using (var t = new TokenBucket(10, 10000)) + { + int tokens = 0; + var ex = await Record.ExceptionAsync(async () => tokens = await t.GetAsync(11)); + + Assert.Null(ex); + Assert.Equal(10, tokens); + } + } + + [Trait("Category", "GetAsync")] + [Fact(DisplayName = "GetAsync returns available tokens if request exceeds available count")] + public async Task GetAsync_Returns_Available_Tokens_If_Request_Exceeds_Available_Count() + { + using (var t = new TokenBucket(10, 10000)) + { + await t.GetAsync(6); + var count = await t.GetAsync(6); + + Assert.Equal(4, count); + } + } + + [Trait("Category", "GetAsync")] + [Fact(DisplayName = "GetAsync waits for reset if bucket is depleted")] + public async Task GetAsync_Waits_For_Reset_If_Bucket_Is_Depleted() + { + using (var t = new TokenBucket(1, 10)) + { + await t.GetAsync(1); + await t.GetAsync(1); + await t.GetAsync(1); + + Assert.True(true); + } + } + + [Trait("Category", "Return")] + [Fact(DisplayName = "Return does not change count given negative")] + public async Task Return_Does_Not_Change_Count_Given_Negative() + { + using (var t = new TokenBucket(10, 1000000)) + { + await t.GetAsync(5); + + Assert.Equal(5, t.GetProperty<long>("CurrentCount")); + + t.Return(-5); + + Assert.Equal(5, t.GetProperty<long>("CurrentCount")); + } + } + + [Trait("Category", "Return")] + [Fact(DisplayName = "Return adds capacity given value larger than capacity")] + public async Task Return_Adds_Capacity_Given_Value_Larger_Than_Capacity() + { + using (var t = new TokenBucket(10, 1000000)) + { + await t.GetAsync(5); + + Assert.Equal(5, t.GetProperty<long>("CurrentCount")); + + t.Return(50); + + Assert.Equal(15, t.GetProperty<long>("CurrentCount")); + } + } + + [Trait("Category", "Return")] + [Fact(DisplayName = "Return adds given value")] + public async Task Return_Adds_Given_Value() + { + using (var t = new TokenBucket(10, 1000000)) + { + await t.GetAsync(5); + + Assert.Equal(5, t.GetProperty<long>("CurrentCount")); + + t.Return(5); + + Assert.Equal(10, t.GetProperty<long>("CurrentCount")); + } + } + } +} diff --git a/tests/slskd.Tests.Unit/TestIsolationExtensions.cs b/tests/slskd.Tests.Unit/TestIsolationExtensions.cs new file mode 100644 index 00000000..f6b774d3 --- /dev/null +++ b/tests/slskd.Tests.Unit/TestIsolationExtensions.cs @@ -0,0 +1,212 @@ +namespace slskd.Tests.Unit +{ + using System; + using System.Reflection; + + public static class TestIsolationExtensions + { + private const BindingFlags Flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; + + public static T GetField<T>(this object target, string fieldName) + { + var type = target.GetType(); + var field = type.GetField(fieldName, Flags); + + if (field == default) + { + throw new ArgumentException($"No such field '{fieldName}' exists on target Type {type.Name}.", nameof(fieldName)); + } + + try + { + return (T)field.GetValue(target); + } + catch (Exception ex) + { + throw new Exception($"Failed to get field '{fieldName}' on target Type {type.Name}. See inner Exception for details.", ex); + } + } + + public static T GetProperty<T>(this object target, string propertyName) + { + var type = target.GetType(); + var property = type.GetProperty(propertyName, Flags); + + if (property == default) + { + throw new ArgumentException($"No such property '{propertyName}' exists on target Type {type.Name}.", nameof(propertyName)); + } + + try + { + return (T)property.GetValue(target); + } + catch (Exception ex) + { + throw new Exception($"Failed to get property '{propertyName}' on target Type {type.Name}. See inner Exception for details.", ex); + } + } + + public static void InvokeGenericMethod(this object target, string methodName, Type typeArgument, params object[] args) + { + InvokeGenericMethod(target, methodName, typeArgument, Flags, args); + } + + public static void InvokeGenericMethod(this object target, string methodName, Type typeArgument, BindingFlags bindingFlags, params object[] args) + { + var type = target.GetType(); + + try + { + var method = GetMethod(type, methodName, bindingFlags); + var generic = method.MakeGenericMethod(typeArgument); + + generic.Invoke(target, args); + } + catch (Exception ex) + { + throw new Exception($"Failed to invoke method '{methodName}<{typeArgument.Name}>' on target Type {type.Name}. See inner Exception for details.", ex); + } + } + + public static TResult InvokeGenericMethod<TArg, TResult>(this object target, string methodName, params object[] args) + { + return InvokeGenericMethod<TArg, TResult>(target, methodName, Flags, args); + } + + public static TResult InvokeGenericMethod<TArg, TResult>(this object target, string methodName, BindingFlags bindingFlags, params object[] args) + { + var type = target.GetType(); + + try + { + var method = GetMethod(type, methodName, bindingFlags); + var generic = method.MakeGenericMethod(typeof(TArg)); + + return (TResult)generic.Invoke(target, args); + } + catch (Exception ex) + { + throw new Exception($"Failed to invoke method '{methodName}<{typeof(TArg).Name}>' on target Type {type.Name}. See inner Exception for details.", ex); + } + } + + public static void InvokeMethod(this object target, string methodName, BindingFlags bindingFlags, params object[] args) + { + var type = target.GetType(); + + try + { + GetMethod(type, methodName, bindingFlags).Invoke(target, args); + } + catch (Exception ex) + { + throw new Exception($"Failed to invoke method '{methodName}' on target Type {type.Name}. See inner Exception for details.", ex); + } + } + + public static void InvokeMethod(this object target, string methodName, params object[] args) + { + InvokeMethod(target, methodName, Flags, args); + } + + public static T InvokeMethod<T>(this object target, string methodName, BindingFlags bindingFlags, params object[] args) + { + var type = target.GetType(); + + try + { + return (T)GetMethod(type, methodName, bindingFlags).Invoke(target, args); + } + catch (Exception ex) + { + throw new Exception($"Failed to invoke method '{methodName}' on target Type {type.Name}. See inner Exception for details.", ex); + } + } + + public static T InvokeMethod<T>(this object target, string methodName, params object[] args) + { + return InvokeMethod<T>(target, methodName, Flags, args); + } + + public static void RaiseEvent(this object target, Type targetType, string eventName, object eventArgs) + { + var type = targetType; + var @event = (MulticastDelegate)type.GetField(eventName, Flags)?.GetValue(target); + + if (@event == null) + { + throw new ArgumentException($"No such event '{eventName}' exists on target Type {type.Name}.", nameof(eventName)); + } + + try + { + foreach (var handler in @event?.GetInvocationList()) + { + handler.Method.Invoke(handler.Target, new object[] { target, eventArgs }); + } + } + catch (Exception ex) + { + throw new Exception($"Failed to raise event '{eventName}' on target Type {type.Name}. See inner Exception for details.", ex); + } + } + + public static void RaiseEvent(this object target, string eventName, object eventArgs) + { + RaiseEvent(target, target.GetType(), eventName, eventArgs); + } + + public static void SetField(this object target, string fieldName, object value) + { + var type = target.GetType(); + var field = type.GetField(fieldName, Flags); + + if (field == default) + { + throw new ArgumentException($"No such field '{fieldName}' exists on target Type {type.Name}.", nameof(fieldName)); + } + + try + { + field.SetValue(target, value); + } + catch (Exception ex) + { + throw new Exception($"Failed to set field '{fieldName}' on target Type {type.Name}. See inner Exception for details.", ex); + } + } + + public static void SetProperty(this object target, string propertyName, object value) + { + var type = target.GetType(); + var property = type.GetProperty(propertyName, Flags); + + if (property == default) + { + throw new ArgumentException($"No such property '{propertyName}' exists on target Type {type.Name}.", nameof(propertyName)); + } + + try + { + property.SetValue(target, value); + } + catch (Exception ex) + { + throw new Exception($"Failed to set property '{propertyName}' on target Type {type.Name}. See inner Exception for details.", ex); + } + } + + private static MethodInfo GetMethod(Type type, string methodName, BindingFlags flags) + { + var method = type.GetMethod(methodName, flags); + + if (method == default) + { + throw new ArgumentException($"No such method '{methodName}' exists on target Type {type.Name}.", nameof(methodName)); + } + + return method; + } + } +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/TestOptionsMonitor.cs b/tests/slskd.Tests.Unit/TestOptionsMonitor.cs new file mode 100644 index 00000000..6c16adf5 --- /dev/null +++ b/tests/slskd.Tests.Unit/TestOptionsMonitor.cs @@ -0,0 +1,40 @@ +using System; +using Microsoft.Extensions.Options; +using Moq; + +namespace slskd.Tests.Unit +{ + public class TestOptionsMonitor<TOptions> : IOptionsMonitor<TOptions> + { + private Action<TOptions, string> _listener; + + public TestOptionsMonitor(TOptions currentValue) + { + CurrentValue = currentValue; + } + + public TOptions CurrentValue { get; private set; } + + public TOptions Get(string name) + { + return CurrentValue; + } + + public void Set(TOptions value) + { + CurrentValue = value; + _listener.Invoke(value, null); + } + + public IDisposable OnChange(Action<TOptions, string> listener) + { + _listener = listener; + return new Mock<IDisposable>().Object; + } + + public void RaiseOnChange(TOptions options) + { + _listener(options, null); + } + } +} diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs new file mode 100644 index 00000000..0e030f27 --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs @@ -0,0 +1,266 @@ +namespace slskd.Tests.Unit.Transfers.Uploads +{ + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using AutoFixture.Xunit2; + using Moq; + using slskd.Transfers; + using slskd.Users; + using Soulseek; + using Xunit; + + public class UploadGovernorTests + { + [Fact] + public void Instantiates_With_BuiltIn_Buckets() + { + var (governor, _) = GetFixture(); + + var buckets = governor.GetProperty<Dictionary<string, ITokenBucket>>("TokenBuckets"); + + Assert.Equal(3, buckets.Count); + Assert.True(buckets.ContainsKey(Application.PriviledgedGroup)); + Assert.True(buckets.ContainsKey(Application.DefaultGroup)); + Assert.True(buckets.ContainsKey(Application.LeecherGroup)); + } + + [Theory, AutoData] + public void Instantiates_With_User_Defined_Buckets(string group1, string group2) + { + var options = new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary<string, Options.GroupsOptions.UserDefinedOptions>() + { + { group1, new Options.GroupsOptions.UserDefinedOptions() }, + { group2, new Options.GroupsOptions.UserDefinedOptions() }, + } + } + }; + + var (governor, _) = GetFixture(options); + + var buckets = governor.GetProperty<Dictionary<string, ITokenBucket>>("TokenBuckets"); + + Assert.Equal(5, buckets.Count); + Assert.True(buckets.ContainsKey(group1)); + Assert.True(buckets.ContainsKey(group2)); + } + + public class GetBytesAsync + { + [Theory, AutoData] + public async Task Gets_Bytes_From_Bucket(string username, string filename) + { + var (governor, _) = GetFixture(); + + // mock the default bucket + var bucket = new Mock<ITokenBucket>(); + governor.SetProperty("TokenBuckets", new Dictionary<string, ITokenBucket>() + { + { Application.DefaultGroup, bucket.Object }, + }); + + var tx = new Transfer(TransferDirection.Upload, username, filename, 0, TransferStates.Completed, 0, 0); + + await governor.GetBytesAsync(tx, 1, CancellationToken.None); + + bucket.Verify(m => m.GetAsync(1, CancellationToken.None), Times.Once); + } + + [Theory, AutoData] + public async Task Gets_Bytes_From_Default_Bucket_If_No_Bucket_For_Group_Exists(string username, string filename, string group) + { + var (governor, mocks) = GetFixture(); + + // return a bogus group for this user, specifically one that does not have + // a corresponding bucket + mocks.UserService.Setup(m => m.GetGroup(username)).Returns(group); + + // mock the default bucket + var bucket = new Mock<ITokenBucket>(); + governor.SetProperty("TokenBuckets", new Dictionary<string, ITokenBucket>() + { + { Application.DefaultGroup, bucket.Object }, + }); + + var tx = new Transfer(TransferDirection.Upload, username, filename, 0, TransferStates.Completed, 0, 0); + + await governor.GetBytesAsync(tx, 1, CancellationToken.None); + + bucket.Verify(m => m.GetAsync(1, CancellationToken.None), Times.Once); + } + + [Theory, AutoData] + public async Task Gets_Bytes_From_User_Defined_Bucket(string username, string filename, string group) + { + var (governor, mocks) = GetFixture(); + + mocks.UserService.Setup(m => m.GetGroup(username)).Returns(group); + + // mock a bucket for the user's group + var bucket = new Mock<ITokenBucket>(); + governor.SetProperty("TokenBuckets", new Dictionary<string, ITokenBucket>() + { + { Application.DefaultGroup, new Mock<ITokenBucket>().Object }, + { group, bucket.Object }, + }); + + var tx = new Transfer(TransferDirection.Upload, username, filename, 0, TransferStates.Completed, 0, 0); + + await governor.GetBytesAsync(tx, 1, CancellationToken.None); + + bucket.Verify(m => m.GetAsync(1, CancellationToken.None), Times.Once); + } + } + + public class ReturnBytes + { + [Theory, AutoData] + public void Returns_Bytes_To_Bucket(string username, string filename, int attemptedBytes) + { + var (governor, _) = GetFixture(); + + // mock the default bucket + var bucket = new Mock<ITokenBucket>(); + governor.SetProperty("TokenBuckets", new Dictionary<string, ITokenBucket>() + { + { Application.DefaultGroup, bucket.Object }, + }); + + var tx = new Transfer(TransferDirection.Upload, username, filename, 0, TransferStates.Completed, 0, 0); + + governor.ReturnBytes(transfer: tx, attemptedBytes, grantedBytes: attemptedBytes / 2, actualBytes: attemptedBytes / 4); + + // assert that the difference between granted and actual was returned + bucket.Verify(m => m.Return((attemptedBytes / 2) - (attemptedBytes / 4)), Times.Once); + } + + [Theory, AutoData] + public void Does_Not_Return_Bytes_To_Bucket_If_No_Bytes_Were_Wasted(string username, string filename) + { + var (governor, _) = GetFixture(); + + // mock the default bucket + var bucket = new Mock<ITokenBucket>(); + governor.SetProperty("TokenBuckets", new Dictionary<string, ITokenBucket>() + { + { Application.DefaultGroup, bucket.Object }, + }); + + var tx = new Transfer(TransferDirection.Upload, username, filename, 0, TransferStates.Completed, 0, 0); + + governor.ReturnBytes(transfer: tx, attemptedBytes: 100, grantedBytes: 50, actualBytes: 50); + + // assert that the bucket's return method was never called + bucket.Verify(m => m.Return(It.IsAny<int>()), Times.Never); + } + + [Theory, AutoData] + public void Returns_Bytes_To_Default_Bucket_If_No_Bucket_For_Group_Exists(string username, string filename, string group) + { + var (governor, mocks) = GetFixture(); + + // return a bogus group for this user, specifically one that does not have + // a corresponding bucket + mocks.UserService.Setup(m => m.GetGroup(username)).Returns(group); + + // mock only the default bucket + var bucket = new Mock<ITokenBucket>(); + governor.SetProperty("TokenBuckets", new Dictionary<string, ITokenBucket>() + { + { Application.DefaultGroup, bucket.Object }, + }); + + var tx = new Transfer(TransferDirection.Upload, username, filename, 0, TransferStates.Completed, 0, 0); + + governor.ReturnBytes(transfer: tx, attemptedBytes: 100, grantedBytes: 50, actualBytes: 25); + + // assert that the difference between granted and actual was returned + bucket.Verify(m => m.Return(25)); + } + + [Theory, AutoData] + public void Returns_Bytes_To_User_Defined_Bucket(string username, string filename, string group) + { + var (governor, mocks) = GetFixture(); + + mocks.UserService.Setup(m => m.GetGroup(username)).Returns(group); + + // mock a bucket for the user's group + var bucket = new Mock<ITokenBucket>(); + governor.SetProperty("TokenBuckets", new Dictionary<string, ITokenBucket>() + { + { Application.DefaultGroup, new Mock<ITokenBucket>().Object }, + { group, bucket.Object }, + }); + + var tx = new Transfer(TransferDirection.Upload, username, filename, 0, TransferStates.Completed, 0, 0); + + governor.ReturnBytes(transfer: tx, attemptedBytes: 100, grantedBytes: 50, actualBytes: 25); + + // assert that the difference between granted and actual was returned + bucket.Verify(m => m.Return(25)); + } + } + + public class Configuration + { + [Theory, AutoData] + public void Reconfigures_Buckets_When_Options_Change(string group) + { + var options = new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary<string, Options.GroupsOptions.UserDefinedOptions>() + { + { group, new Options.GroupsOptions.UserDefinedOptions() }, + } + } + }; + + // do not pass options; only default buckets + var (governor, mocks) = GetFixture(); + + var buckets = governor.GetProperty<Dictionary<string, ITokenBucket>>("TokenBuckets"); + + // ensure only default buckets are created + Assert.Equal(3, buckets.Count); + Assert.False(buckets.ContainsKey(group)); + + // reconfigure with options + mocks.OptionsMonitor.RaiseOnChange(options); + + // grab the new copy of buckets + buckets = governor.GetProperty<Dictionary<string, ITokenBucket>>("TokenBuckets"); + + Assert.Equal(4, buckets.Count); + Assert.True(buckets.ContainsKey(group)); + } + } + + private static (UploadGovernor governor, Mocks mocks) GetFixture(Options options = null) + { + var mocks = new Mocks(options); + var governor = new UploadGovernor( + mocks.UserService.Object, + mocks.OptionsMonitor); + + return (governor, mocks); + } + + private class Mocks + { + public Mocks(Options options = null) + { + OptionsMonitor = new TestOptionsMonitor<Options>(options ?? new Options()); + } + + public Mock<IUserService> UserService { get; } = new Mock<IUserService>(); + public TestOptionsMonitor<Options> OptionsMonitor { get; init; } + } + } +} diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs new file mode 100644 index 00000000..9b0fba72 --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -0,0 +1,723 @@ +namespace slskd.Tests.Unit.Transfers.Uploads +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; + using AutoFixture.Xunit2; + using Moq; + using slskd.Transfers; + using slskd.Users; + using Soulseek; + using System; + using Xunit; + using static slskd.Transfers.UploadQueue; + + public class UploadQueueTests + { + [Fact] + public void Instantiates_With_BuiltIn_Groups() + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + Assert.Equal(3, groups.Count); + Assert.True(groups.ContainsKey(Application.PriviledgedGroup)); + Assert.True(groups.ContainsKey(Application.DefaultGroup)); + Assert.True(groups.ContainsKey(Application.LeecherGroup)); + } + + [Fact] + public void Instantiates_With_Expected_Privileged_Options() + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + var p = groups[Application.PriviledgedGroup]; + + Assert.Equal(Application.PriviledgedGroup, p.Name); + Assert.Equal(0, p.Priority); + Assert.Equal(new Options().Global.Upload.Slots, p.Slots); + Assert.Equal(0, p.UsedSlots); + Assert.Equal(QueueStrategy.FirstInFirstOut, p.Strategy); + } + + [Theory, AutoData] + public void Instantiates_With_Expected_Default_Group_Options(int priority, int slots, QueueStrategy strategy) + { + var (queue, _) = GetFixture(new Options() + { + Groups = new Options.GroupsOptions() + { + Default = new Options.GroupsOptions.BuiltInOptions() + { + Upload = new Options.GroupsOptions.UploadOptions() + { + Priority = priority, + Slots = slots, + Strategy = strategy.ToString(), + } + } + } + }); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + var p = groups[Application.DefaultGroup]; + + Assert.Equal(Application.DefaultGroup, p.Name); + Assert.Equal(priority, p.Priority); + Assert.Equal(slots, p.Slots); + Assert.Equal(0, p.UsedSlots); + Assert.Equal(strategy, p.Strategy); + } + + [Theory, AutoData] + public void Instantiates_With_Expected_Leecher_Group_Options(int priority, int slots, QueueStrategy strategy) + { + var (queue, _) = GetFixture(new Options() + { + Groups = new Options.GroupsOptions() + { + Leechers = new Options.GroupsOptions.BuiltInOptions() + { + Upload = new Options.GroupsOptions.UploadOptions() + { + Priority = priority, + Slots = slots, + Strategy = strategy.ToString(), + } + } + } + }); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + var p = groups[Application.LeecherGroup]; + + Assert.Equal(Application.LeecherGroup, p.Name); + Assert.Equal(priority, p.Priority); + Assert.Equal(slots, p.Slots); + Assert.Equal(0, p.UsedSlots); + Assert.Equal(strategy, p.Strategy); + } + + [Theory, AutoData] + public void Instantiates_With_Expected_User_Defined_Group_Options(string group1, int priority1, int slots1, QueueStrategy strategy1, string group2, int priority2, int slots2, QueueStrategy strategy2) + { + var (queue, _) = GetFixture(new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary<string, Options.GroupsOptions.UserDefinedOptions>() + { + { + group1, + new Options.GroupsOptions.UserDefinedOptions() + { + Upload = new Options.GroupsOptions.UploadOptions() + { + Priority = priority1, + Slots = slots1, + Strategy = strategy1.ToString(), + } + } + }, + { + group2, + new Options.GroupsOptions.UserDefinedOptions() + { + Upload = new Options.GroupsOptions.UploadOptions() + { + Priority = priority2, + Slots = slots2, + Strategy = strategy2.ToString(), + } + } + } + } + } + }); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + var p = groups[group1]; + + Assert.Equal(group1, p.Name); + Assert.Equal(priority1, p.Priority); + Assert.Equal(slots1, p.Slots); + Assert.Equal(0, p.UsedSlots); + Assert.Equal(strategy1, p.Strategy); + + p = groups[group2]; + + Assert.Equal(group2, p.Name); + Assert.Equal(priority2, p.Priority); + Assert.Equal(slots2, p.Slots); + Assert.Equal(0, p.UsedSlots); + Assert.Equal(strategy2, p.Strategy); + } + + public class Configuration + { + [Theory, AutoData] + public void Reconfigures_Groups_When_Options_Change(string group, int priority, int slots, QueueStrategy strategy) + { + var options = new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary<string, Options.GroupsOptions.UserDefinedOptions>() + { + { + group, + new Options.GroupsOptions.UserDefinedOptions() + { + Upload = new Options.GroupsOptions.UploadOptions() + { + Priority = priority, + Slots = slots, + Strategy = strategy.ToString(), + } + } + }, + } + } + }; + + // do not pass options; init with defaults + var (queue, mocks) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + // user defined group does not exist + Assert.False(groups.ContainsKey(group)); + + // reconfigure + mocks.OptionsMonitor.RaiseOnChange(options); + + // get the new copy + groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + Assert.True(groups.ContainsKey(group)); + + var p = groups[group]; + + Assert.Equal(group, p.Name); + Assert.Equal(priority, p.Priority); + Assert.Equal(slots, p.Slots); + Assert.Equal(0, p.UsedSlots); + Assert.Equal(strategy, p.Strategy); + } + + [Theory, AutoData] + public void Retains_Used_Slot_Count_When_Options_Change(string group, int newPriority, int usedSlots) + { + var options = new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary<string, Options.GroupsOptions.UserDefinedOptions>() + { + { + group, + new Options.GroupsOptions.UserDefinedOptions() + { + Upload = new Options.GroupsOptions.UploadOptions() + { + Priority = 0, + Slots = 0, + Strategy = QueueStrategy.FirstInFirstOut.ToString(), + } + } + }, + } + } + }; + + var (queue, mocks) = GetFixture(options); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + groups[group].UsedSlots = usedSlots; + + // reconfigure with different options to bypass the hash check + options = new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary<string, Options.GroupsOptions.UserDefinedOptions>() + { + { + group, + new Options.GroupsOptions.UserDefinedOptions() + { + Upload = new Options.GroupsOptions.UploadOptions() + { + Priority = newPriority, // change priority + Slots = 0, + Strategy = QueueStrategy.FirstInFirstOut.ToString(), + } + } + }, + } + } + }; + + mocks.OptionsMonitor.RaiseOnChange(options); + + // get the new copy + groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + var p = groups[group]; + + Assert.Equal(usedSlots, p.UsedSlots); + Assert.Equal(newPriority, p.Priority); + } + } + + public class Enqueue + { + [Theory, AutoData] + public void Enqueue_Enqueues_If_Nothing_Is_Enqueued_Already(string username, string filename) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + + Assert.Empty(queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("Uploads")); + + queue.Enqueue(tx); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("Uploads"); + + Assert.Single(uploads); + Assert.True(uploads.ContainsKey(username)); + Assert.Single(uploads.GetValueOrDefault(username)); + Assert.Equal(tx.Filename, uploads.GetValueOrDefault(username).First().Filename); + } + + [Theory, AutoData] + public void Enqueue_Enqueues_If_Something_Is_Enqueued_Already(string username, string filename, string filename2) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + var tx2 = GetTransfer(username, filename2); + + queue.Enqueue(tx); + queue.Enqueue(tx2); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("Uploads"); + + Assert.Single(uploads); + Assert.True(uploads.ContainsKey(username)); + Assert.Equal(2, uploads.GetValueOrDefault(username).Count); + Assert.Equal(tx.Filename, uploads.GetValueOrDefault(username)[0].Filename); + Assert.Equal(tx2.Filename, uploads.GetValueOrDefault(username)[1].Filename); + } + + [Theory, AutoData] + public void Enqueue_Enqueues_Transfers_From_Different_Users(string username, string filename, string username2, string filename2) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + var tx2 = GetTransfer(username2, filename2); + + Assert.Empty(queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("Uploads")); + + queue.Enqueue(tx); + queue.Enqueue(tx2); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("Uploads"); + + Assert.Equal(2, uploads.Count); + Assert.True(uploads.ContainsKey(username)); + Assert.True(uploads.ContainsKey(username2)); + + // username should have a list containing 1 file + Assert.Single(uploads.GetValueOrDefault(username)); + Assert.Equal(tx.Filename, uploads.GetValueOrDefault(username).First().Filename); + + // username2 should also have a list containing 1 file + Assert.Single(uploads.GetValueOrDefault(username2)); + Assert.Equal(tx2.Filename, uploads.GetValueOrDefault(username2).First().Filename); + } + } + + public class Complete + { + [Theory, AutoData] + public void Throws_If_No_Such_Username(string username, string filename) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + + var ex = Record.Exception(() => queue.Complete(tx)); + + Assert.NotNull(ex); + Assert.IsType<SlskdException>(ex); + Assert.True(ex.Message.Contains("no enqueued uploads for user", System.StringComparison.InvariantCultureIgnoreCase)); + } + + [Theory, AutoData] + public void Throws_If_No_Such_Filename(string username, string filename) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + var badTx = GetTransfer(username, "foo"); + + queue.Enqueue(tx); + + var ex = Record.Exception(() => queue.Complete(badTx)); + + Assert.NotNull(ex); + Assert.IsType<SlskdException>(ex); + Assert.True(ex.Message.Contains("is not enqueued for user", System.StringComparison.InvariantCultureIgnoreCase)); + } + + [Theory, AutoData] + public async Task Removes_Filename(string username, string filename, string filename2) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + var tx2 = GetTransfer(username, filename2); + + queue.Enqueue(tx); + await queue.AwaitStartAsync(tx); + queue.Enqueue(tx2); + await queue.AwaitStartAsync(tx2); + + queue.Complete(tx); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("Uploads"); + + Assert.Single(uploads); + Assert.True(uploads.ContainsKey(username)); + Assert.Single(uploads[username]); + Assert.Equal(filename2, uploads[username][0].Filename); + } + + [Theory, AutoData] + public async Task Decrements_UsedSlots_For_Group(string username, string filename, string filename2) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + var tx2 = GetTransfer(username, filename2); + + queue.Enqueue(tx); + await queue.AwaitStartAsync(tx); + + queue.Enqueue(tx2); + await queue.AwaitStartAsync(tx2); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + Assert.Equal(2, groups[Application.DefaultGroup].UsedSlots); + + queue.Complete(tx); + + groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + Assert.Equal(1, groups[Application.DefaultGroup].UsedSlots); + } + + [Theory, AutoData] + public void Cleans_Up_If_User_Has_No_More_Files_Enqueued(string username, string filename, string filename2) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + var tx2 = GetTransfer(username, filename2); + + queue.Enqueue(tx); + queue.Enqueue(tx2); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("Uploads"); + + Assert.Single(uploads); + + queue.Complete(tx); + queue.Complete(tx2); + + uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("Uploads"); + + Assert.Empty(uploads); + } + } + + public class AwaitStartAsync + { + [Theory, AutoData] + public async Task Throws_If_No_Such_Username(string username, string filename) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + + var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(tx)); + + Assert.NotNull(ex); + Assert.IsType<SlskdException>(ex); + Assert.True(ex.Message.Contains("no enqueued uploads for user", System.StringComparison.InvariantCultureIgnoreCase)); + } + + [Theory, AutoData] + public async Task Throws_If_No_Such_Filename(string username, string filename) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + var badTx = GetTransfer(username, "foo"); + + queue.Enqueue(tx); + + var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(badTx)); + + Assert.NotNull(ex); + Assert.IsType<SlskdException>(ex); + Assert.True(ex.Message.Contains("is not enqueued for user", System.StringComparison.InvariantCultureIgnoreCase)); + } + + [Theory, AutoData] + public void Returns_Task_Associated_With_Upload(string username, string filename) + { + var (queue, _) = GetFixture(); + var tx = GetTransfer(username, filename); + + queue.Enqueue(tx); + + var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("Uploads"); + + var task = queue.AwaitStartAsync(tx); + + Assert.Equal(task, uploads[username][0].TaskCompletionSource.Task); + } + } + + public class Process + { + [Fact] + public void Does_Nothing_If_MaxSlots_Is_Reached() + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + groups[Application.DefaultGroup].UsedSlots = int.MaxValue; + + var result = queue.InvokeMethod<UploadQueue.Upload>("Process"); + + Assert.Null(result); + } + + [Fact] + public void Does_Nothing_If_No_Uploads() + { + var (queue, _) = GetFixture(); + + var result = queue.InvokeMethod<UploadQueue.Upload>("Process"); + + Assert.Null(result); + } + + [Theory, AutoData] + public void Sets_Started_And_Group_Properties_Of_Released_Upload(string user1, string file1) + { + var (queue, mocks) = GetFixture(); + + mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.PriviledgedGroup); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + + uploads.TryAdd(user1, new List<Upload>() + { + new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } + }); + + queue.SetProperty("Uploads", uploads); + + var result = queue.InvokeMethod<UploadQueue.Upload>("Process"); + + Assert.Equal(user1, result.Username); + Assert.Equal(file1, result.Filename); + Assert.NotNull(result.Started); + Assert.Equal(Application.PriviledgedGroup, result.Group); + } + + [Theory, AutoData] + public void Increments_UsedSlots_Of_Group(string user1, string file1) + { + var (queue, mocks) = GetFixture(); + + mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.PriviledgedGroup); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + + uploads.TryAdd(user1, new List<Upload>() + { + new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } + }); + + queue.SetProperty("Uploads", uploads); + + var result = queue.InvokeMethod<UploadQueue.Upload>("Process"); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + + Assert.Equal(1, groups[Application.PriviledgedGroup].UsedSlots); + } + + [Theory, AutoData] + public void Releases_Higher_Priority_Upload_First(string user1, string user2, string file1, string file2) + { + var (queue, mocks) = GetFixture(); + + mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.PriviledgedGroup); + mocks.UserService.Setup(m => m.GetGroup(user2)).Returns(Application.DefaultGroup); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + + uploads.TryAdd(user1, new List<Upload>() + { + new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } + }); + + uploads.TryAdd(user2, new List<Upload>() + { + new Upload() { Username = user2, Filename = file2, Ready = DateTime.UtcNow } + }); + + queue.SetProperty("Uploads", uploads); + + var result = queue.InvokeMethod<UploadQueue.Upload>("Process"); + + Assert.Equal(user1, result.Username); + Assert.Equal(file1, result.Filename); + } + + [Theory, AutoData] + public void Releases_Lower_Priority_Upload_First_If_All_Higher_Slots_Consumed_Or_Empty(string user1, string user2, string file1, string file2) + { + var (queue, mocks) = GetFixture(); + + // no privileged uploads + mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.DefaultGroup); + mocks.UserService.Setup(m => m.GetGroup(user2)).Returns(Application.LeecherGroup); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + + uploads.TryAdd(user1, new List<Upload>() + { + new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } + }); + + uploads.TryAdd(user2, new List<Upload>() + { + new Upload() { Username = user2, Filename = file2, Ready = DateTime.UtcNow } + }); + + queue.SetProperty("Uploads", uploads); + + // all default group slots consumed + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + groups[Application.DefaultGroup].Slots = 1; + groups[Application.DefaultGroup].UsedSlots = 1; + + var result = queue.InvokeMethod<UploadQueue.Upload>("Process"); + + // leecher group upload released + Assert.Equal(user2, result.Username); + Assert.Equal(file2, result.Filename); + } + + [Theory, AutoData] + public void Releases_First_Enqueued_Upload_When_Strategy_Is_FirstInFirstOut(string user1, string user2, string file1, string file2) + { + var (queue, mocks) = GetFixture(); + + mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.DefaultGroup); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + var ready = DateTime.UtcNow; + var enqueued = DateTime.UtcNow; + + uploads.TryAdd(user1, new List<Upload>() + { + new Upload() { Username = user1, Filename = file1, Enqueued = enqueued.AddHours(-1), Ready = ready } + }); + + uploads.TryAdd(user2, new List<Upload>() + { + new Upload() { Username = user2, Filename = file2, Enqueued = enqueued.AddHours(-2), Ready = ready } + }); + + queue.SetProperty("Uploads", uploads); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + groups[Application.DefaultGroup].Strategy = QueueStrategy.FirstInFirstOut; + + var result = queue.InvokeMethod<UploadQueue.Upload>("Process"); + + Assert.Equal(user2, result.Username); + Assert.Equal(file2, result.Filename); + } + + [Theory, AutoData] + public void Releases_First_Ready_Upload_When_Strategy_Is_RoundRobin(string user1, string user2, string file1, string file2) + { + var (queue, mocks) = GetFixture(); + + mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.DefaultGroup); + + var uploads = new ConcurrentDictionary<string, List<Upload>>(); + var ready = DateTime.UtcNow; + var enqueued = DateTime.UtcNow; + + uploads.TryAdd(user1, new List<Upload>() + { + new Upload() { Username = user1, Filename = file1, Enqueued = enqueued, Ready = ready } + }); + + uploads.TryAdd(user2, new List<Upload>() + { + new Upload() { Username = user2, Filename = file2, Enqueued = enqueued, Ready = ready.AddMinutes(-1) } + }); + + queue.SetProperty("Uploads", uploads); + + var groups = queue.GetProperty<Dictionary<string, UploadQueue.Group>>("Groups"); + groups[Application.DefaultGroup].Strategy = QueueStrategy.RoundRobin; + + var result = queue.InvokeMethod<UploadQueue.Upload>("Process"); + + Assert.Equal(user2, result.Username); + Assert.Equal(file2, result.Filename); + } + } + + private static (UploadQueue queue, Mocks mocks) GetFixture(Options options = null) + { + var mocks = new Mocks(options); + + mocks.UserService.Setup(m => m.GetGroup(It.IsAny<string>())) + .Returns(Application.DefaultGroup); + + var queue = new UploadQueue( + mocks.UserService.Object, + mocks.OptionsMonitor); + + return (queue, mocks); + } + + private static Transfer GetTransfer(string username, string filename) + => new Transfer(TransferDirection.Upload, username, filename, 0, TransferStates.Queued, 0, 0); + + private class Mocks + { + public Mocks(Options options = null) + { + OptionsMonitor = new TestOptionsMonitor<Options>(options ?? new Options()); + } + + public Mock<IUserService> UserService { get; } = new Mock<IUserService>(); + public TestOptionsMonitor<Options> OptionsMonitor { get; init; } + } + } +} diff --git a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs new file mode 100644 index 00000000..49f1f530 --- /dev/null +++ b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs @@ -0,0 +1,146 @@ +namespace slskd.Tests.Unit.Users +{ + using System.Collections.Generic; + using AutoFixture.Xunit2; + using Microsoft.EntityFrameworkCore; + using Moq; + using slskd.Users; + using Soulseek; + using Xunit; + + public class UserServiceTests + { + public class GetGroup + { + [Theory, AutoData] + public void Returns_Default_For_All_Users_If_No_User_Defined_Groups_Configured(string username) + { + var (service, _) = GetFixture(); + + Assert.Equal(Application.DefaultGroup, service.GetGroup(username)); + } + + [Fact] + public void Returns_Default_If_Username_Is_Null() + { + var (service, _) = GetFixture(); + + Assert.Equal(Application.DefaultGroup, service.GetGroup(null)); + } + + [Theory, AutoData] + public void Returns_User_Defined_Group(string group, string username) + { + var options = new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary<string, Options.GroupsOptions.UserDefinedOptions>() + { + { + group, + new Options.GroupsOptions.UserDefinedOptions() + { + Members = new[] { username }, + } + }, + } + } + }; + + var (service, _) = GetFixture(options); + + Assert.Equal(group, service.GetGroup(username)); + } + } + + public class Configuration + { + [Theory, AutoData] + public void Reconfigures_Groups_When_Options_Change(string group, string user) + { + var options = new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary<string, Options.GroupsOptions.UserDefinedOptions>() + { + { group, new Options.GroupsOptions.UserDefinedOptions() + { + Members = new[] { user }, + } }, + } + } + }; + + // do not pass options; only default groups + var (service, mocks) = GetFixture(); + + // ensure defaults + Assert.Equal(Application.DefaultGroup, service.GetGroup(user)); + + // reconfigure with options + mocks.OptionsMonitor.RaiseOnChange(options); + + Assert.Equal(group, service.GetGroup(user)); + } + + [Theory, AutoData] + public void Gives_Lowest_Priority_Group_To_Users_Appearing_In_Multiple_Groups(string group0, string group100, string user) + { + var options = new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary<string, Options.GroupsOptions.UserDefinedOptions>() + { + { + group100, + new Options.GroupsOptions.UserDefinedOptions() + { + Upload = new Options.GroupsOptions.UploadOptions() { Priority = 100 }, + Members = new[] { user }, + } + }, + { + group0, + new Options.GroupsOptions.UserDefinedOptions() + { + Upload = new Options.GroupsOptions.UploadOptions() { Priority = 0 }, + Members = new[] { user }, + } + }, + } + } + }; + + var (service, _) = GetFixture(options); + + Assert.Equal(group0, service.GetGroup(user)); + } + } + + private static (UserService governor, Mocks mocks) GetFixture(Options options = null) + { + var mocks = new Mocks(options); + var service = new UserService( + mocks.SoulseekClient.Object, + mocks.ContextFactory.Object, + mocks.OptionsMonitor); + + return (service, mocks); + } + + private class Mocks + { + public Mocks(Options options = null) + { + OptionsMonitor = new TestOptionsMonitor<Options>(options ?? new Options()); + } + + public Mock<ISoulseekClient> SoulseekClient { get; } = new Mock<ISoulseekClient>(); + public Mock<IDbContextFactory<UserDbContext>> ContextFactory { get; } = new Mock<IDbContextFactory<UserDbContext>>(); + public TestOptionsMonitor<Options> OptionsMonitor { get; init; } + } + } +} diff --git a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj index 892e1612..c3225e74 100644 --- a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj +++ b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj @@ -7,16 +7,18 @@ </PropertyGroup>
<ItemGroup>
- <PackageReference Include="coverlet.msbuild" Version="3.1.2">
- <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
- <PrivateAssets>all</PrivateAssets>
- </PackageReference>
+ <PackageReference Include="AutoFixture.Xunit2" Version="4.17.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
+ <PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
+ <PackageReference Include="coverlet.msbuild" Version="3.1.2">
+ <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+ <PrivateAssets>all</PrivateAssets>
+ </PackageReference>
</ItemGroup>
<ItemGroup>
|
