From 196361b38188276531c005855f9c8d6491762605 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 12 Jan 2022 09:04:57 -0600 Subject: tweak naming of global upload slot limit --- src/slskd/Options.cs | 25 +++++++++++++------------ src/slskd/Startup.cs | 4 ++-- 2 files changed, 15 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 900f2cd4..6b3d07ac 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -228,10 +228,11 @@ namespace slskd public DirectoriesOptions Directories { get; init; } = new DirectoriesOptions(); /// - /// Gets limits. + /// Gets global options. /// [Validate] - public LimitsOptions Limits { get; init; } = new LimitsOptions(); + public GlobalOptions Global { get; init; } = new GlobalOptions(); + /// /// Gets filter options. @@ -385,27 +386,27 @@ namespace slskd } /// - /// Limits. + /// Global options. /// - public class LimitsOptions + public class GlobalOptions { /// - /// Gets queue limits. + /// Gets global upload options. /// [Validate] - public LimitsQueueOptions Queue { get; init; } = new LimitsQueueOptions(); + public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions(); /// - /// Queue limits. + /// Global upload options. /// - public class LimitsQueueOptions + public class GlobalUploadOptions { /// /// Gets the limit for the total number of queue slots. /// - [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; diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 200a23fc..59557a81 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -235,7 +235,7 @@ namespace slskd // complete configuration at startup. services.AddSingleton(_ => new SoulseekClient(options: new SoulseekClientOptions( - maximumConcurrentUploads: OptionsAtStartup.Limits.Queue.Slots, + maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel))); // add the core application service to DI as well as a hosted service so that other services can -- cgit v1.2.3 From c32e83489eb621a97a5395d31c3d90bd4c7b3666 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 12 Jan 2022 09:06:17 -0600 Subject: rough in group config --- config/slskd.example.yml | 20 ++++++++++++++++++++ src/slskd/Options.cs | 41 +++++++++++++++++++++++++++++++++++++++-- src/slskd/Startup.cs | 2 +- 3 files changed, 60 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 56d0348c..72203d5e 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -14,6 +14,26 @@ # global: # upload: # slots: 20 +# groups: +# default: +# upload: +# priority: 500 +# strategy: roundrobin +# slots: 10 +# leechers: +# upload: +# priority: 1000 +# queue_strategy: roundrobin +# slots: 1 +# user_defined: +# my_buddies: +# upload: +# priority: 250 +# queue_strategy: firstinfirstout +# slots: 10 +# members: +# - alice +# - bob # filters: # share: # - \.ini$ diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 6b3d07ac..467c4bec 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -233,6 +233,11 @@ namespace slskd [Validate] public GlobalOptions Global { get; init; } = new GlobalOptions(); + /// + /// Gets user groups. + /// + [Validate] + public GroupsOptions Groups { get; init; } = new GroupsOptions(); /// /// Gets filter options. @@ -413,6 +418,38 @@ namespace slskd } } + /// + /// User groups. + /// + public class GroupsOptions + { + public BuiltInGroupOptions Default { get; init; } = new BuiltInGroupOptions(); + public BuiltInGroupOptions Leechers { get; init; } = new BuiltInGroupOptions(); + + public class BuiltInGroupOptions + { + public GroupUploadOptions Upload { get; init; } = new GroupUploadOptions(); + } + + public class UserDefinedGroupOptions + { + public GroupUploadOptions Upload { get; init; } = new GroupUploadOptions(); + public string[] Members { get; init; } = Array.Empty(); + } + + public class GroupUploadOptions + { + [Range(1, int.MaxValue)] + public int Priority { get; init; } + + [Enum(typeof(QueueStrategy))] + public string QueueStrategy { get; init; } = slskd.QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); + + [Range(1, int.MaxValue)] + public int Slots { get; init; } = 10; + } + } + /// /// Feature options. /// @@ -973,7 +1010,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(); /// /// Gets a value indicating whether FTP certificate errors should be ignored. diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 59557a81..dfe12824 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify -- cgit v1.2.3 From 72641b2f4154cec8b8c470ffcff456be31e6169d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 14 Jan 2022 15:29:14 -0600 Subject: docs for group options --- src/slskd/Options.cs | 47 +++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 467c4bec..e63a3b48 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -407,7 +407,7 @@ namespace slskd public class GlobalUploadOptions { /// - /// Gets the limit for the total number of queue slots. + /// Gets the limit for the total number of upload slots. /// [Argument(default, "upload-slots")] [EnvironmentVariable("UPLOAD_SLOTS")] @@ -423,28 +423,67 @@ namespace slskd /// public class GroupsOptions { + /// + /// Gets options for the default user group. + /// + [Validate] public BuiltInGroupOptions Default { get; init; } = new BuiltInGroupOptions(); - public BuiltInGroupOptions Leechers { get; init; } = new BuiltInGroupOptions(); + /// + /// Gets options for the leecher user group. + /// + [Validate] + public BuiltInGroupOptions Leechers { get; init; } = new BuiltInGroupOptions() { Upload = new GroupUploadOptions() { Priority = 99, Slots = 1 } }; + + /// + /// Built in user group options. + /// public class BuiltInGroupOptions { + /// + /// Gets upload options. + /// + [Validate] public GroupUploadOptions Upload { get; init; } = new GroupUploadOptions(); } + /// + /// User defined user group options. + /// public class UserDefinedGroupOptions { + /// + /// Gets upload options. + /// + [Validate] public GroupUploadOptions Upload { get; init; } = new GroupUploadOptions(); + + /// + /// Gets the list of group member usernames. + /// public string[] Members { get; init; } = Array.Empty(); } + /// + /// User group upload options. + /// public class GroupUploadOptions { + /// + /// Gets the priority of the group. + /// [Range(1, int.MaxValue)] - public int Priority { get; init; } + public int Priority { get; init; } = 1; + /// + /// Gets the queue strategy for the group. + /// [Enum(typeof(QueueStrategy))] - public string QueueStrategy { get; init; } = slskd.QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); + public string Strategy { get; init; } = slskd.QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); + /// + /// Gets the limit for the total number of upload slots for the group. + /// [Range(1, int.MaxValue)] public int Slots { get; init; } = 10; } -- cgit v1.2.3 From ab656f0feed130a1e7e58509a794e08c68de664d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Jan 2022 08:05:13 -0600 Subject: add global download options --- src/slskd/Options.cs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index e63a3b48..7c9fae0a 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -401,6 +401,12 @@ namespace slskd [Validate] public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions(); + /// + /// Gets global download options. + /// + [Validate] + public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions(); + /// /// Global upload options. /// @@ -415,6 +421,30 @@ namespace slskd [RequiresRestart] [Range(1, int.MaxValue)] public int Slots { get; init; } = 10; + + /// + /// Gets the total upload speed limit. + /// + [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; + } + + /// + /// Gets global download options. + /// + public class GlobalDownloadOptions + { + /// + /// Gets the total download speed limit. + /// + [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; } } -- cgit v1.2.3 From 15b057abf23778ec8bf595ccf4d773373510200a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Jan 2022 08:06:31 -0600 Subject: bump dependencies, including Soulseek.NET to 4.3.0 --- src/slskd/slskd.csproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index cdaa055d..072528c5 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -43,7 +43,7 @@ - + @@ -65,17 +65,17 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + -- cgit v1.2.3 From e039221926b192d2de0d164c8641dba5e4908c2f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Jan 2022 08:08:40 -0600 Subject: reconfigure options if globals change --- src/slskd/Application.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 73818c09..f2d81471 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -255,6 +255,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, @@ -545,7 +547,7 @@ 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), governor: (t, c) => Task.Delay(1, c)); + var topts = new TransferOptions(stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts)); // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and // uploads would be handled separately. @@ -619,8 +621,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 +684,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, -- cgit v1.2.3 From 299dbc204c182ca57ad5f08743db1ec8219b5b74 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 10:24:02 -0600 Subject: add download slot config --- src/slskd/Options.cs | 10 ++++++++++ src/slskd/Startup.cs | 1 + 2 files changed, 11 insertions(+) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 7c9fae0a..5f674eaf 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -437,6 +437,16 @@ namespace slskd /// public class GlobalDownloadOptions { + /// + /// Gets the limit for the total number of download slots. + /// + [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; + /// /// Gets the total download speed limit. /// diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index dfe12824..658f62f8 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -236,6 +236,7 @@ namespace slskd services.AddSingleton(_ => new SoulseekClient(options: new SoulseekClientOptions( 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 -- cgit v1.2.3 From 24dc05d101691e7c3216eca767d329af795c0036 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 11:09:13 -0600 Subject: temporarily remove leecher built in group --- config/slskd.example.yml | 5 ----- src/slskd/Options.cs | 8 +------- 2 files changed, 1 insertion(+), 12 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index eeb9b677..bff2df5b 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -24,11 +24,6 @@ # priority: 500 # strategy: roundrobin # slots: 10 -# leechers: -# upload: -# priority: 1000 -# queue_strategy: roundrobin -# slots: 1 # user_defined: # my_buddies: # upload: diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 5f674eaf..6b3bafa2 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -469,12 +469,6 @@ namespace slskd [Validate] public BuiltInGroupOptions Default { get; init; } = new BuiltInGroupOptions(); - /// - /// Gets options for the leecher user group. - /// - [Validate] - public BuiltInGroupOptions Leechers { get; init; } = new BuiltInGroupOptions() { Upload = new GroupUploadOptions() { Priority = 99, Slots = 1 } }; - /// /// Built in user group options. /// @@ -519,7 +513,7 @@ namespace slskd /// Gets the queue strategy for the group. /// [Enum(typeof(QueueStrategy))] - public string Strategy { get; init; } = slskd.QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); + public string Strategy { get; init; } = QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); /// /// Gets the limit for the total number of upload slots for the group. -- cgit v1.2.3 From 9557f842cc68eb259eacbe15d33ce09ad04dba08 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 13:18:39 -0600 Subject: add IsDictionary --- src/slskd/Common/Extensions.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 90f0b659..ebf16fce 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -18,6 +18,7 @@ namespace slskd { using System; + using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; @@ -307,6 +308,23 @@ namespace slskd return builder.ToString(); } + /// + /// Determines whether the given object is a . + /// + /// The object to check. + /// A value indicating whether the given object is a dictionary. + public static bool IsDictionary(this object obj) + { + if (obj == null) + { + return false; + } + + return obj is IDictionary && + obj.GetType().IsGenericType && + obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); + } + /// /// Redacts this instance of Options, replacing properties marked with with '*****'. /// -- cgit v1.2.3 From 963311ed00b8550933491944421f45d6a81228c0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 13:18:53 -0600 Subject: recursively validate dictionary elements --- src/slskd/Common/Validation/ValidateAttribute.cs | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Validation/ValidateAttribute.cs b/src/slskd/Common/Validation/ValidateAttribute.cs index d731eb0e..c7efaa92 100644 --- a/src/slskd/Common/Validation/ValidateAttribute.cs +++ b/src/slskd/Common/Validation/ValidateAttribute.cs @@ -17,8 +17,10 @@ namespace slskd.Validation { + using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; + using System.Linq; /// /// Indicates that attributed properties should be recursively validated. @@ -35,6 +37,30 @@ namespace slskd.Validation var results = new List(); var context = new ValidationContext(value, null, null); + if (value.IsDictionary()) + { + var compositeResults = new CompositeValidationResult(validationContext.DisplayName); + + // given the context in this application, key type should never be anything but a string + foreach (string key in ((IDictionary)value).Keys) + { + var val = ((IDictionary)value)[key]; + var result = IsValid(val, new ValidationContext(val, null, null)); + + if (result != ValidationResult.Success) + { + compositeResults.AddResult(new CompositeValidationResult(key, new[] { result }.ToList())); + } + } + + if (compositeResults.Results.Any()) + { + return compositeResults; + } + + return ValidationResult.Success; + } + Validator.TryValidateObject(value, context, results, true); if (results.Count != 0) -- cgit v1.2.3 From 33d10909007fcaaee16aa455b2bb24488ba17d19 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 13:19:17 -0600 Subject: simplify type names --- src/slskd/Options.cs | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 6b3bafa2..8acd5a11 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -399,18 +399,18 @@ namespace slskd /// Gets global upload options. /// [Validate] - public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions(); + public UploadOptions Upload { get; init; } = new UploadOptions(); /// /// Gets global download options. /// [Validate] - public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions(); + public DownloadOptions Download { get; init; } = new DownloadOptions(); /// /// Global upload options. /// - public class GlobalUploadOptions + public class UploadOptions { /// /// Gets the limit for the total number of upload slots. @@ -435,7 +435,7 @@ namespace slskd /// /// Gets global download options. /// - public class GlobalDownloadOptions + public class DownloadOptions { /// /// Gets the limit for the total number of download slots. @@ -467,30 +467,36 @@ namespace slskd /// Gets options for the default user group. /// [Validate] - public BuiltInGroupOptions Default { get; init; } = new BuiltInGroupOptions(); + public BuiltInOptions Default { get; init; } = new BuiltInOptions(); + + /// + /// Gets user defined groups and options. + /// + [Validate] + public Dictionary UserDefined { get; init; } = new Dictionary(); /// /// Built in user group options. /// - public class BuiltInGroupOptions + public class BuiltInOptions { /// /// Gets upload options. /// [Validate] - public GroupUploadOptions Upload { get; init; } = new GroupUploadOptions(); + public UploadOptions Upload { get; init; } = new UploadOptions(); } /// /// User defined user group options. /// - public class UserDefinedGroupOptions + public class UserDefinedOptions { /// /// Gets upload options. /// [Validate] - public GroupUploadOptions Upload { get; init; } = new GroupUploadOptions(); + public UploadOptions Upload { get; init; } = new UploadOptions(); /// /// Gets the list of group member usernames. @@ -501,7 +507,7 @@ namespace slskd /// /// User group upload options. /// - public class GroupUploadOptions + public class UploadOptions { /// /// Gets the priority of the group. -- cgit v1.2.3 From c586e614c7894c8791541f1526d38a989160eaa0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 18:24:39 -0600 Subject: add TokenBucket --- src/slskd/Common/TokenBucket.cs | 250 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 250 insertions(+) create mode 100644 src/slskd/Common/TokenBucket.cs (limited to 'src') diff --git a/src/slskd/Common/TokenBucket.cs b/src/slskd/Common/TokenBucket.cs new file mode 100644 index 00000000..29fd720c --- /dev/null +++ b/src/slskd/Common/TokenBucket.cs @@ -0,0 +1,250 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Implements the 'token bucket' or 'leaky bucket' rate limiting algorithm. + /// + public interface ITokenBucket + { + /// + /// Gets the bucket capacity. + /// + public long Capacity { get; } + + /// + /// Asynchronously retrieves the specified token from the bucket. + /// + /// + /// + /// If the requested exceeds the bucket , the request is lowered to + /// the capacity of the bucket. + /// + /// If the bucket has tokens available, but fewer than the requested amount, the available tokens are returned. + /// + /// If the bucket has no tokens available, execution waits for the bucket to be replenished before servicing the request. + /// + /// + /// The number of tokens to retrieve. + /// The token to monitor for cancellation requests. + /// A Task that completes when tokens have been provided. + Task GetAsync(int count, CancellationToken cancellationToken = default); + + /// + /// Returns the specified token to the bucket. + /// + /// + /// This method should only be called if tokens were retrieved from the bucket, but were not used. + /// + /// If the specified count exceeds the bucket capacity, the count is lowered to the capacity. Effectively this + /// allows the bucket to 'burst' up to 2x capacity to 'catch up' to the desired rate if tokens were wastefully + /// retrieved. + /// + /// If the specified count is negative, no change is made to the available count. + /// + /// The number of tokens to return. + void Return(int count); + + /// + /// Sets the bucket capacity to the supplied . + /// + /// Change takes effect on the next reset. + /// The bucket capacity. + void SetCapacity(long capacity); + } + + /// + /// Implements the 'token bucket' or 'leaky bucket' rate limiting algorithm. + /// + public class TokenBucket : ITokenBucket, IDisposable + { + /// + /// Initializes a new instance of the class. + /// + /// The bucket capacity. + /// The interval at which tokens are replenished. + public TokenBucket(long capacity, int interval) + { + if (capacity < 1) + { + throw new ArgumentOutOfRangeException(nameof(capacity), "Bucket capacity must be greater than or equal to 1"); + } + + if (interval < 1) + { + throw new ArgumentOutOfRangeException(nameof(interval), "Interval must be greater than or equal to 1"); + } + + Capacity = capacity; + CurrentCount = Capacity; + + Clock = new System.Timers.Timer(interval); + Clock.Elapsed += (sender, e) => _ = Reset(); + Clock.Start(); + } + + /// + /// Gets the bucket capacity. + /// + public long Capacity { get; private set; } + + private System.Timers.Timer Clock { get; set; } + private long CurrentCount { get; set; } + private bool Disposed { get; set; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private TaskCompletionSource WaitForReset { get; set; } = new TaskCompletionSource(); + + /// + /// Disposes this instance. + /// + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + /// + /// Asynchronously retrieves the specified token from the bucket. + /// + /// + /// + /// If the requested exceeds the bucket , the request is lowered to + /// the capacity of the bucket. + /// + /// If the bucket has tokens available, but fewer than the requested amount, the available tokens are returned. + /// + /// If the bucket has no tokens available, execution waits for the bucket to be replenished before servicing the request. + /// + /// + /// The number of tokens to retrieve. + /// The token to monitor for cancellation requests. + /// A Task that completes when tokens have been provided. + public Task GetAsync(int count, CancellationToken cancellationToken = default) + { + return GetInternalAsync(Math.Min(count, (int)Math.Min(int.MaxValue, Capacity)), cancellationToken); + } + + /// + /// Returns the specified token to the bucket. + /// + /// + /// This method should only be called if tokens were retrieved from the bucket, but were not used. + /// + /// If the specified count exceeds the bucket capacity, the count is lowered to the capacity. Effectively this + /// allows the bucket to 'burst' up to 2x capacity to 'catch up' to the desired rate if tokens were wastefully + /// retrieved. + /// + /// If the specified count is negative, no change is made to the available count. + /// + /// The number of tokens to return. + public void Return(int count) + { + CurrentCount += Math.Min(Math.Max(count, 0), Capacity); + } + + /// + /// Sets the bucket capacity to the supplied . + /// + /// Change takes effect on the next reset. + /// The bucket capacity. + public void SetCapacity(long capacity) + { + if (capacity < 1) + { + throw new ArgumentOutOfRangeException(nameof(capacity), "Bucket capacity must be greater than or equal to 1"); + } + + Capacity = capacity; + } + + /// + /// Disposes this instance. + /// + /// A value indicating whether disposal is in progress. + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + Clock.Dispose(); + SyncRoot.Dispose(); + } + + Disposed = true; + } + } + + private async Task GetInternalAsync(int count, CancellationToken cancellationToken = default) + { + Task waitTask = Task.CompletedTask; + + await SyncRoot.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + // if the bucket has enough tokens to fulfil the request, return them and decrement the bucket + if (CurrentCount >= count) + { + CurrentCount -= count; + return count; + } + + // if the bucket doesn't have enough tokens to fulfil the request, but has some available, return the available + // tokens and zero the bucket + if (CurrentCount > 0) + { + var availableCount = CurrentCount; + CurrentCount = 0; + return (int)availableCount; + } + + // if the bucket is empty, make the caller wait until the bucket is replenished + waitTask = WaitForReset.Task; + } + finally + { + SyncRoot.Release(); + } + + await waitTask.ConfigureAwait(false); + return await GetAsync(count, cancellationToken).ConfigureAwait(false); + } + + private async Task Reset() + { + await SyncRoot.WaitAsync().ConfigureAwait(false); + + try + { + CurrentCount = Capacity; + + WaitForReset.SetResult(true); + WaitForReset = new TaskCompletionSource(); + } + finally + { + SyncRoot.Release(); + } + } + } +} -- cgit v1.2.3 From 7d89bc4ad9035a37b1506a635d9fb3fe3df4cde0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 21:07:50 -0600 Subject: add user/group mapping to UserService --- src/slskd/Users/IUserService.cs | 7 +++++++ src/slskd/Users/UserService.cs | 40 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 43 insertions(+), 4 deletions(-) (limited to 'src') 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 @@ -25,6 +25,13 @@ namespace slskd.Users /// public interface IUserService { + /// + /// Gets the name of the group for the specified . + /// + /// The username of the peer. + /// The group for the specified username. + string GetGroup(string username); + /// /// Retrieves peer . /// diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index f52f19f1..1f037d3d 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -15,13 +15,16 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Options; + namespace slskd.Users { using System; + using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Logging; + using Serilog; using Soulseek; /// @@ -30,26 +33,55 @@ namespace slskd.Users public class UserService : IUserService { private const int CacheTTLSeconds = 300; + private static readonly string DefaultGroup = "default"; /// /// Initializes a new instance of the class. /// /// /// The database context to use. + /// /// The logger. public UserService( ISoulseekClient soulseekClient, IDbContextFactory contextFactory, - ILogger log) + IOptionsMonitor optionsMonitor) { Client = soulseekClient; ContextFactory = contextFactory; - Log = log; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(Configure); + + Configure(OptionsMonitor.CurrentValue); } private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } - private ILogger Log { get; set; } + private IOptionsMonitor OptionsMonitor { get; } + private ILogger Log { get; set; } = Serilog.Log.ForContext(); + private Dictionary Map { get; set; } = new Dictionary(); + + private void Configure(Options options) + { + var map = new Dictionary(); + + foreach (var group in options.Groups.UserDefined) + { + foreach (var user in group.Value.Members) + { + map.Add(user, group.Key); + } + } + + Map = map; + Log.Debug("Updated user/group map with {Count} entries", Map.Count); + } + + public string GetGroup(string username) + { + return Map.GetValueOrDefault(username, DefaultGroup); + } /// /// Retrieves peer . -- cgit v1.2.3 From 6e84e1f8686cf1a4299cb039a2fa1ec90d5674b8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 21:08:09 -0600 Subject: bump Soulseek.NET to 4.4.1 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 243d05a9..3c786493 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -69,7 +69,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From ee21f4514305fb1ff213aae016817b7ff25d628d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 21:08:24 -0600 Subject: add SpeedLimit to UploadOptions --- src/slskd/Options.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 8acd5a11..302b01d0 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -526,6 +526,12 @@ namespace slskd /// [Range(1, int.MaxValue)] public int Slots { get; init; } = 10; + + /// + /// Gets the total upload speed limit for the group. + /// + [Range(1, int.MaxValue)] + public int SpeedLimit { get; init; } = int.MaxValue; } } -- cgit v1.2.3 From d592695e40b23e4bffbea2651313c2f674a19ec3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 21:10:45 -0600 Subject: stub Governor --- src/slskd/Application.cs | 10 +++++- src/slskd/Governor.cs | 93 ++++++++++++++++++++++++++++++++++++++++++++++++ src/slskd/Startup.cs | 2 ++ 3 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 src/slskd/Governor.cs (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index f2d81471..1d3d1b33 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -68,6 +68,7 @@ namespace slskd IRoomService roomService, ISharedFileCache sharedFileCache, IPushbulletService pushbulletService, + IGovernor governor, IHubContext applicationHub, IHubContext logHub) { @@ -89,6 +90,8 @@ namespace slskd ConversationTracker = conversationTracker; Pushbullet = pushbulletService; + Governor = governor; + RoomService = roomService; ApplicationHub = applicationHub; @@ -125,6 +128,7 @@ namespace slskd private IRoomService RoomService { get; set; } private IBrowseTracker BrowseTracker { get; set; } private IConversationTracker ConversationTracker { get; set; } + private IGovernor Governor { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); private Options Options => OptionsMonitor.CurrentValue; @@ -547,7 +551,11 @@ 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), + progressUpdated: (e) => tracker.AddOrUpdate(e, cts), + governor: (tx, req, ct) => Governor.GetBytes(tx, req, ct), + reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx, att, grant, act)); // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and // uploads would be handled separately. diff --git a/src/slskd/Governor.cs b/src/slskd/Governor.cs new file mode 100644 index 00000000..7b61d73a --- /dev/null +++ b/src/slskd/Governor.cs @@ -0,0 +1,93 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd +{ + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Serilog; + using slskd.Users; + using Soulseek; + + public interface IGovernor + { + Task GetBytes(Transfer transfer, int requestedBytes, CancellationToken cancellationToken); + public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes); + } + + public class Governor : IGovernor + { + public Governor( + IUserService userService, + IOptionsMonitor optionsMonitor) + { + UserService = userService; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(Configure); + + Configure(OptionsMonitor.CurrentValue); + } + + private IUserService UserService { get; } + private IOptionsMonitor OptionsMonitor { get; } + private ILogger Log { get; set; } = Serilog.Log.ForContext(); + private ITokenBucket DefaultTokenBucket { get; set; } + private Dictionary TokenBuckets { get; set; } = new Dictionary(); + + public Task GetBytes(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) + { + var group = UserService.GetGroup(transfer.Username); + var bucket = TokenBuckets.GetValueOrDefault(group, DefaultTokenBucket); + + return bucket.GetAsync(requestedBytes, cancellationToken); + } + + public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes) + { + var group = UserService.GetGroup(transfer.Username); + var bucket = TokenBuckets.GetValueOrDefault(group, DefaultTokenBucket); + + // 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(grantedBytes - actualBytes); + } + + private void Configure(Options options) + { + DefaultTokenBucket = new TokenBucket((options.Groups.Default.Upload.SpeedLimit * 1024L) / 10, 100); + + var tokenBuckets = new Dictionary(); + + foreach (var group in options.Groups.UserDefined) + { + tokenBuckets.Add(group.Key, new TokenBucket((group.Value.Upload.SpeedLimit * 1024L) / 10, 100)); + } + + TokenBuckets = tokenBuckets; + Log.Debug("Reconfigured governor for {Count} groups", TokenBuckets.Count); + } + } +} diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 658f62f8..15baa98d 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -259,6 +259,8 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); + + services.AddSingleton(); } /// -- cgit v1.2.3 From e6ca0002ca73ee5e6ba87fdc669d5c0c3e8327a7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Jan 2022 21:12:23 -0600 Subject: rename method --- src/slskd/Application.cs | 2 +- src/slskd/Governor.cs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 1d3d1b33..d1257b21 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -554,7 +554,7 @@ namespace slskd var topts = new TransferOptions( stateChanged: (e) => tracker.AddOrUpdate(e, cts), progressUpdated: (e) => tracker.AddOrUpdate(e, cts), - governor: (tx, req, ct) => Governor.GetBytes(tx, req, ct), + governor: (tx, req, ct) => Governor.GetBytesAsync(tx, req, ct), reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx, att, grant, act)); // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and diff --git a/src/slskd/Governor.cs b/src/slskd/Governor.cs index 7b61d73a..807fec71 100644 --- a/src/slskd/Governor.cs +++ b/src/slskd/Governor.cs @@ -28,7 +28,7 @@ namespace slskd public interface IGovernor { - Task GetBytes(Transfer transfer, int requestedBytes, CancellationToken cancellationToken); + Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken); public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes); } @@ -52,7 +52,7 @@ namespace slskd private ITokenBucket DefaultTokenBucket { get; set; } private Dictionary TokenBuckets { get; set; } = new Dictionary(); - public Task GetBytes(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) + public Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) { var group = UserService.GetGroup(transfer.Username); var bucket = TokenBuckets.GetValueOrDefault(group, DefaultTokenBucket); -- cgit v1.2.3 From a1cd5351ca77bb20f74f1877a26d809f75e2f0dc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 31 Jan 2022 08:13:28 -0600 Subject: clean up and move Governor --- src/slskd/Governor.cs | 93 ------------------------- src/slskd/Transfers/Governor.cs | 147 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 147 insertions(+), 93 deletions(-) delete mode 100644 src/slskd/Governor.cs create mode 100644 src/slskd/Transfers/Governor.cs (limited to 'src') diff --git a/src/slskd/Governor.cs b/src/slskd/Governor.cs deleted file mode 100644 index 807fec71..00000000 --- a/src/slskd/Governor.cs +++ /dev/null @@ -1,93 +0,0 @@ -// -// 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/. -// - -using Microsoft.Extensions.Options; - -namespace slskd -{ - using System.Collections.Generic; - using System.Threading; - using System.Threading.Tasks; - using Serilog; - using slskd.Users; - using Soulseek; - - public interface IGovernor - { - Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken); - public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes); - } - - public class Governor : IGovernor - { - public Governor( - IUserService userService, - IOptionsMonitor optionsMonitor) - { - UserService = userService; - - OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(Configure); - - Configure(OptionsMonitor.CurrentValue); - } - - private IUserService UserService { get; } - private IOptionsMonitor OptionsMonitor { get; } - private ILogger Log { get; set; } = Serilog.Log.ForContext(); - private ITokenBucket DefaultTokenBucket { get; set; } - private Dictionary TokenBuckets { get; set; } = new Dictionary(); - - public Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) - { - var group = UserService.GetGroup(transfer.Username); - var bucket = TokenBuckets.GetValueOrDefault(group, DefaultTokenBucket); - - return bucket.GetAsync(requestedBytes, cancellationToken); - } - - public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes) - { - var group = UserService.GetGroup(transfer.Username); - var bucket = TokenBuckets.GetValueOrDefault(group, DefaultTokenBucket); - - // 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(grantedBytes - actualBytes); - } - - private void Configure(Options options) - { - DefaultTokenBucket = new TokenBucket((options.Groups.Default.Upload.SpeedLimit * 1024L) / 10, 100); - - var tokenBuckets = new Dictionary(); - - foreach (var group in options.Groups.UserDefined) - { - tokenBuckets.Add(group.Key, new TokenBucket((group.Value.Upload.SpeedLimit * 1024L) / 10, 100)); - } - - TokenBuckets = tokenBuckets; - Log.Debug("Reconfigured governor for {Count} groups", TokenBuckets.Count); - } - } -} diff --git a/src/slskd/Transfers/Governor.cs b/src/slskd/Transfers/Governor.cs new file mode 100644 index 00000000..f58815b4 --- /dev/null +++ b/src/slskd/Transfers/Governor.cs @@ -0,0 +1,147 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Transfers +{ + using System; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Serilog; + using slskd.Users; + using Soulseek; + + /// + /// Governs transfer speed. + /// + public interface IGovernor + { + /// + /// Asynchronously obtains a grant of for the specified . + /// + /// + /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the + /// requested amount. + /// + /// The transfer for which the grant is requested. + /// The number of requested bytes. + /// The token to monitor for cancellation. + /// The operation context, including the number of bytes granted. + Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken); + + /// + /// Returns wasted bytes for redistribution. + /// + /// The transfer which generated the waste. + /// The number of bytes that were attempted to be transferred. + /// The number of bytes granted by all governors in the system. + /// The actual number of bytes transferred. + public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes); + } + + /// + /// Governs transfer speed. + /// + public class Governor : IGovernor + { + /// + /// Initializes a new instance of the class. + /// + /// The UserService instance to use. + /// The OptionsMonitor instance to use. + public Governor( + IUserService userService, + IOptionsMonitor optionsMonitor) + { + Users = userService; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(Configure); + + Configure(OptionsMonitor.CurrentValue); + } + + private ITokenBucket DefaultTokenBucket { get; set; } = new TokenBucket((int.MaxValue * 1024L) / 10, 100); + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IOptionsMonitor OptionsMonitor { get; } + private Dictionary TokenBuckets { get; set; } = new Dictionary(); + private IUserService Users { get; } + + /// + /// Asynchronously obtains a grant of for the specified . + /// + /// + /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the + /// requested amount. + /// + /// The transfer for which the grant is requested. + /// The number of requested bytes. + /// The token to monitor for cancellation. + /// The operation context, including the number of bytes granted. + public Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) + { + var group = Users.GetGroup(transfer.Username); + var bucket = TokenBuckets.GetValueOrDefault(group, DefaultTokenBucket); + + return bucket.GetAsync(requestedBytes, cancellationToken); + } + + /// + /// Returns wasted bytes for redistribution. + /// + /// The transfer which generated the waste. + /// The number of bytes that were attempted to be transferred. + /// The number of bytes granted by all governors in the system. + /// The actual number of bytes transferred. + public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes) + { + var waste = Math.Min(0, grantedBytes - actualBytes); + + if (waste == 0) + { + return; + } + + var group = Users.GetGroup(transfer.Username); + var bucket = TokenBuckets.GetValueOrDefault(group, DefaultTokenBucket); + + // 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) + { + DefaultTokenBucket = new TokenBucket((options.Groups.Default.Upload.SpeedLimit * 1024L) / 10, 100); + + var tokenBuckets = new Dictionary(); + + foreach (var group in options.Groups.UserDefined) + { + tokenBuckets.Add(group.Key, new TokenBucket((group.Value.Upload.SpeedLimit * 1024L) / 10, 100)); + } + + TokenBuckets = tokenBuckets; + Log.Debug("Reconfigured governor for {Count} groups", TokenBuckets.Count); + } + } +} \ No newline at end of file -- cgit v1.2.3 From 6f2fae7c40c53021f6326e4a4ea3ab705a0360b1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 31 Jan 2022 17:34:10 -0600 Subject: wip --- src/slskd/Transfers/UploadQueue.cs | 174 +++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 src/slskd/Transfers/UploadQueue.cs (limited to 'src') diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs new file mode 100644 index 00000000..f00d821f --- /dev/null +++ b/src/slskd/Transfers/UploadQueue.cs @@ -0,0 +1,174 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Transfers +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using slskd.Users; + using Soulseek; + + /// + /// Orchestrates uploads. + /// + public interface IUploadQueue + { + void Enqueue(Transfer transfer); + Task StartAsync(Transfer transfer); + void Complete(Transfer transfer); + } + + /// + /// Orchestrates uploads. + /// + public class UploadQueue : IUploadQueue + { + public UploadQueue( + IUserService userService, + IOptionsMonitor optionsMonitor) + { + Users = userService; + OptionsMonitor = optionsMonitor; + } + + private IUserService Users { get; } + private IOptionsMonitor OptionsMonitor { get; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private ConcurrentDictionary ActiveUploadCounts { get; } = new ConcurrentDictionary(); + private ConcurrentDictionary> WaitingUploads { get; } = new ConcurrentDictionary>(); + + public void Enqueue(Transfer transfer) + { + var group = Users.GetGroup(transfer.Username); + + var entry = new Entry() { Username = transfer.Username, Filename = transfer.Filename }; + + SyncRoot.Wait(); + + try + { + WaitingUploads.AddOrUpdate( + key: group, + addValue: new List(new[] { entry }), + updateValueFactory: (key, bag) => + { + bag.Add(entry); + return bag; + }); + + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + public Task StartAsync(Transfer transfer) + { + var group = Users.GetGroup(transfer.Username); + + SyncRoot.Wait(); + + try + { + if (!WaitingUploads.TryGetValue(group, out var list)) + { + throw new Exception($"No such group: {group}"); + } + + var entry = list.FirstOrDefault(e => e.Username == transfer.Username && e.Filename == transfer.Filename); + + if (entry == default) + { + throw new Exception($"No such transfer: {transfer.Username}/{transfer.Filename}"); + } + + entry.Ready = DateTime.UtcNow; + + return entry.TaskCompletionSource.Task; + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + public void Complete(Transfer transfer) + { + var group = Users.GetGroup(transfer.Username); + + SyncRoot.Wait(); + + try + { + if (!WaitingUploads.TryGetValue(group, out var list)) + { + throw new Exception($"No such group: {group}"); + } + + var entry = list.FirstOrDefault(e => e.Username == transfer.Username && e.Filename == transfer.Filename); + + list.Remove(entry); + + ActiveUploadCounts.AddOrUpdate( + key: group, + addValue: 0, + updateValueFactory: (key, count) => Math.Min(0, --count)); + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + private void Process() + { + SyncRoot.Wait(); + + try + { + // sort groups in ascending priority order + // while slots are available + // take lowest priority group + // sort waiting uploads according to strategy + // release uploads in order, up to the slot limit of the group + } + finally + { + SyncRoot.Release(); + } + } + + private class Entry + { + public string Username { get; set; } + public string Filename { get; set; } + public DateTime Enqueued { get; set; } = DateTime.UtcNow; + public DateTime? Ready { get; set; } = null; + public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource(); + } + } +} -- cgit v1.2.3 From 4d2ae22106b88d80873b80abea58f9c3b9c3530f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 31 Jan 2022 22:51:45 -0600 Subject: rough in UploadQueue --- src/slskd/Application.cs | 18 +++++- src/slskd/Startup.cs | 1 + src/slskd/Transfers/UploadQueue.cs | 126 ++++++++++++++++++++++++++++--------- 3 files changed, 114 insertions(+), 31 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index d1257b21..3e91e99e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -69,6 +69,7 @@ namespace slskd ISharedFileCache sharedFileCache, IPushbulletService pushbulletService, IGovernor governor, + IUploadQueue uploadQueue, IHubContext applicationHub, IHubContext logHub) { @@ -91,6 +92,7 @@ namespace slskd Pushbullet = pushbulletService; Governor = governor; + UploadQueue = uploadQueue; RoomService = roomService; ApplicationHub = applicationHub; @@ -129,6 +131,7 @@ namespace slskd private IBrowseTracker BrowseTracker { get; set; } private IConversationTracker ConversationTracker { get; set; } private IGovernor Governor { get; set; } + private IUploadQueue UploadQueue { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); private Options Options => OptionsMonitor.CurrentValue; @@ -552,10 +555,20 @@ 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), + stateChanged: (e) => + { + tracker.AddOrUpdate(e, cts); + + if (e.Transfer.State.HasFlag(TransferStates.Queued)) + { + UploadQueue.Enqueue(e.Transfer); + } + }, progressUpdated: (e) => tracker.AddOrUpdate(e, cts), governor: (tx, req, ct) => Governor.GetBytesAsync(tx, req, ct), - reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx, att, grant, act)); + reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx, att, grant, act), + slotAwaiter: (tx, ct) => UploadQueue.StartAsync(tx), + slotReleased: (tx) => UploadQueue.Complete(tx)); // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and // uploads would be handled separately. @@ -563,6 +576,7 @@ namespace slskd { using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); + }).ContinueWith(t => { Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index 15baa98d..b750ab4d 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -261,6 +261,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); } /// diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs index f00d821f..d7348aa3 100644 --- a/src/slskd/Transfers/UploadQueue.cs +++ b/src/slskd/Transfers/UploadQueue.cs @@ -48,34 +48,39 @@ namespace slskd.Transfers IOptionsMonitor optionsMonitor) { Users = userService; + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(Configure); + + Configure(OptionsMonitor.CurrentValue); } private IUserService Users { get; } private IOptionsMonitor OptionsMonitor { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private ConcurrentDictionary ActiveUploadCounts { get; } = new ConcurrentDictionary(); - private ConcurrentDictionary> WaitingUploads { get; } = new ConcurrentDictionary>(); + private int MaxSlots { get; set; } = 0; + private Dictionary Groups { get; set; } = new Dictionary(); + private ConcurrentDictionary> Uploads { get; } = new ConcurrentDictionary>(); public void Enqueue(Transfer transfer) { var group = Users.GetGroup(transfer.Username); - - var entry = new Entry() { Username = transfer.Username, Filename = transfer.Filename }; + var upload = new Upload() { Username = transfer.Username, Filename = transfer.Filename }; SyncRoot.Wait(); try { - WaitingUploads.AddOrUpdate( + Uploads.AddOrUpdate( key: group, - addValue: new List(new[] { entry }), - updateValueFactory: (key, bag) => + addValue: new List(new[] { upload }), + updateValueFactory: (key, list) => { - bag.Add(entry); - return bag; + list.Add(upload); + return list; }); + Console.WriteLine($"[ENQUEUED]: {upload.ToJson()}"); } finally { @@ -92,7 +97,7 @@ namespace slskd.Transfers try { - if (!WaitingUploads.TryGetValue(group, out var list)) + if (!Uploads.TryGetValue(group, out var list)) { throw new Exception($"No such group: {group}"); } @@ -106,6 +111,8 @@ namespace slskd.Transfers entry.Ready = DateTime.UtcNow; + Console.WriteLine($"[READY]: {entry.ToJson()}"); + return entry.TaskCompletionSource.Task; } finally @@ -123,19 +130,8 @@ namespace slskd.Transfers try { - if (!WaitingUploads.TryGetValue(group, out var list)) - { - throw new Exception($"No such group: {group}"); - } - - var entry = list.FirstOrDefault(e => e.Username == transfer.Username && e.Filename == transfer.Filename); - - list.Remove(entry); - - ActiveUploadCounts.AddOrUpdate( - key: group, - addValue: 0, - updateValueFactory: (key, count) => Math.Min(0, --count)); + Groups[group].UsedSlots = Math.Min(0, Groups[group].UsedSlots - 1); + Console.WriteLine($"Slot returned to group {group}"); } finally { @@ -150,11 +146,47 @@ namespace slskd.Transfers try { - // sort groups in ascending priority order - // while slots are available - // take lowest priority group - // sort waiting uploads according to strategy - // release uploads in order, up to the slot limit of the group + if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots) + { + Console.WriteLine($"All global slots are used, nothing to process (used: {Groups.Values.Sum(g => g.UsedSlots)}, max: {MaxSlots})"); + return; + } + + if (!Uploads.Values.Any(v => v.Any(u => u.Ready.HasValue))) + { + Console.WriteLine($"No ready uploads for any group, nothing to process"); + return; + } + + foreach (var group in Groups.Values.OrderBy(g => g.Priority)) + { + Console.WriteLine($"Processing group {group.Name} (slots: {group.Slots}, used: {group.UsedSlots}, strategy: {group.Strategy})"); + + if (group.UsedSlots >= group.Slots) + { + Console.WriteLine($"{group.Name} has no available slots, skipping (used: {group.UsedSlots}, max: {group.Slots})"); + continue; + } + + if (!Uploads.TryGetValue(group.Name, out var uploads) || !uploads.Any(u => u.Ready.HasValue)) + { + Console.WriteLine($"{group.Name} has no ready uploads, skippling"); + continue; + } + + var ready = uploads.Where(u => u.Ready.HasValue); + Console.WriteLine($"{group.Name} has {uploads.Count} uploads, {ready.Count()} of which are ready"); + + var upload = ready + .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) + .FirstOrDefault(); + + Console.WriteLine($"Next upload for group {group.Name} using strategy {group.Strategy}: {upload.Filename} to {upload.Username}"); + + uploads.Remove(upload); + upload.TaskCompletionSource.SetResult(); + group.UsedSlots++; + } } finally { @@ -162,7 +194,43 @@ namespace slskd.Transfers } } - private class Entry + private void Configure(Options options) + { + var o = OptionsMonitor.CurrentValue.Groups; + + var groups = new List() + { + new Group() + { + Name = "default", + Priority = o.Default.Upload.Priority, + Slots = o.Default.Upload.Slots, + Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), o.Default.Upload.Strategy, true), + }, + }; + + groups.AddRange(o.UserDefined.Select(kvp => new Group() + { + Name = kvp.Key, + Priority = kvp.Value.Upload.Priority, + Slots = kvp.Value.Upload.Slots, + Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), kvp.Value.Upload.Strategy, true), + })); + + Groups = groups.ToDictionary(g => g.Name); + MaxSlots = options.Global.Upload.Slots; + } + + private 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; } + } + + private class Upload { public string Username { get; set; } public string Filename { get; set; } -- cgit v1.2.3 From 1d2a7ad2244b39d6e3c415c3e124bd536ccd434e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 31 Jan 2022 22:58:20 -0600 Subject: add note about copying slots --- src/slskd/Transfers/UploadQueue.cs | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs index d7348aa3..69bed107 100644 --- a/src/slskd/Transfers/UploadQueue.cs +++ b/src/slskd/Transfers/UploadQueue.cs @@ -196,29 +196,40 @@ namespace slskd.Transfers private void Configure(Options options) { - var o = OptionsMonitor.CurrentValue.Groups; + SyncRoot.Wait(); - var groups = new List() + try + { + var o = OptionsMonitor.CurrentValue.Groups; + + var groups = new List() { new Group() { Name = "default", Priority = o.Default.Upload.Priority, Slots = o.Default.Upload.Slots, + UsedSlots = 0, // TODO: copy this from existing group Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), o.Default.Upload.Strategy, true), }, }; - groups.AddRange(o.UserDefined.Select(kvp => new Group() + groups.AddRange(o.UserDefined.Select(kvp => new Group() + { + Name = kvp.Key, + Priority = kvp.Value.Upload.Priority, + Slots = kvp.Value.Upload.Slots, + UsedSlots = 0, // TODO: copy this from existing group + Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), kvp.Value.Upload.Strategy, true), + })); + + Groups = groups.ToDictionary(g => g.Name); + MaxSlots = options.Global.Upload.Slots; + } + finally { - Name = kvp.Key, - Priority = kvp.Value.Upload.Priority, - Slots = kvp.Value.Upload.Slots, - Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), kvp.Value.Upload.Strategy, true), - })); - - Groups = groups.ToDictionary(g => g.Name); - MaxSlots = options.Global.Upload.Slots; + SyncRoot.Release(); + } } private class Group -- cgit v1.2.3 From a7d5a64092cd76b632aeac9d8476d912c96adf5b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 1 Feb 2022 09:01:48 -0600 Subject: disambiguate class name for swagger serialization --- src/slskd/Options.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 302b01d0..b97c40d1 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -399,18 +399,18 @@ namespace slskd /// Gets global upload options. /// [Validate] - public UploadOptions Upload { get; init; } = new UploadOptions(); + public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions(); /// /// Gets global download options. /// [Validate] - public DownloadOptions Download { get; init; } = new DownloadOptions(); + public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions(); /// /// Global upload options. /// - public class UploadOptions + public class GlobalUploadOptions { /// /// Gets the limit for the total number of upload slots. @@ -435,7 +435,7 @@ namespace slskd /// /// Gets global download options. /// - public class DownloadOptions + public class GlobalDownloadOptions { /// /// Gets the limit for the total number of download slots. -- cgit v1.2.3 From a2206e6b06980e270dd57e8255c61612c4f52ca7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 1 Feb 2022 21:43:36 -0600 Subject: sort groups by priority when mapping users --- src/slskd/Users/UserService.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 1f037d3d..5a6170fc 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -20,7 +20,9 @@ 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; @@ -60,17 +62,21 @@ namespace slskd.Users private IDbContextFactory ContextFactory { get; } private IOptionsMonitor OptionsMonitor { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); - private Dictionary Map { get; set; } = new Dictionary(); + private ConcurrentDictionary Map { get; set; } = new ConcurrentDictionary(); private void Configure(Options options) { - var map = new Dictionary(); + var map = new ConcurrentDictionary(); - foreach (var group in options.Groups.UserDefined) + // sort by priority, ascending + foreach (var group in options.Groups.UserDefined.OrderBy(kvp => kvp.Value.Upload.Priority)) { foreach (var user in group.Value.Members) { - map.Add(user, group.Key); + // 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); } } -- cgit v1.2.3 From 8d77e37304d16cae7d1b4528cdbce8ffd62e02ee Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 2 Feb 2022 08:22:43 -0600 Subject: add TransferService to encapsulate Governor and UploadQueue --- src/slskd/Application.cs | 21 ++++----- src/slskd/Startup.cs | 4 +- src/slskd/Transfers/TransferService.cs | 78 ++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 16 deletions(-) create mode 100644 src/slskd/Transfers/TransferService.cs (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 3e91e99e..2b6177d6 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -62,14 +62,13 @@ namespace slskd IManagedState state, ISoulseekClient soulseekClient, ITransferTracker transferTracker, + ITransferService transferService, IBrowseTracker browseTracker, IConversationTracker conversationTracker, IRoomTracker roomTracker, IRoomService roomService, ISharedFileCache sharedFileCache, IPushbulletService pushbulletService, - IGovernor governor, - IUploadQueue uploadQueue, IHubContext applicationHub, IHubContext logHub) { @@ -87,13 +86,11 @@ namespace slskd SharedFileCache.StateMonitor.OnChange(state => SharedFileCacheState_OnChange(state)); TransferTracker = transferTracker; + Transfers = transferService; BrowseTracker = browseTracker; ConversationTracker = conversationTracker; Pushbullet = pushbulletService; - Governor = governor; - UploadQueue = uploadQueue; - RoomService = roomService; ApplicationHub = applicationHub; @@ -130,8 +127,6 @@ namespace slskd private IRoomService RoomService { get; set; } private IBrowseTracker BrowseTracker { get; set; } private IConversationTracker ConversationTracker { get; set; } - private IGovernor Governor { get; set; } - private IUploadQueue UploadQueue { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); private Options Options => OptionsMonitor.CurrentValue; @@ -144,6 +139,7 @@ namespace slskd private DateTime SharesRefreshStarted { get; set; } private IManagedState State { get; } private ITransferTracker TransferTracker { get; set; } + private ITransferService Transfers { get; init; } private IHubContext ApplicationHub { get; set; } private IHubContext LogHub { get; set; } @@ -561,14 +557,14 @@ namespace slskd if (e.Transfer.State.HasFlag(TransferStates.Queued)) { - UploadQueue.Enqueue(e.Transfer); + Transfers.Uploads.Enqueue(e.Transfer); } }, progressUpdated: (e) => tracker.AddOrUpdate(e, cts), - governor: (tx, req, ct) => Governor.GetBytesAsync(tx, req, ct), - reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx, att, grant, act), - slotAwaiter: (tx, ct) => UploadQueue.StartAsync(tx), - slotReleased: (tx) => UploadQueue.Complete(tx)); + governor: (tx, req, ct) => Transfers.Governor.GetBytesAsync(tx, req, ct), + reporter: (tx, att, grant, act) => Transfers.Governor.ReturnBytes(tx, att, grant, act), + slotAwaiter: (tx, ct) => Transfers.Uploads.AwaitStartAsync(tx), + slotReleased: (tx) => Transfers.Uploads.Complete(tx)); // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and // uploads would be handled separately. @@ -576,7 +572,6 @@ namespace slskd { using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); - }).ContinueWith(t => { Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); diff --git a/src/slskd/Startup.cs b/src/slskd/Startup.cs index b750ab4d..b1af2482 100644 --- a/src/slskd/Startup.cs +++ b/src/slskd/Startup.cs @@ -254,14 +254,12 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - - services.AddSingleton(); - services.AddSingleton(); } /// diff --git a/src/slskd/Transfers/TransferService.cs b/src/slskd/Transfers/TransferService.cs new file mode 100644 index 00000000..952e5e38 --- /dev/null +++ b/src/slskd/Transfers/TransferService.cs @@ -0,0 +1,78 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Transfers +{ + using slskd.Users; + + /// + /// Manages transfers. + /// + public interface ITransferService + { + /// + /// Gets the upload governor. + /// + IGovernor Governor { get; } + + /// + /// Gets the upload queue. + /// + IUploadQueue Uploads { get; } + } + + /// + /// Manages transfers. + /// + public class TransferService : ITransferService + { + /// + /// Initializes a new instance of the class. + /// + /// The UserService instance to use. + /// The OptionsMonitor instance to use. + /// The optional Governor instance to use. + /// The optional UploadQueue instance to use. + public TransferService( + IUserService userService, + IOptionsMonitor optionsMonitor, + IGovernor governor = null, + IUploadQueue uploadQueue = null) + { + Users = userService; + OptionsMonitor = optionsMonitor; + + Governor = governor ?? new Governor(userService: Users, optionsMonitor: OptionsMonitor); + Uploads = uploadQueue ?? new UploadQueue(userService: Users, optionsMonitor: OptionsMonitor); + } + + /// + /// Gets the upload governor. + /// + public IGovernor Governor { get; init; } + + /// + /// Gets the upload queue. + /// + public IUploadQueue Uploads { get; init; } + + private IOptionsMonitor OptionsMonitor { get; init; } + private IUserService Users { get; init; } + } +} \ No newline at end of file -- cgit v1.2.3 From 9dda24ccfab947932df56f6d808a2dde48e0d163 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 2 Feb 2022 08:22:59 -0600 Subject: docs --- src/slskd/Transfers/UploadQueue.cs | 41 ++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs index 69bed107..aa051197 100644 --- a/src/slskd/Transfers/UploadQueue.cs +++ b/src/slskd/Transfers/UploadQueue.cs @@ -33,8 +33,23 @@ namespace slskd.Transfers /// public interface IUploadQueue { + /// + /// Enqueues an upload. + /// + /// The upload to enqueue. void Enqueue(Transfer transfer); - Task StartAsync(Transfer transfer); + + /// + /// Awaits the start of an upload. + /// + /// The upload for which to wait. + /// The operation context. + Task AwaitStartAsync(Transfer transfer); + + /// + /// Signals the completion of an upload. + /// + /// The completed upload. void Complete(Transfer transfer); } @@ -43,6 +58,11 @@ namespace slskd.Transfers /// public class UploadQueue : IUploadQueue { + /// + /// Initializes a new instance of the class. + /// + /// The UserService instance to use. + /// The OptionsMonitor instance to use. public UploadQueue( IUserService userService, IOptionsMonitor optionsMonitor) @@ -62,6 +82,10 @@ namespace slskd.Transfers private Dictionary Groups { get; set; } = new Dictionary(); private ConcurrentDictionary> Uploads { get; } = new ConcurrentDictionary>(); + /// + /// Enqueues an upload. + /// + /// The upload to enqueue. public void Enqueue(Transfer transfer) { var group = Users.GetGroup(transfer.Username); @@ -89,7 +113,12 @@ namespace slskd.Transfers } } - public Task StartAsync(Transfer transfer) + /// + /// Awaits the start of an upload. + /// + /// The upload for which to wait. + /// The operation context. + public Task AwaitStartAsync(Transfer transfer) { var group = Users.GetGroup(transfer.Username); @@ -122,6 +151,10 @@ namespace slskd.Transfers } } + /// + /// Signals the completion of an upload. + /// + /// The completed upload. public void Complete(Transfer transfer) { var group = Users.GetGroup(transfer.Username); @@ -232,7 +265,7 @@ namespace slskd.Transfers } } - private class Group + private sealed class Group { public string Name { get; set; } public int Slots { get; set; } @@ -241,7 +274,7 @@ namespace slskd.Transfers public int UsedSlots { get; set; } } - private class Upload + private sealed class Upload { public string Username { get; set; } public string Filename { get; set; } -- cgit v1.2.3 From 75cd4f807eedd018f5c4e49f00973a5a20aaeb6c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Feb 2022 09:16:56 -0600 Subject: add constants for built in groups --- src/slskd/Application.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 2b6177d6..2b3b4e0d 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -54,6 +54,21 @@ namespace slskd public sealed class Application : IApplication { + /// + /// The name of the default user group. + /// + public static readonly string DefaultGroup = "default"; + + /// + /// The name of the priviledged user group. + /// + public static readonly string PriviledgedGroup = "priviledged"; + + /// + /// The name of the leecher user group. + /// + public static readonly string LeecherGroup = "leechers"; + private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes public Application( -- cgit v1.2.3 From 40b858f4710a3762390cfa0eb9415caeaa6ed39e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Feb 2022 09:36:34 -0600 Subject: validate group overlap --- src/slskd/Options.cs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index b97c40d1..f7e1266d 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -461,20 +461,46 @@ namespace slskd /// /// User groups. /// - public class GroupsOptions + public class GroupsOptions : IValidatableObject { /// /// Gets options for the default user group. /// + /// + /// 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. + /// [Validate] public BuiltInOptions Default { get; init; } = new BuiltInOptions(); + /// + /// Gets options for the leecher user group. + /// + /// + /// These options apply to users that have been identified as leechers, and have not been added as a member of any group. + /// + [Validate] + public BuiltInOptions Leechers { get; init; } = new BuiltInOptions(); + /// /// Gets user defined groups and options. /// [Validate] public Dictionary UserDefined { get; init; } = new Dictionary(); + /// + /// Extended validation. + /// + /// + /// + public IEnumerable 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.")); + } + /// /// Built in user group options. /// -- cgit v1.2.3 From 6df03a2dbe92c84309553661bec24873f5b5d204 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Feb 2022 09:37:04 -0600 Subject: add ToSHA1 --- src/slskd/Common/Extensions.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index ebf16fce..736d8863 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -25,6 +25,7 @@ namespace slskd using System.Net.Sockets; using System.Numerics; using System.Reflection; + using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; @@ -325,6 +326,17 @@ namespace slskd obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); } + /// + /// Returns the SHA1 hash of the input string. + /// + /// The string to hash. + /// The computed SHA1 hash. + public static string ToSHA1(this string str) + { + using var sha = SHA1.Create(); + return BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); + } + /// /// Redacts this instance of Options, replacing properties marked with with '*****'. /// -- cgit v1.2.3 From 5322c596f4baf688e2467571af60318d077fec9c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Feb 2022 09:48:41 -0600 Subject: configure additional built in groups, copy used slots from existing config --- src/slskd/Transfers/UploadQueue.cs | 59 ++++++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs index aa051197..aed43bed 100644 --- a/src/slskd/Transfers/UploadQueue.cs +++ b/src/slskd/Transfers/UploadQueue.cs @@ -77,6 +77,7 @@ namespace slskd.Transfers private IUserService Users { get; } private IOptionsMonitor OptionsMonitor { get; } + private string LastOptionsHash { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private int MaxSlots { get; set; } = 0; private Dictionary Groups { get; set; } = new Dictionary(); @@ -103,8 +104,6 @@ namespace slskd.Transfers list.Add(upload); return list; }); - - Console.WriteLine($"[ENQUEUED]: {upload.ToJson()}"); } finally { @@ -128,20 +127,17 @@ namespace slskd.Transfers { if (!Uploads.TryGetValue(group, out var list)) { - throw new Exception($"No such group: {group}"); + throw new SlskdException($"Error resolving list for upload group '{group}'"); } var entry = list.FirstOrDefault(e => e.Username == transfer.Username && e.Filename == transfer.Filename); if (entry == default) { - throw new Exception($"No such transfer: {transfer.Username}/{transfer.Filename}"); + throw new SlskdException($"No such transfer: {transfer.Filename} to {transfer.Username}"); } entry.Ready = DateTime.UtcNow; - - Console.WriteLine($"[READY]: {entry.ToJson()}"); - return entry.TaskCompletionSource.Task; } finally @@ -164,7 +160,6 @@ namespace slskd.Transfers try { Groups[group].UsedSlots = Math.Min(0, Groups[group].UsedSlots - 1); - Console.WriteLine($"Slot returned to group {group}"); } finally { @@ -181,13 +176,11 @@ namespace slskd.Transfers { if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots) { - Console.WriteLine($"All global slots are used, nothing to process (used: {Groups.Values.Sum(g => g.UsedSlots)}, max: {MaxSlots})"); return; } if (!Uploads.Values.Any(v => v.Any(u => u.Ready.HasValue))) { - Console.WriteLine($"No ready uploads for any group, nothing to process"); return; } @@ -229,35 +222,63 @@ namespace slskd.Transfers private void Configure(Options options) { + int GetExistingUsedSlotsOrDefault(string group) + => Groups.ContainsKey(group) ? Groups[group].UsedSlots : 0; + SyncRoot.Wait(); try { - var o = OptionsMonitor.CurrentValue.Groups; + MaxSlots = options.Global.Upload.Slots; + + // don't rebuild everything if nothing changed + if (options.Groups.ToJson().ToSHA1() == LastOptionsHash) + { + return; + } + // statically add built-in groups var groups = new List() { new Group() { - Name = "default", - Priority = o.Default.Upload.Priority, - Slots = o.Default.Upload.Slots, - UsedSlots = 0, // TODO: copy this from existing group - Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), o.Default.Upload.Strategy, true), + Name = Application.PriviledgedGroup, + Priority = 0, + Slots = MaxSlots, + UsedSlots = GetExistingUsedSlotsOrDefault(Application.PriviledgedGroup), + Strategy = QueueStrategy.RoundRobin, + }, + 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), }, }; - groups.AddRange(o.UserDefined.Select(kvp => new Group() + // 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 = 0, // TODO: copy this from existing group + UsedSlots = GetExistingUsedSlotsOrDefault(kvp.Key), Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), kvp.Value.Upload.Strategy, true), })); Groups = groups.ToDictionary(g => g.Name); - MaxSlots = options.Global.Upload.Slots; + + LastOptionsHash = options.Groups.ToJson().ToSHA1(); } finally { -- cgit v1.2.3 From b76b9ca7160a04101bb488122d822299959f9096 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Feb 2022 09:48:53 -0600 Subject: add config todos --- src/slskd/Transfers/Governor.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Governor.cs b/src/slskd/Transfers/Governor.cs index f58815b4..6e065f8b 100644 --- a/src/slskd/Transfers/Governor.cs +++ b/src/slskd/Transfers/Governor.cs @@ -131,10 +131,15 @@ namespace slskd.Transfers private void Configure(Options options) { + // todo: only do this if the speed changed DefaultTokenBucket = new TokenBucket((options.Groups.Default.Upload.SpeedLimit * 1024L) / 10, 100); var tokenBuckets = new Dictionary(); + // todo: diff the existing dictionary and: + // todo: remove groups that no longer exist + // todo: add new groups + // todo: update existing groups with a new token bucket, but only if the speed for that group changed foreach (var group in options.Groups.UserDefined) { tokenBuckets.Add(group.Key, new TokenBucket((group.Value.Upload.SpeedLimit * 1024L) / 10, 100)); -- cgit v1.2.3 From 26de2c48a77d295b9529a9a5774663a6056b5b5b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Feb 2022 09:49:12 -0600 Subject: use group constant from Application --- src/slskd/Users/UserService.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 5a6170fc..b6ae4e30 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -35,7 +35,6 @@ namespace slskd.Users public class UserService : IUserService { private const int CacheTTLSeconds = 300; - private static readonly string DefaultGroup = "default"; /// /// Initializes a new instance of the class. @@ -43,7 +42,6 @@ namespace slskd.Users /// /// The database context to use. /// - /// The logger. public UserService( ISoulseekClient soulseekClient, IDbContextFactory contextFactory, @@ -86,7 +84,7 @@ namespace slskd.Users public string GetGroup(string username) { - return Map.GetValueOrDefault(username, DefaultGroup); + return Map.GetValueOrDefault(username, Application.DefaultGroup); } /// -- cgit v1.2.3 From 631b0082590d37efc6fe65b02ec81a4cefde8ff7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Feb 2022 21:11:38 -0600 Subject: add buckets for other built-ins --- src/slskd/Transfers/Governor.cs | 42 ++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Governor.cs b/src/slskd/Transfers/Governor.cs index 6e065f8b..80114102 100644 --- a/src/slskd/Transfers/Governor.cs +++ b/src/slskd/Transfers/Governor.cs @@ -77,9 +77,9 @@ namespace slskd.Transfers Configure(OptionsMonitor.CurrentValue); } - private ITokenBucket DefaultTokenBucket { get; set; } = new TokenBucket((int.MaxValue * 1024L) / 10, 100); - private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } + private string LastOptionsHash { get; set; } + private int LastGlobalSpeedLimit { get; set; } private Dictionary TokenBuckets { get; set; } = new Dictionary(); private IUserService Users { get; } @@ -97,7 +97,7 @@ namespace slskd.Transfers public Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) { var group = Users.GetGroup(transfer.Username); - var bucket = TokenBuckets.GetValueOrDefault(group, DefaultTokenBucket); + var bucket = TokenBuckets.GetValueOrDefault(group, TokenBuckets[Application.DefaultGroup]); return bucket.GetAsync(requestedBytes, cancellationToken); } @@ -119,7 +119,7 @@ namespace slskd.Transfers } var group = Users.GetGroup(transfer.Username); - var bucket = TokenBuckets.GetValueOrDefault(group, DefaultTokenBucket); + var bucket = TokenBuckets.GetValueOrDefault(group, 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. @@ -131,22 +131,38 @@ namespace slskd.Transfers private void Configure(Options options) { - // todo: only do this if the speed changed - DefaultTokenBucket = new TokenBucket((options.Groups.Default.Upload.SpeedLimit * 1024L) / 10, 100); + static long ComputeBucketCapacity(int speed) + => speed * 1024L / 10; - var tokenBuckets = new Dictionary(); + static TokenBucket CreateBucket(int speed) + => new(ComputeBucketCapacity(speed), 100); + + if (options.Groups.ToJson().ToSHA1() == 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() + { + { Application.PriviledgedGroup, CreateBucket(options.Global.Upload.SpeedLimit) }, + { Application.DefaultGroup, CreateBucket(options.Groups.Default.Upload.SpeedLimit) }, + { Application.LeecherGroup, CreateBucket(options.Groups.Leechers.Upload.SpeedLimit) }, + }; - // todo: diff the existing dictionary and: - // todo: remove groups that no longer exist - // todo: add new groups - // todo: update existing groups with a new token bucket, but only if the speed for that group changed foreach (var group in options.Groups.UserDefined) { - tokenBuckets.Add(group.Key, new TokenBucket((group.Value.Upload.SpeedLimit * 1024L) / 10, 100)); + tokenBuckets.Add(group.Key, CreateBucket(group.Value.Upload.SpeedLimit)); } TokenBuckets = tokenBuckets; - Log.Debug("Reconfigured governor for {Count} groups", TokenBuckets.Count); + + LastGlobalSpeedLimit = options.Global.Upload.SpeedLimit; + LastOptionsHash = options.Groups.ToJson().ToSHA1(); } } } \ No newline at end of file -- cgit v1.2.3 From 048622f9b42a3a03bf29c48e12e497a945103598 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Feb 2022 22:04:03 -0600 Subject: remove serilog using --- src/slskd/Transfers/Governor.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Governor.cs b/src/slskd/Transfers/Governor.cs index 80114102..76fbb1fb 100644 --- a/src/slskd/Transfers/Governor.cs +++ b/src/slskd/Transfers/Governor.cs @@ -23,7 +23,6 @@ namespace slskd.Transfers using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; - using Serilog; using slskd.Users; using Soulseek; -- cgit v1.2.3 From dd26f1bf2f5cb93edce9a5d9fcdb79afd86d5b32 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 3 Feb 2022 23:10:29 -0600 Subject: wip --- src/slskd/Transfers/UploadQueue.cs | 111 ++++++++++++++++++++++--------------- 1 file changed, 65 insertions(+), 46 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs index aed43bed..de8af8a9 100644 --- a/src/slskd/Transfers/UploadQueue.cs +++ b/src/slskd/Transfers/UploadQueue.cs @@ -89,15 +89,14 @@ namespace slskd.Transfers /// The upload to enqueue. public void Enqueue(Transfer transfer) { - var group = Users.GetGroup(transfer.Username); - var upload = new Upload() { Username = transfer.Username, Filename = transfer.Filename }; - SyncRoot.Wait(); try { + var upload = new Upload() { Username = transfer.Username, Filename = transfer.Filename }; + Uploads.AddOrUpdate( - key: group, + key: transfer.Username, addValue: new List(new[] { upload }), updateValueFactory: (key, list) => { @@ -119,22 +118,20 @@ namespace slskd.Transfers /// The operation context. public Task AwaitStartAsync(Transfer transfer) { - var group = Users.GetGroup(transfer.Username); - SyncRoot.Wait(); try { - if (!Uploads.TryGetValue(group, out var list)) + if (!Uploads.TryGetValue(transfer.Username, out var list)) { - throw new SlskdException($"Error resolving list for upload group '{group}'"); + throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); } var entry = list.FirstOrDefault(e => e.Username == transfer.Username && e.Filename == transfer.Filename); if (entry == default) { - throw new SlskdException($"No such transfer: {transfer.Filename} to {transfer.Username}"); + throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); } entry.Ready = DateTime.UtcNow; @@ -153,13 +150,35 @@ namespace slskd.Transfers /// The completed upload. public void Complete(Transfer transfer) { - var group = Users.GetGroup(transfer.Username); - SyncRoot.Wait(); try { - Groups[group].UsedSlots = Math.Min(0, Groups[group].UsedSlots - 1); + if (!Uploads.TryGetValue(transfer.Username, out var list)) + { + throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); + } + + var entry = list.FirstOrDefault(e => e.Username == transfer.Username && e.Filename == transfer.Filename); + + if (entry == default) + { + throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + } + + // 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(entry.Group)) + { + Groups[entry.Group].UsedSlots = Math.Min(0, Groups[entry.Group].UsedSlots - 1); + } + + list.Remove(entry); + + if (!list.Any()) + { + Uploads.TryRemove(transfer.Username, out _); + } } finally { @@ -174,44 +193,42 @@ namespace slskd.Transfers try { - if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots) - { - return; - } - - if (!Uploads.Values.Any(v => v.Any(u => u.Ready.HasValue))) - { - return; - } + var maxSlotsReached = Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots; + var atLeastOneUploadReady = Uploads.Values.Any(v => v.Any(u => u.Ready.HasValue)); - foreach (var group in Groups.Values.OrderBy(g => g.Priority)) + if (!maxSlotsReached && atLeastOneUploadReady) { - Console.WriteLine($"Processing group {group.Name} (slots: {group.Slots}, used: {group.UsedSlots}, strategy: {group.Strategy})"); - - if (group.UsedSlots >= group.Slots) - { - Console.WriteLine($"{group.Name} has no available slots, skipping (used: {group.UsedSlots}, max: {group.Slots})"); - continue; - } - - if (!Uploads.TryGetValue(group.Name, out var uploads) || !uploads.Any(u => u.Ready.HasValue)) + foreach (var group in Groups.Values.OrderBy(g => g.Priority)) { - Console.WriteLine($"{group.Name} has no ready uploads, skippling"); - continue; + Console.WriteLine($"Processing group {group.Name} (slots: {group.Slots}, used: {group.UsedSlots}, strategy: {group.Strategy})"); + + if (group.UsedSlots >= group.Slots) + { + Console.WriteLine($"{group.Name} has no available slots, skipping (used: {group.UsedSlots}, max: {group.Slots})"); + continue; + } + + // todo: make this work with username as key + if (!Uploads.TryGetValue(group.Name, out var uploads) || !uploads.Any(u => u.Ready.HasValue)) + { + Console.WriteLine($"{group.Name} has no ready uploads, skippling"); + continue; + } + + var ready = uploads.Where(u => u.Ready.HasValue && !u.Started.HasValue); + Console.WriteLine($"{group.Name} has {uploads.Count} uploads, {ready.Count()} of which are ready"); + + var upload = ready + .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) + .FirstOrDefault(); + + Console.WriteLine($"Next upload for group {group.Name} using strategy {group.Strategy}: {upload.Filename} to {upload.Username}"); + + upload.Started = DateTime.UtcNow; + upload.Group = group.Name; + upload.TaskCompletionSource.SetResult(); + group.UsedSlots++; } - - var ready = uploads.Where(u => u.Ready.HasValue); - Console.WriteLine($"{group.Name} has {uploads.Count} uploads, {ready.Count()} of which are ready"); - - var upload = ready - .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) - .FirstOrDefault(); - - Console.WriteLine($"Next upload for group {group.Name} using strategy {group.Strategy}: {upload.Filename} to {upload.Username}"); - - uploads.Remove(upload); - upload.TaskCompletionSource.SetResult(); - group.UsedSlots++; } } finally @@ -299,8 +316,10 @@ namespace slskd.Transfers { 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(); } } -- cgit v1.2.3 From 2cd5da10ac93a787fcf1dd971ed07893d77db96f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Feb 2022 09:47:00 -0600 Subject: long when an upload is requested --- src/slskd/Application.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 2b3b4e0d..40c61182 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -550,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."); -- cgit v1.2.3 From 1d6815d1552244d785c751b7251cb4567ec830d4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Feb 2022 09:58:37 -0600 Subject: log config updates, process queue afterwards --- src/slskd/Transfers/UploadQueue.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs index de8af8a9..2844a7cd 100644 --- a/src/slskd/Transfers/UploadQueue.cs +++ b/src/slskd/Transfers/UploadQueue.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -251,6 +251,7 @@ namespace slskd.Transfers // don't rebuild everything if nothing changed if (options.Groups.ToJson().ToSHA1() == LastOptionsHash) { + Log.Debug($"Skipped upload queue reconfiguration; no changes."); return; } @@ -296,10 +297,13 @@ namespace slskd.Transfers Groups = groups.ToDictionary(g => g.Name); LastOptionsHash = options.Groups.ToJson().ToSHA1(); + + Log.Debug("Reconfigured upload queue. Groups: {Groups}", Groups.ToJson()); } finally { SyncRoot.Release(); + Process(); } } -- cgit v1.2.3 From 3e9bac23fa3c3ba6dbcd28c6dddd1bc7cf8d6a17 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 4 Feb 2022 09:59:00 -0600 Subject: group uploads by group prior to processing queue --- src/slskd/Transfers/UploadQueue.cs | 82 +++++++++++++++++++++++++------------- 1 file changed, 54 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs index 2844a7cd..7a05ea5c 100644 --- a/src/slskd/Transfers/UploadQueue.cs +++ b/src/slskd/Transfers/UploadQueue.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -25,6 +25,7 @@ namespace slskd.Transfers using System.Linq; using System.Threading; using System.Threading.Tasks; + using Serilog; using slskd.Users; using Soulseek; @@ -75,6 +76,7 @@ namespace slskd.Transfers Configure(OptionsMonitor.CurrentValue); } + private ILogger Log { get; set; } = Serilog.Log.ForContext(); private IUserService Users { get; } private IOptionsMonitor OptionsMonitor { get; } private string LastOptionsHash { get; set; } @@ -103,6 +105,8 @@ namespace slskd.Transfers list.Add(upload); return list; }); + + Console.WriteLine($"[QUEUE] [ENQUEUE] {transfer.Username} {transfer.Filename}"); } finally { @@ -127,13 +131,15 @@ namespace slskd.Transfers throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); } - var entry = list.FirstOrDefault(e => e.Username == transfer.Username && e.Filename == transfer.Filename); + var entry = list.FirstOrDefault(e => e.Filename == transfer.Filename); if (entry == default) { throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); } + Console.WriteLine($"[QUEUE] [READY] {transfer.Username} {transfer.Filename}"); + entry.Ready = DateTime.UtcNow; return entry.TaskCompletionSource.Task; } @@ -159,7 +165,7 @@ namespace slskd.Transfers throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); } - var entry = list.FirstOrDefault(e => e.Username == transfer.Username && e.Filename == transfer.Filename); + var entry = list.FirstOrDefault(e => e.Filename == transfer.Filename); if (entry == default) { @@ -170,7 +176,7 @@ namespace slskd.Transfers // the group may have been removed during the transfer. if so, do nothing. if (Groups.ContainsKey(entry.Group)) { - Groups[entry.Group].UsedSlots = Math.Min(0, Groups[entry.Group].UsedSlots - 1); + Groups[entry.Group].UsedSlots = Math.Max(0, Groups[entry.Group].UsedSlots - 1); } list.Remove(entry); @@ -179,6 +185,8 @@ namespace slskd.Transfers { Uploads.TryRemove(transfer.Username, out _); } + + Console.WriteLine($"[QUEUE] [COMPLETE] {transfer.Username} {transfer.Filename}"); } finally { @@ -194,41 +202,59 @@ namespace slskd.Transfers try { var maxSlotsReached = Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots; - var atLeastOneUploadReady = Uploads.Values.Any(v => v.Any(u => u.Ready.HasValue)); - if (!maxSlotsReached && atLeastOneUploadReady) + if (maxSlotsReached) { - foreach (var group in Groups.Values.OrderBy(g => g.Priority)) + return; + } + + var readyUploadsByGroup = Uploads.Aggregate( + seed: new ConcurrentDictionary>(), + func: (groups, user) => { - Console.WriteLine($"Processing group {group.Name} (slots: {group.Slots}, used: {group.UsedSlots}, strategy: {group.Strategy})"); + var ready = user.Value.Where(u => u.Ready.HasValue && !u.Started.HasValue); - if (group.UsedSlots >= group.Slots) + if (ready.Any()) { - Console.WriteLine($"{group.Name} has no available slots, skipping (used: {group.UsedSlots}, max: {group.Slots})"); - continue; + var group = Users.GetGroup(user.Key); + + groups.AddOrUpdate( + key: group, + addValue: new List(ready), + updateValueFactory: (group, list) => + { + list.AddRange(ready); + return list; + }); } - // todo: make this work with username as key - if (!Uploads.TryGetValue(group.Name, out var uploads) || !uploads.Any(u => u.Ready.HasValue)) - { - Console.WriteLine($"{group.Name} has no ready uploads, skippling"); - continue; - } + return groups; + }); - var ready = uploads.Where(u => u.Ready.HasValue && !u.Started.HasValue); - Console.WriteLine($"{group.Name} has {uploads.Count} uploads, {ready.Count()} of which are ready"); + foreach (var group in Groups.Values.OrderBy(g => g.Priority)) + { + if (!readyUploadsByGroup.TryGetValue(group.Name, out var uploads)) + { + continue; + } + + if (group.UsedSlots >= group.Slots) + { + continue; + } - var upload = ready - .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) - .FirstOrDefault(); + Console.WriteLine($"[QUEUE] {group.Name} has {group.Slots} available and {group.UsedSlots} are used"); - Console.WriteLine($"Next upload for group {group.Name} using strategy {group.Strategy}: {upload.Filename} to {upload.Username}"); + var upload = uploads + .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) + .FirstOrDefault(); - upload.Started = DateTime.UtcNow; - upload.Group = group.Name; - upload.TaskCompletionSource.SetResult(); - group.UsedSlots++; - } + Console.WriteLine($"Next upload for group {group.Name} using strategy {group.Strategy}: {upload.Filename} to {upload.Username}"); + + upload.Started = DateTime.UtcNow; + upload.Group = group.Name; + upload.TaskCompletionSource.SetResult(); + group.UsedSlots++; } } finally -- cgit v1.2.3 From 9a3358c52c9f31c15c9675d94e4ff2057b6c8e22 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Feb 2022 15:02:10 -0600 Subject: remove redundant sha1 method --- src/slskd/Common/Extensions.cs | 11 ----------- src/slskd/Transfers/Governor.cs | 4 ++-- 2 files changed, 2 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/Extensions.cs index 736d8863..8b1ead8c 100644 --- a/src/slskd/Common/Extensions.cs +++ b/src/slskd/Common/Extensions.cs @@ -326,17 +326,6 @@ namespace slskd obj.GetType().GetGenericTypeDefinition().IsAssignableFrom(typeof(Dictionary<,>)); } - /// - /// Returns the SHA1 hash of the input string. - /// - /// The string to hash. - /// The computed SHA1 hash. - public static string ToSHA1(this string str) - { - using var sha = SHA1.Create(); - return BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); - } - /// /// Redacts this instance of Options, replacing properties marked with with '*****'. /// diff --git a/src/slskd/Transfers/Governor.cs b/src/slskd/Transfers/Governor.cs index 76fbb1fb..02e0e5bb 100644 --- a/src/slskd/Transfers/Governor.cs +++ b/src/slskd/Transfers/Governor.cs @@ -136,7 +136,7 @@ namespace slskd.Transfers static TokenBucket CreateBucket(int speed) => new(ComputeBucketCapacity(speed), 100); - if (options.Groups.ToJson().ToSHA1() == LastOptionsHash && options.Global.Upload.SpeedLimit == LastGlobalSpeedLimit) + if (Compute.Sha1Hash(options.Groups.ToJson()) == LastOptionsHash && options.Global.Upload.SpeedLimit == LastGlobalSpeedLimit) { return; } @@ -161,7 +161,7 @@ namespace slskd.Transfers TokenBuckets = tokenBuckets; LastGlobalSpeedLimit = options.Global.Upload.SpeedLimit; - LastOptionsHash = options.Groups.ToJson().ToSHA1(); + LastOptionsHash = Compute.Sha1Hash(options.Groups.ToJson()); } } } \ No newline at end of file -- cgit v1.2.3 From 569a99d784c194b692acba7e7844d0e93995af87 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Feb 2022 15:32:46 -0600 Subject: replace sha1 --- src/slskd/Transfers/UploadQueue.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs index 7a05ea5c..91f94252 100644 --- a/src/slskd/Transfers/UploadQueue.cs +++ b/src/slskd/Transfers/UploadQueue.cs @@ -275,7 +275,7 @@ namespace slskd.Transfers MaxSlots = options.Global.Upload.Slots; // don't rebuild everything if nothing changed - if (options.Groups.ToJson().ToSHA1() == LastOptionsHash) + if (Compute.Sha1Hash(options.Groups.ToJson()) == LastOptionsHash) { Log.Debug($"Skipped upload queue reconfiguration; no changes."); return; @@ -322,7 +322,7 @@ namespace slskd.Transfers Groups = groups.ToDictionary(g => g.Name); - LastOptionsHash = options.Groups.ToJson().ToSHA1(); + LastOptionsHash = Compute.Sha1Hash(options.Groups.ToJson()); Log.Debug("Reconfigured upload queue. Groups: {Groups}", Groups.ToJson()); } -- cgit v1.2.3 From 47b72c9c60482f05afb93788fcaa983b9e287320 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Feb 2022 17:17:23 -0600 Subject: simplify hashing/options debounce --- src/slskd/Transfers/Governor.cs | 6 ++++-- src/slskd/Transfers/UploadQueue.cs | 10 ++++------ src/slskd/Users/UserService.cs | 10 +++++++++- 3 files changed, 17 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Governor.cs b/src/slskd/Transfers/Governor.cs index 02e0e5bb..54f62930 100644 --- a/src/slskd/Transfers/Governor.cs +++ b/src/slskd/Transfers/Governor.cs @@ -136,7 +136,9 @@ namespace slskd.Transfers static TokenBucket CreateBucket(int speed) => new(ComputeBucketCapacity(speed), 100); - if (Compute.Sha1Hash(options.Groups.ToJson()) == LastOptionsHash && options.Global.Upload.SpeedLimit == LastGlobalSpeedLimit) + var optionsHash = Compute.Sha1Hash(options.Groups.ToJson()); + + if (optionsHash == LastOptionsHash && options.Global.Upload.SpeedLimit == LastGlobalSpeedLimit) { return; } @@ -161,7 +163,7 @@ namespace slskd.Transfers TokenBuckets = tokenBuckets; LastGlobalSpeedLimit = options.Global.Upload.SpeedLimit; - LastOptionsHash = Compute.Sha1Hash(options.Groups.ToJson()); + LastOptionsHash = optionsHash; } } } \ No newline at end of file diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs index 91f94252..a00e000f 100644 --- a/src/slskd/Transfers/UploadQueue.cs +++ b/src/slskd/Transfers/UploadQueue.cs @@ -274,10 +274,11 @@ namespace slskd.Transfers { MaxSlots = options.Global.Upload.Slots; + var optionsHash = Compute.Sha1Hash(options.Groups.ToJson()); + // don't rebuild everything if nothing changed - if (Compute.Sha1Hash(options.Groups.ToJson()) == LastOptionsHash) + if (optionsHash == LastOptionsHash) { - Log.Debug($"Skipped upload queue reconfiguration; no changes."); return; } @@ -321,10 +322,7 @@ namespace slskd.Transfers })); Groups = groups.ToDictionary(g => g.Name); - - LastOptionsHash = Compute.Sha1Hash(options.Groups.ToJson()); - - Log.Debug("Reconfigured upload queue. Groups: {Groups}", Groups.ToJson()); + LastOptionsHash = optionsHash; } finally { diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index b6ae4e30..a54005f1 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -59,11 +59,19 @@ namespace slskd.Users private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } private IOptionsMonitor OptionsMonitor { get; } + private string LastOptionsHash { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private ConcurrentDictionary Map { get; set; } = new ConcurrentDictionary(); private void Configure(Options options) { + var optionsHash = Compute.Sha1Hash(options.Groups.UserDefined.ToJson()); + + if (optionsHash == LastOptionsHash) + { + return; + } + var map = new ConcurrentDictionary(); // sort by priority, ascending @@ -79,7 +87,7 @@ namespace slskd.Users } Map = map; - Log.Debug("Updated user/group map with {Count} entries", Map.Count); + LastOptionsHash = optionsHash; } public string GetGroup(string username) -- cgit v1.2.3 From 9fd50317dd1eea4f59764ad00aec2594c9bb48c7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Feb 2022 20:50:43 -0600 Subject: initial tests for UserService --- src/slskd/Users/UserService.cs | 60 +++++----- tests/slskd.Tests.Unit/TestOptionsMonitor.cs | 2 +- tests/slskd.Tests.Unit/Transfers/GovernorTests.cs | 63 +++++----- tests/slskd.Tests.Unit/Users/UserServiceTests.cs | 138 ++++++++++++++++++++++ 4 files changed, 204 insertions(+), 59 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Users/UserServiceTests.cs (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index a54005f1..6a42d3d2 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -58,38 +58,16 @@ namespace slskd.Users private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } - private IOptionsMonitor OptionsMonitor { get; } private string LastOptionsHash { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private ConcurrentDictionary Map { get; set; } = new ConcurrentDictionary(); + private IOptionsMonitor OptionsMonitor { get; } - private void Configure(Options options) - { - var optionsHash = Compute.Sha1Hash(options.Groups.UserDefined.ToJson()); - - if (optionsHash == LastOptionsHash) - { - return; - } - - var map = new ConcurrentDictionary(); - - // 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; - } - + /// + /// Gets the name of the group for the specified . + /// + /// The username of the peer. + /// The group for the specified username. public string GetGroup(string username) { return Map.GetValueOrDefault(username, Application.DefaultGroup); @@ -178,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(); + + // 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/tests/slskd.Tests.Unit/TestOptionsMonitor.cs b/tests/slskd.Tests.Unit/TestOptionsMonitor.cs index 92cf2fa5..6c16adf5 100644 --- a/tests/slskd.Tests.Unit/TestOptionsMonitor.cs +++ b/tests/slskd.Tests.Unit/TestOptionsMonitor.cs @@ -32,7 +32,7 @@ namespace slskd.Tests.Unit return new Mock().Object; } - public void RaiseOnchange(TOptions options) + public void RaiseOnChange(TOptions options) { _listener(options, null); } diff --git a/tests/slskd.Tests.Unit/Transfers/GovernorTests.cs b/tests/slskd.Tests.Unit/Transfers/GovernorTests.cs index f6b01b29..9b4743a4 100644 --- a/tests/slskd.Tests.Unit/Transfers/GovernorTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/GovernorTests.cs @@ -1,16 +1,16 @@ -using System.Collections.Generic; -using AutoFixture.Xunit2; -using Moq; -using slskd.Transfers; -using slskd.Users; -using Xunit; - -namespace slskd.Tests.Unit.Transfers +namespace slskd.Tests.Unit.Transfers { + using System.Collections.Generic; + using AutoFixture.Xunit2; + using Moq; + using slskd.Transfers; + using slskd.Users; + using Xunit; + public class GovernorTests { [Fact] - private void Instantiates_With_BuiltIn_Buckets() + public void Instantiates_With_BuiltIn_Buckets() { var (governor, _) = GetFixture(); @@ -23,7 +23,7 @@ namespace slskd.Tests.Unit.Transfers } [Theory, AutoData] - private void Instantiates_With_User_Defined_Buckets(string group1, string group2) + public void Instantiates_With_User_Defined_Buckets(string group1, string group2) { var options = new Options() { @@ -46,40 +46,43 @@ namespace slskd.Tests.Unit.Transfers Assert.True(buckets.ContainsKey(group2)); } - [Theory, AutoData] - private void Reconfigures_Buckets_When_Options_change(string group) + public class Configuration { - var options = new Options() + [Theory, AutoData] + public void Reconfigures_Buckets_When_Options_Change(string group) { - Groups = new Options.GroupsOptions() + var options = new Options() { - UserDefined = new Dictionary() + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary() { { group, new Options.GroupsOptions.UserDefinedOptions() }, } - } - }; + } + }; - // do not pass options; only default buckets - var (governor, mocks) = GetFixture(); + // do not pass options; only default buckets + var (governor, mocks) = GetFixture(); - var buckets = governor.GetProperty>("TokenBuckets"); + var buckets = governor.GetProperty>("TokenBuckets"); - // ensure only default buckets are created - Assert.Equal(3, buckets.Count); - Assert.False(buckets.ContainsKey(group)); + // ensure only default buckets are created + Assert.Equal(3, buckets.Count); + Assert.False(buckets.ContainsKey(group)); - // reconfigure with options - mocks.OptionsMonitor.RaiseOnchange(options); + // reconfigure with options + mocks.OptionsMonitor.RaiseOnChange(options); - // grab the new copy of buckets - buckets = governor.GetProperty>("TokenBuckets"); + // grab the new copy of buckets + buckets = governor.GetProperty>("TokenBuckets"); - Assert.Equal(4, buckets.Count); - Assert.True(buckets.ContainsKey(group)); + Assert.Equal(4, buckets.Count); + Assert.True(buckets.ContainsKey(group)); + } } - private (Governor governor, Mocks mocks) GetFixture(Options options = null) + private static (Governor governor, Mocks mocks) GetFixture(Options options = null) { var mocks = new Mocks(options); var governor = new Governor( diff --git a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs new file mode 100644 index 00000000..4c9a0542 --- /dev/null +++ b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs @@ -0,0 +1,138 @@ +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(string username) + { + var (service, _) = GetFixture(); + + Assert.Equal(Application.DefaultGroup, service.GetGroup(username)); + } + + [Theory, AutoData] + public void Returns_User_Defined_Group(string group, string username) + { + var options = new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary() + { + { + 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() + { + { 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() + { + { + 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 ?? new Options()); + } + + public Mock SoulseekClient { get; } = new Mock(); + public Mock> ContextFactory { get; } = new Mock>(); + public TestOptionsMonitor OptionsMonitor { get; init; } + } + } +} -- cgit v1.2.3 From 331166bd02121faebece8a0cacfff529f2ca1b1b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 7 Feb 2022 08:08:43 -0600 Subject: split uploads out into a service --- src/slskd/Application.cs | 10 +- src/slskd/Transfers/Governor.cs | 169 ---------- src/slskd/Transfers/TransferService.cs | 32 +- src/slskd/Transfers/UploadQueue.cs | 354 --------------------- src/slskd/Transfers/Uploads/UploadGovernor.cs | 169 ++++++++++ src/slskd/Transfers/Uploads/UploadQueue.cs | 354 +++++++++++++++++++++ src/slskd/Transfers/Uploads/UploadService.cs | 34 ++ tests/slskd.Tests.Unit/Transfers/GovernorTests.cs | 106 ------ .../Transfers/Uploads/GovernorTests.cs | 106 ++++++ 9 files changed, 680 insertions(+), 654 deletions(-) delete mode 100644 src/slskd/Transfers/Governor.cs delete mode 100644 src/slskd/Transfers/UploadQueue.cs create mode 100644 src/slskd/Transfers/Uploads/UploadGovernor.cs create mode 100644 src/slskd/Transfers/Uploads/UploadQueue.cs create mode 100644 src/slskd/Transfers/Uploads/UploadService.cs delete mode 100644 tests/slskd.Tests.Unit/Transfers/GovernorTests.cs create mode 100644 tests/slskd.Tests.Unit/Transfers/Uploads/GovernorTests.cs (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 40c61182..b03f1abd 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -574,14 +574,14 @@ namespace slskd if (e.Transfer.State.HasFlag(TransferStates.Queued)) { - Transfers.Uploads.Enqueue(e.Transfer); + Transfers.Uploads.Queue.Enqueue(e.Transfer); } }, progressUpdated: (e) => tracker.AddOrUpdate(e, cts), - governor: (tx, req, ct) => Transfers.Governor.GetBytesAsync(tx, req, ct), - reporter: (tx, att, grant, act) => Transfers.Governor.ReturnBytes(tx, att, grant, act), - slotAwaiter: (tx, ct) => Transfers.Uploads.AwaitStartAsync(tx), - slotReleased: (tx) => Transfers.Uploads.Complete(tx)); + 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. diff --git a/src/slskd/Transfers/Governor.cs b/src/slskd/Transfers/Governor.cs deleted file mode 100644 index 54f62930..00000000 --- a/src/slskd/Transfers/Governor.cs +++ /dev/null @@ -1,169 +0,0 @@ -// -// 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/. -// - -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; - - /// - /// Governs transfer speed. - /// - public interface IGovernor - { - /// - /// Asynchronously obtains a grant of for the specified . - /// - /// - /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the - /// requested amount. - /// - /// The transfer for which the grant is requested. - /// The number of requested bytes. - /// The token to monitor for cancellation. - /// The operation context, including the number of bytes granted. - Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken); - - /// - /// Returns wasted bytes for redistribution. - /// - /// The transfer which generated the waste. - /// The number of bytes that were attempted to be transferred. - /// The number of bytes granted by all governors in the system. - /// The actual number of bytes transferred. - public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes); - } - - /// - /// Governs transfer speed. - /// - public class Governor : IGovernor - { - /// - /// Initializes a new instance of the class. - /// - /// The UserService instance to use. - /// The OptionsMonitor instance to use. - public Governor( - IUserService userService, - IOptionsMonitor optionsMonitor) - { - Users = userService; - - OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(Configure); - - Configure(OptionsMonitor.CurrentValue); - } - - private IOptionsMonitor OptionsMonitor { get; } - private string LastOptionsHash { get; set; } - private int LastGlobalSpeedLimit { get; set; } - private Dictionary TokenBuckets { get; set; } = new Dictionary(); - private IUserService Users { get; } - - /// - /// Asynchronously obtains a grant of for the specified . - /// - /// - /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the - /// requested amount. - /// - /// The transfer for which the grant is requested. - /// The number of requested bytes. - /// The token to monitor for cancellation. - /// The operation context, including the number of bytes granted. - public Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) - { - var group = Users.GetGroup(transfer.Username); - var bucket = TokenBuckets.GetValueOrDefault(group, TokenBuckets[Application.DefaultGroup]); - - return bucket.GetAsync(requestedBytes, cancellationToken); - } - - /// - /// Returns wasted bytes for redistribution. - /// - /// The transfer which generated the waste. - /// The number of bytes that were attempted to be transferred. - /// The number of bytes granted by all governors in the system. - /// The actual number of bytes transferred. - public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes) - { - var waste = Math.Min(0, grantedBytes - actualBytes); - - if (waste == 0) - { - return; - } - - var group = Users.GetGroup(transfer.Username); - var bucket = TokenBuckets.GetValueOrDefault(group, 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() - { - { 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/TransferService.cs b/src/slskd/Transfers/TransferService.cs index 952e5e38..714d85be 100644 --- a/src/slskd/Transfers/TransferService.cs +++ b/src/slskd/Transfers/TransferService.cs @@ -19,6 +19,7 @@ using Microsoft.Extensions.Options; namespace slskd.Transfers { + using slskd.Transfers.Uploads; using slskd.Users; /// @@ -27,14 +28,9 @@ namespace slskd.Transfers public interface ITransferService { /// - /// Gets the upload governor. + /// Gets the upload service. /// - IGovernor Governor { get; } - - /// - /// Gets the upload queue. - /// - IUploadQueue Uploads { get; } + IUploadService Uploads { get; } } /// @@ -47,30 +43,26 @@ namespace slskd.Transfers /// /// The UserService instance to use. /// The OptionsMonitor instance to use. - /// The optional Governor instance to use. - /// The optional UploadQueue instance to use. + /// The optional UploadService instance to use. public TransferService( IUserService userService, IOptionsMonitor optionsMonitor, - IGovernor governor = null, - IUploadQueue uploadQueue = null) + IUploadService uploadService = null) { Users = userService; OptionsMonitor = optionsMonitor; - Governor = governor ?? new Governor(userService: Users, optionsMonitor: OptionsMonitor); - Uploads = uploadQueue ?? new UploadQueue(userService: Users, optionsMonitor: OptionsMonitor); + Uploads = uploadService ?? new UploadService() + { + Governor = new UploadGovernor(userService: Users, optionsMonitor: OptionsMonitor), + Queue = new UploadQueue(userService: Users, optionsMonitor: OptionsMonitor), + }; } /// - /// Gets the upload governor. - /// - public IGovernor Governor { get; init; } - - /// - /// Gets the upload queue. + /// Gets the upload service. /// - public IUploadQueue Uploads { get; init; } + public IUploadService Uploads { get; init; } private IOptionsMonitor OptionsMonitor { get; init; } private IUserService Users { get; init; } diff --git a/src/slskd/Transfers/UploadQueue.cs b/src/slskd/Transfers/UploadQueue.cs deleted file mode 100644 index a00e000f..00000000 --- a/src/slskd/Transfers/UploadQueue.cs +++ /dev/null @@ -1,354 +0,0 @@ -// -// 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/. -// - -using Microsoft.Extensions.Options; - -namespace slskd.Transfers -{ - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.Linq; - using System.Threading; - using System.Threading.Tasks; - using Serilog; - using slskd.Users; - using Soulseek; - - /// - /// Orchestrates uploads. - /// - public interface IUploadQueue - { - /// - /// Enqueues an upload. - /// - /// The upload to enqueue. - void Enqueue(Transfer transfer); - - /// - /// Awaits the start of an upload. - /// - /// The upload for which to wait. - /// The operation context. - Task AwaitStartAsync(Transfer transfer); - - /// - /// Signals the completion of an upload. - /// - /// The completed upload. - void Complete(Transfer transfer); - } - - /// - /// Orchestrates uploads. - /// - public class UploadQueue : IUploadQueue - { - /// - /// Initializes a new instance of the class. - /// - /// The UserService instance to use. - /// The OptionsMonitor instance to use. - public UploadQueue( - IUserService userService, - IOptionsMonitor optionsMonitor) - { - Users = userService; - - OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(Configure); - - Configure(OptionsMonitor.CurrentValue); - } - - private ILogger Log { get; set; } = Serilog.Log.ForContext(); - private IUserService Users { get; } - private IOptionsMonitor OptionsMonitor { get; } - private string LastOptionsHash { get; set; } - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private int MaxSlots { get; set; } = 0; - private Dictionary Groups { get; set; } = new Dictionary(); - private ConcurrentDictionary> Uploads { get; } = new ConcurrentDictionary>(); - - /// - /// Enqueues an upload. - /// - /// The upload to enqueue. - 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(new[] { upload }), - updateValueFactory: (key, list) => - { - list.Add(upload); - return list; - }); - - Console.WriteLine($"[QUEUE] [ENQUEUE] {transfer.Username} {transfer.Filename}"); - } - finally - { - SyncRoot.Release(); - Process(); - } - } - - /// - /// Awaits the start of an upload. - /// - /// The upload for which to wait. - /// The operation context. - 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 entry = list.FirstOrDefault(e => e.Filename == transfer.Filename); - - if (entry == default) - { - throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); - } - - Console.WriteLine($"[QUEUE] [READY] {transfer.Username} {transfer.Filename}"); - - entry.Ready = DateTime.UtcNow; - return entry.TaskCompletionSource.Task; - } - finally - { - SyncRoot.Release(); - Process(); - } - } - - /// - /// Signals the completion of an upload. - /// - /// The completed upload. - 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 entry = list.FirstOrDefault(e => e.Filename == transfer.Filename); - - if (entry == default) - { - throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); - } - - // 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(entry.Group)) - { - Groups[entry.Group].UsedSlots = Math.Max(0, Groups[entry.Group].UsedSlots - 1); - } - - list.Remove(entry); - - if (!list.Any()) - { - Uploads.TryRemove(transfer.Username, out _); - } - - Console.WriteLine($"[QUEUE] [COMPLETE] {transfer.Username} {transfer.Filename}"); - } - finally - { - SyncRoot.Release(); - Process(); - } - } - - private void Process() - { - SyncRoot.Wait(); - - try - { - var maxSlotsReached = Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots; - - if (maxSlotsReached) - { - return; - } - - var readyUploadsByGroup = Uploads.Aggregate( - seed: new ConcurrentDictionary>(), - 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(ready), - updateValueFactory: (group, list) => - { - list.AddRange(ready); - return list; - }); - } - - return groups; - }); - - foreach (var group in Groups.Values.OrderBy(g => g.Priority)) - { - if (!readyUploadsByGroup.TryGetValue(group.Name, out var uploads)) - { - continue; - } - - if (group.UsedSlots >= group.Slots) - { - continue; - } - - Console.WriteLine($"[QUEUE] {group.Name} has {group.Slots} available and {group.UsedSlots} are used"); - - var upload = uploads - .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) - .FirstOrDefault(); - - Console.WriteLine($"Next upload for group {group.Name} using strategy {group.Strategy}: {upload.Filename} to {upload.Username}"); - - upload.Started = DateTime.UtcNow; - upload.Group = group.Name; - upload.TaskCompletionSource.SetResult(); - group.UsedSlots++; - } - } - finally - { - SyncRoot.Release(); - } - } - - private void Configure(Options options) - { - int GetExistingUsedSlotsOrDefault(string group) - => Groups.ContainsKey(group) ? Groups[group].UsedSlots : 0; - - SyncRoot.Wait(); - - try - { - MaxSlots = options.Global.Upload.Slots; - - var optionsHash = Compute.Sha1Hash(options.Groups.ToJson()); - - // don't rebuild everything if nothing changed - if (optionsHash == LastOptionsHash) - { - return; - } - - // statically add built-in groups - var groups = new List() - { - new Group() - { - Name = Application.PriviledgedGroup, - Priority = 0, - Slots = MaxSlots, - UsedSlots = GetExistingUsedSlotsOrDefault(Application.PriviledgedGroup), - Strategy = QueueStrategy.RoundRobin, - }, - 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); - LastOptionsHash = optionsHash; - } - finally - { - SyncRoot.Release(); - Process(); - } - } - - private 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; } - } - - private 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/UploadGovernor.cs b/src/slskd/Transfers/Uploads/UploadGovernor.cs new file mode 100644 index 00000000..c18ea882 --- /dev/null +++ b/src/slskd/Transfers/Uploads/UploadGovernor.cs @@ -0,0 +1,169 @@ +// +// 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/. +// + +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; + + /// + /// Governs upload transfer speed. + /// + public interface IUploadGovernor + { + /// + /// Asynchronously obtains a grant of for the specified . + /// + /// + /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the + /// requested amount. + /// + /// The transfer for which the grant is requested. + /// The number of requested bytes. + /// The token to monitor for cancellation. + /// The operation context, including the number of bytes granted. + Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken); + + /// + /// Returns wasted bytes for redistribution. + /// + /// The transfer which generated the waste. + /// The number of bytes that were attempted to be transferred. + /// The number of bytes granted by all governors in the system. + /// The actual number of bytes transferred. + public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes); + } + + /// + /// Governs upload transfer speed. + /// + public class UploadGovernor : IUploadGovernor + { + /// + /// Initializes a new instance of the class. + /// + /// The UserService instance to use. + /// The OptionsMonitor instance to use. + public UploadGovernor( + IUserService userService, + IOptionsMonitor optionsMonitor) + { + Users = userService; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(Configure); + + Configure(OptionsMonitor.CurrentValue); + } + + private IOptionsMonitor OptionsMonitor { get; } + private string LastOptionsHash { get; set; } + private int LastGlobalSpeedLimit { get; set; } + private Dictionary TokenBuckets { get; set; } = new Dictionary(); + private IUserService Users { get; } + + /// + /// Asynchronously obtains a grant of for the specified . + /// + /// + /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the + /// requested amount. + /// + /// The transfer for which the grant is requested. + /// The number of requested bytes. + /// The token to monitor for cancellation. + /// The operation context, including the number of bytes granted. + public Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) + { + var group = Users.GetGroup(transfer.Username); + var bucket = TokenBuckets.GetValueOrDefault(group, TokenBuckets[Application.DefaultGroup]); + + return bucket.GetAsync(requestedBytes, cancellationToken); + } + + /// + /// Returns wasted bytes for redistribution. + /// + /// The transfer which generated the waste. + /// The number of bytes that were attempted to be transferred. + /// The number of bytes granted by all governors in the system. + /// The actual number of bytes transferred. + public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes) + { + var waste = Math.Min(0, grantedBytes - actualBytes); + + if (waste == 0) + { + return; + } + + var group = Users.GetGroup(transfer.Username); + var bucket = TokenBuckets.GetValueOrDefault(group, 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() + { + { 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..a00e000f --- /dev/null +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -0,0 +1,354 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Transfers +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + using Serilog; + using slskd.Users; + using Soulseek; + + /// + /// Orchestrates uploads. + /// + public interface IUploadQueue + { + /// + /// Enqueues an upload. + /// + /// The upload to enqueue. + void Enqueue(Transfer transfer); + + /// + /// Awaits the start of an upload. + /// + /// The upload for which to wait. + /// The operation context. + Task AwaitStartAsync(Transfer transfer); + + /// + /// Signals the completion of an upload. + /// + /// The completed upload. + void Complete(Transfer transfer); + } + + /// + /// Orchestrates uploads. + /// + public class UploadQueue : IUploadQueue + { + /// + /// Initializes a new instance of the class. + /// + /// The UserService instance to use. + /// The OptionsMonitor instance to use. + public UploadQueue( + IUserService userService, + IOptionsMonitor optionsMonitor) + { + Users = userService; + + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(Configure); + + Configure(OptionsMonitor.CurrentValue); + } + + private ILogger Log { get; set; } = Serilog.Log.ForContext(); + private IUserService Users { get; } + private IOptionsMonitor OptionsMonitor { get; } + private string LastOptionsHash { get; set; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private int MaxSlots { get; set; } = 0; + private Dictionary Groups { get; set; } = new Dictionary(); + private ConcurrentDictionary> Uploads { get; } = new ConcurrentDictionary>(); + + /// + /// Enqueues an upload. + /// + /// The upload to enqueue. + 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(new[] { upload }), + updateValueFactory: (key, list) => + { + list.Add(upload); + return list; + }); + + Console.WriteLine($"[QUEUE] [ENQUEUE] {transfer.Username} {transfer.Filename}"); + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + /// + /// Awaits the start of an upload. + /// + /// The upload for which to wait. + /// The operation context. + 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 entry = list.FirstOrDefault(e => e.Filename == transfer.Filename); + + if (entry == default) + { + throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + } + + Console.WriteLine($"[QUEUE] [READY] {transfer.Username} {transfer.Filename}"); + + entry.Ready = DateTime.UtcNow; + return entry.TaskCompletionSource.Task; + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + /// + /// Signals the completion of an upload. + /// + /// The completed upload. + 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 entry = list.FirstOrDefault(e => e.Filename == transfer.Filename); + + if (entry == default) + { + throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + } + + // 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(entry.Group)) + { + Groups[entry.Group].UsedSlots = Math.Max(0, Groups[entry.Group].UsedSlots - 1); + } + + list.Remove(entry); + + if (!list.Any()) + { + Uploads.TryRemove(transfer.Username, out _); + } + + Console.WriteLine($"[QUEUE] [COMPLETE] {transfer.Username} {transfer.Filename}"); + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + private void Process() + { + SyncRoot.Wait(); + + try + { + var maxSlotsReached = Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots; + + if (maxSlotsReached) + { + return; + } + + var readyUploadsByGroup = Uploads.Aggregate( + seed: new ConcurrentDictionary>(), + 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(ready), + updateValueFactory: (group, list) => + { + list.AddRange(ready); + return list; + }); + } + + return groups; + }); + + foreach (var group in Groups.Values.OrderBy(g => g.Priority)) + { + if (!readyUploadsByGroup.TryGetValue(group.Name, out var uploads)) + { + continue; + } + + if (group.UsedSlots >= group.Slots) + { + continue; + } + + Console.WriteLine($"[QUEUE] {group.Name} has {group.Slots} available and {group.UsedSlots} are used"); + + var upload = uploads + .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) + .FirstOrDefault(); + + Console.WriteLine($"Next upload for group {group.Name} using strategy {group.Strategy}: {upload.Filename} to {upload.Username}"); + + upload.Started = DateTime.UtcNow; + upload.Group = group.Name; + upload.TaskCompletionSource.SetResult(); + group.UsedSlots++; + } + } + finally + { + SyncRoot.Release(); + } + } + + private void Configure(Options options) + { + int GetExistingUsedSlotsOrDefault(string group) + => Groups.ContainsKey(group) ? Groups[group].UsedSlots : 0; + + SyncRoot.Wait(); + + try + { + MaxSlots = options.Global.Upload.Slots; + + var optionsHash = Compute.Sha1Hash(options.Groups.ToJson()); + + // don't rebuild everything if nothing changed + if (optionsHash == LastOptionsHash) + { + return; + } + + // statically add built-in groups + var groups = new List() + { + new Group() + { + Name = Application.PriviledgedGroup, + Priority = 0, + Slots = MaxSlots, + UsedSlots = GetExistingUsedSlotsOrDefault(Application.PriviledgedGroup), + Strategy = QueueStrategy.RoundRobin, + }, + 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); + LastOptionsHash = optionsHash; + } + finally + { + SyncRoot.Release(); + Process(); + } + } + + private 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; } + } + + private 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 +{ + /// + /// Manages uploads. + /// + public interface IUploadService + { + /// + /// Gets the upload governor. + /// + IUploadGovernor Governor { get; } + + /// + /// Gets the upload queue. + /// + IUploadQueue Queue { get; } + } + + /// + /// Manages uploads. + /// + public class UploadService : IUploadService + { + /// + /// Gets the upload governor. + /// + public IUploadGovernor Governor { get; init; } + + /// + /// Gets the upload queue. + /// + public IUploadQueue Queue { get; init; } + } +} diff --git a/tests/slskd.Tests.Unit/Transfers/GovernorTests.cs b/tests/slskd.Tests.Unit/Transfers/GovernorTests.cs deleted file mode 100644 index 9b4743a4..00000000 --- a/tests/slskd.Tests.Unit/Transfers/GovernorTests.cs +++ /dev/null @@ -1,106 +0,0 @@ -namespace slskd.Tests.Unit.Transfers -{ - using System.Collections.Generic; - using AutoFixture.Xunit2; - using Moq; - using slskd.Transfers; - using slskd.Users; - using Xunit; - - public class GovernorTests - { - [Fact] - public void Instantiates_With_BuiltIn_Buckets() - { - var (governor, _) = GetFixture(); - - var buckets = governor.GetProperty>("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() - { - { group1, new Options.GroupsOptions.UserDefinedOptions() }, - { group2, new Options.GroupsOptions.UserDefinedOptions() }, - } - } - }; - - var (governor, _) = GetFixture(options); - - var buckets = governor.GetProperty>("TokenBuckets"); - - Assert.Equal(5, buckets.Count); - Assert.True(buckets.ContainsKey(group1)); - Assert.True(buckets.ContainsKey(group2)); - } - - 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() - { - { group, new Options.GroupsOptions.UserDefinedOptions() }, - } - } - }; - - // do not pass options; only default buckets - var (governor, mocks) = GetFixture(); - - var buckets = governor.GetProperty>("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>("TokenBuckets"); - - Assert.Equal(4, buckets.Count); - Assert.True(buckets.ContainsKey(group)); - } - } - - private static (Governor governor, Mocks mocks) GetFixture(Options options = null) - { - var mocks = new Mocks(options); - var governor = new Governor( - mocks.UserService.Object, - mocks.OptionsMonitor); - - return (governor, mocks); - } - - private class Mocks - { - public Mocks(Options options = null) - { - OptionsMonitor = new TestOptionsMonitor(options ?? new Options()); - } - - public Mock UserService { get; } = new Mock(); - public TestOptionsMonitor OptionsMonitor { get; init; } - } - } -} diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/GovernorTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/GovernorTests.cs new file mode 100644 index 00000000..c386038d --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/GovernorTests.cs @@ -0,0 +1,106 @@ +namespace slskd.Tests.Unit.Transfers.Uploads +{ + using System.Collections.Generic; + using AutoFixture.Xunit2; + using Moq; + using slskd.Transfers; + using slskd.Users; + using Xunit; + + public class GovernorTests + { + [Fact] + public void Instantiates_With_BuiltIn_Buckets() + { + var (governor, _) = GetFixture(); + + var buckets = governor.GetProperty>("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() + { + { group1, new Options.GroupsOptions.UserDefinedOptions() }, + { group2, new Options.GroupsOptions.UserDefinedOptions() }, + } + } + }; + + var (governor, _) = GetFixture(options); + + var buckets = governor.GetProperty>("TokenBuckets"); + + Assert.Equal(5, buckets.Count); + Assert.True(buckets.ContainsKey(group1)); + Assert.True(buckets.ContainsKey(group2)); + } + + 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() + { + { group, new Options.GroupsOptions.UserDefinedOptions() }, + } + } + }; + + // do not pass options; only default buckets + var (governor, mocks) = GetFixture(); + + var buckets = governor.GetProperty>("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>("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 ?? new Options()); + } + + public Mock UserService { get; } = new Mock(); + public TestOptionsMonitor OptionsMonitor { get; init; } + } + } +} -- cgit v1.2.3 From 9aff08103ebe95cca60ff458a6a6cc3a68ffe0e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 7 Feb 2022 08:46:54 -0600 Subject: fix crash from null username, math error --- src/slskd/Transfers/Uploads/UploadGovernor.cs | 6 +++--- src/slskd/Users/UserService.cs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadGovernor.cs b/src/slskd/Transfers/Uploads/UploadGovernor.cs index c18ea882..9221d686 100644 --- a/src/slskd/Transfers/Uploads/UploadGovernor.cs +++ b/src/slskd/Transfers/Uploads/UploadGovernor.cs @@ -96,7 +96,7 @@ namespace slskd.Transfers public Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) { var group = Users.GetGroup(transfer.Username); - var bucket = TokenBuckets.GetValueOrDefault(group, TokenBuckets[Application.DefaultGroup]); + var bucket = TokenBuckets.GetValueOrDefault(group ?? string.Empty, TokenBuckets[Application.DefaultGroup]); return bucket.GetAsync(requestedBytes, cancellationToken); } @@ -110,7 +110,7 @@ namespace slskd.Transfers /// The actual number of bytes transferred. public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes) { - var waste = Math.Min(0, grantedBytes - actualBytes); + var waste = Math.Max(0, grantedBytes - actualBytes); if (waste == 0) { @@ -118,7 +118,7 @@ namespace slskd.Transfers } var group = Users.GetGroup(transfer.Username); - var bucket = TokenBuckets.GetValueOrDefault(group, TokenBuckets[Application.DefaultGroup]); + 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. diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 6a42d3d2..cb56e6dd 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -70,7 +70,7 @@ namespace slskd.Users /// The group for the specified username. public string GetGroup(string username) { - return Map.GetValueOrDefault(username, Application.DefaultGroup); + return Map.GetValueOrDefault(username ?? string.Empty, Application.DefaultGroup); } /// -- cgit v1.2.3 From 3067d26cd92f4388485797482b0ace764bdd11bf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 8 Feb 2022 20:59:42 -0600 Subject: improve logging, add docs --- src/slskd/Transfers/Uploads/UploadQueue.cs | 86 +++++++++++++++++------------- 1 file changed, 50 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index a00e000f..6a839bb3 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -22,6 +22,7 @@ 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; @@ -80,6 +81,7 @@ namespace slskd.Transfers private IUserService Users { get; } private IOptionsMonitor 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 Groups { get; set; } = new Dictionary(); @@ -106,7 +108,7 @@ namespace slskd.Transfers return list; }); - Console.WriteLine($"[QUEUE] [ENQUEUE] {transfer.Username} {transfer.Filename}"); + Log.Debug("Enqueued: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); } finally { @@ -131,17 +133,17 @@ namespace slskd.Transfers throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); } - var entry = list.FirstOrDefault(e => e.Filename == transfer.Filename); + var upload = list.FirstOrDefault(e => e.Filename == transfer.Filename); - if (entry == default) + if (upload == default) { throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); } - Console.WriteLine($"[QUEUE] [READY] {transfer.Username} {transfer.Filename}"); + upload.Ready = DateTime.UtcNow; + Log.Debug("Ready: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued); - entry.Ready = DateTime.UtcNow; - return entry.TaskCompletionSource.Task; + return upload.TaskCompletionSource.Task; } finally { @@ -165,28 +167,30 @@ namespace slskd.Transfers throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); } - var entry = list.FirstOrDefault(e => e.Filename == transfer.Filename); + var upload = list.FirstOrDefault(e => e.Filename == transfer.Filename); - if (entry == default) + 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(entry.Group)) + if (Groups.ContainsKey(upload.Group)) { - Groups[entry.Group].UsedSlots = Math.Max(0, Groups[entry.Group].UsedSlots - 1); - } + var group = Groups[upload.Group]; - list.Remove(entry); + group.UsedSlots = Math.Max(0, group.UsedSlots - 1); + Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); + } - if (!list.Any()) + if (!list.Any() && Uploads.TryRemove(transfer.Username, out _)) { - Uploads.TryRemove(transfer.Username, out _); + Log.Debug("Cleaned up tracking list for {User}; no more queued uploads to track", transfer.Username); } - - Console.WriteLine($"[QUEUE] [COMPLETE] {transfer.Username} {transfer.Filename}"); } finally { @@ -201,13 +205,15 @@ namespace slskd.Transfers try { - var maxSlotsReached = Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots; - - if (maxSlotsReached) + if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots) { return; } + // 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>(), func: (groups, user) => @@ -231,30 +237,32 @@ namespace slskd.Transfers 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)) { - if (!readyUploadsByGroup.TryGetValue(group.Name, out var uploads)) + if (group.UsedSlots >= group.Slots || !readyUploadsByGroup.TryGetValue(group.Name, out var uploads) || !uploads.Any()) { continue; } - if (group.UsedSlots >= group.Slots) - { - continue; - } - - Console.WriteLine($"[QUEUE] {group.Name} has {group.Slots} available and {group.UsedSlots} are used"); - var upload = uploads .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready) - .FirstOrDefault(); - - Console.WriteLine($"Next upload for group {group.Name} using strategy {group.Strategy}: {upload.Filename} to {upload.Username}"); + .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; - upload.TaskCompletionSource.SetResult(); 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); + + break; } } finally @@ -272,26 +280,30 @@ namespace slskd.Transfers try { - MaxSlots = options.Global.Upload.Slots; - var optionsHash = Compute.Sha1Hash(options.Groups.ToJson()); - // don't rebuild everything if nothing changed - if (optionsHash == LastOptionsHash) + if (optionsHash == LastOptionsHash && options.Global.Upload.Slots == LastGlobalSlots) { return; } + MaxSlots = options.Global.Upload.Slots; + // statically add built-in groups var groups = new List() { + // 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.RoundRobin, + Strategy = QueueStrategy.FirstInFirstOut, }, new Group() { @@ -322,6 +334,8 @@ namespace slskd.Transfers })); Groups = groups.ToDictionary(g => g.Name); + + LastGlobalSlots = options.Global.Upload.Slots; LastOptionsHash = optionsHash; } finally -- cgit v1.2.3 From 7dd7970bc9fcce6f4aaece6694ddbdb11eaa0f2a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Feb 2022 08:08:25 -0600 Subject: update TokenBucket implementation --- src/slskd/Common/TokenBucket.cs | 54 ++++++++++++----------------------------- 1 file changed, 16 insertions(+), 38 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/TokenBucket.cs b/src/slskd/Common/TokenBucket.cs index 29fd720c..51a0281b 100644 --- a/src/slskd/Common/TokenBucket.cs +++ b/src/slskd/Common/TokenBucket.cs @@ -77,6 +77,8 @@ namespace slskd /// public class TokenBucket : ITokenBucket, IDisposable { + private TaskCompletionSource waitForReset = new(); + /// /// Initializes a new instance of the class. /// @@ -98,7 +100,7 @@ namespace slskd CurrentCount = Capacity; Clock = new System.Timers.Timer(interval); - Clock.Elapsed += (sender, e) => _ = Reset(); + Clock.Elapsed += (sender, e) => Reset(); Clock.Start(); } @@ -111,7 +113,6 @@ namespace slskd private long CurrentCount { get; set; } private bool Disposed { get; set; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); - private TaskCompletionSource WaitForReset { get; set; } = new TaskCompletionSource(); /// /// Disposes this instance. @@ -196,55 +197,32 @@ namespace slskd private async Task GetInternalAsync(int count, CancellationToken cancellationToken = default) { - Task waitTask = Task.CompletedTask; - await SyncRoot.WaitAsync(cancellationToken).ConfigureAwait(false); try { - // if the bucket has enough tokens to fulfil the request, return them and decrement the bucket - if (CurrentCount >= count) - { - CurrentCount -= count; - return count; - } - - // if the bucket doesn't have enough tokens to fulfil the request, but has some available, return the available - // tokens and zero the bucket - if (CurrentCount > 0) + // if the bucket is empty, wait for a reset, then replenish it before continuing + // this ensures tokens are distributed in the order in which callers obtain the semaphore, + // which is as close to a FIFO as .NET synchronization primitives will allow + if (CurrentCount == 0) { - var availableCount = CurrentCount; - CurrentCount = 0; - return (int)availableCount; + await waitForReset.Task.ConfigureAwait(false); + CurrentCount = Capacity; } - // if the bucket is empty, make the caller wait until the bucket is replenished - waitTask = WaitForReset.Task; + // take the minimum of requested count or CurrentCount, deduct it from + // CurrentCount (potentially zeroing the bucket), and return it + var availableCount = Math.Min(CurrentCount, count); + CurrentCount -= availableCount; + return (int)availableCount; } finally { SyncRoot.Release(); } - - await waitTask.ConfigureAwait(false); - return await GetAsync(count, cancellationToken).ConfigureAwait(false); } - private async Task Reset() - { - await SyncRoot.WaitAsync().ConfigureAwait(false); - - try - { - CurrentCount = Capacity; - - WaitForReset.SetResult(true); - WaitForReset = new TaskCompletionSource(); - } - finally - { - SyncRoot.Release(); - } - } + private void Reset() + => Interlocked.Exchange(ref waitForReset, new TaskCompletionSource()).SetResult(true); } } -- cgit v1.2.3 From 447b95757716a94ccd31b958c8ab86544aff1e1e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Feb 2022 08:09:18 -0600 Subject: bump Soulseek.NET to 4.4.3 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') 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 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From 69f2ad37cbe9baf18ce981e790afa948bb990371 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Feb 2022 21:49:47 -0600 Subject: initial tests for UploadQueue --- src/slskd/Transfers/Uploads/UploadQueue.cs | 4 +- .../Transfers/Uploads/UploadQueueTests.cs | 158 ++++++++++++++++++++- 2 files changed, 155 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 6a839bb3..f441b120 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -345,7 +345,7 @@ namespace slskd.Transfers } } - private sealed class Group + public sealed class Group { public string Name { get; set; } public int Slots { get; set; } @@ -354,7 +354,7 @@ namespace slskd.Transfers public int UsedSlots { get; set; } } - private sealed class Upload + public sealed class Upload { public string Username { get; set; } public string Filename { get; set; } diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index 77a44a2d..7fe0bd3e 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -1,11 +1,159 @@ -using Moq; -using slskd.Transfers; -using slskd.Users; - -namespace slskd.Tests.Unit.Transfers.Uploads +namespace slskd.Tests.Unit.Transfers.Uploads { + using System.Collections.Generic; + using AutoFixture.Xunit2; + using Moq; + using slskd.Transfers; + using slskd.Users; + using Xunit; + public class UploadQueueTests { + [Fact] + public void Instantiates_With_BuiltIn_Groups() + { + var (queue, _) = GetFixture(); + + var groups = queue.GetProperty>("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>("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>("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>("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() + { + { + 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>("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); + } + private static (UploadQueue queue, Mocks mocks) GetFixture(Options options = null) { var mocks = new Mocks(options); -- cgit v1.2.3 From 451f3a4cb38cc8bc2610b5f0e7997ebe992ec9e7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 12 Feb 2022 14:36:50 -0600 Subject: more UploadQueue tests --- src/slskd/Transfers/Uploads/UploadQueue.cs | 2 +- .../Transfers/Uploads/UploadQueueTests.cs | 191 +++++++++++++++++++++ 2 files changed, 192 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index f441b120..34af4b3b 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -77,7 +77,7 @@ namespace slskd.Transfers Configure(OptionsMonitor.CurrentValue); } - private ILogger Log { get; set; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); private IUserService Users { get; } private IOptionsMonitor OptionsMonitor { get; } private string LastOptionsHash { get; set; } diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index 7fe0bd3e..e615ff15 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -1,11 +1,15 @@ namespace slskd.Tests.Unit.Transfers.Uploads { + using System.Collections.Concurrent; using System.Collections.Generic; + using System.Linq; using AutoFixture.Xunit2; using Moq; using slskd.Transfers; using slskd.Users; + using Soulseek; using Xunit; + using static slskd.Transfers.UploadQueue; public class UploadQueueTests { @@ -154,6 +158,190 @@ 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() + { + { + 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>("Groups"); + + // user defined group does not exist + Assert.False(groups.ContainsKey(group)); + + // reconfigure + mocks.OptionsMonitor.RaiseOnChange(options); + + // get the new copy + groups = queue.GetProperty>("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() + { + { + 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>("Groups"); + groups[group].UsedSlots = usedSlots; + + // reconfigure with different options to bypass the hash check + options = new Options() + { + Groups = new Options.GroupsOptions() + { + UserDefined = new Dictionary() + { + { + 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>("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>>("Uploads")); + + queue.Enqueue(tx); + + var uploads = queue.GetProperty>>("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>>("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>>("Uploads")); + + queue.Enqueue(tx); + queue.Enqueue(tx2); + + var uploads = queue.GetProperty>>("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); + } + } + private static (UploadQueue queue, Mocks mocks) GetFixture(Options options = null) { var mocks = new Mocks(options); @@ -164,6 +352,9 @@ 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) -- cgit v1.2.3 From e7c5cfd3d9d5e6551270e35f33b5259c21e0725c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Feb 2022 14:46:20 -0600 Subject: more UploadQueue tests --- src/slskd/Transfers/Uploads/UploadQueue.cs | 2 +- .../Transfers/Uploads/UploadQueueTests.cs | 105 +++++++++++++++++++++ 2 files changed, 106 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 34af4b3b..e899b70a 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -179,7 +179,7 @@ namespace slskd.Transfers // 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)) + if (Groups.ContainsKey(upload.Group ?? string.Empty)) { var group = Groups[upload.Group]; diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index e615ff15..2e422290 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -3,6 +3,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; + using System.Threading.Tasks; using AutoFixture.Xunit2; using Moq; using slskd.Transfers; @@ -342,9 +343,113 @@ } } + 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(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(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>>("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>("Groups"); + + Assert.Equal(2, groups[Application.DefaultGroup].UsedSlots); + + queue.Complete(tx); + + groups = queue.GetProperty>("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>>("Uploads"); + + Assert.Single(uploads); + + queue.Complete(tx); + queue.Complete(tx2); + + uploads = queue.GetProperty>>("Uploads"); + + Assert.Empty(uploads); + } + } + private static (UploadQueue queue, Mocks mocks) GetFixture(Options options = null) { var mocks = new Mocks(options); + + mocks.UserService.Setup(m => m.GetGroup(It.IsAny())) + .Returns(Application.DefaultGroup); + var queue = new UploadQueue( mocks.UserService.Object, mocks.OptionsMonitor); -- cgit v1.2.3 From 3f8c2142fa657aebd2bde87ef511eeab2c5df148 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Feb 2022 21:10:16 -0600 Subject: return released upload from Process() --- src/slskd/Transfers/Uploads/UploadQueue.cs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index e899b70a..fac802f5 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -199,7 +199,7 @@ namespace slskd.Transfers } } - private void Process() + private Upload Process() { SyncRoot.Wait(); @@ -207,7 +207,7 @@ namespace slskd.Transfers { if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots) { - return; + return null; } // flip the uploads dictionary so that it is keyed by group instead of user. @@ -262,8 +262,10 @@ namespace slskd.Transfers 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); - break; + return upload; } + + return null; } finally { -- cgit v1.2.3 From 83b809edaf0c1f1774e33c912ca975a9ff76d212 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 14 Feb 2022 21:39:18 -0600 Subject: make Uploads settable --- src/slskd/Transfers/Uploads/UploadQueue.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index fac802f5..71c8bf93 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -85,7 +85,7 @@ namespace slskd.Transfers private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private int MaxSlots { get; set; } = 0; private Dictionary Groups { get; set; } = new Dictionary(); - private ConcurrentDictionary> Uploads { get; } = new ConcurrentDictionary>(); + private ConcurrentDictionary> Uploads { get; set; } = new ConcurrentDictionary>(); /// /// Enqueues an upload. -- cgit v1.2.3 From 336934033515650e271fd4d7d517600644693667 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 15 Feb 2022 21:32:18 -0600 Subject: default group slots to int.MaxValue --- src/slskd/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index f7e1266d..2313ce69 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -551,7 +551,7 @@ namespace slskd /// Gets the limit for the total number of upload slots for the group. /// [Range(1, int.MaxValue)] - public int Slots { get; init; } = 10; + public int Slots { get; init; } = int.MaxValue; /// /// Gets the total upload speed limit for the group. -- cgit v1.2.3 From 8e3ee8ecb276669745dc0eb6266d78055632f075 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 15 Feb 2022 21:33:07 -0600 Subject: sort by group name if priority is the same --- src/slskd/Transfers/Uploads/UploadQueue.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 71c8bf93..44aa8af4 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -239,7 +239,7 @@ namespace slskd.Transfers // 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)) + 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()) { -- cgit v1.2.3