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/slskd/Application.cs') 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 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/slskd/Application.cs') 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/slskd/Application.cs') 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 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/slskd/Application.cs') 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 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/slskd/Application.cs') 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 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/slskd/Application.cs') 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 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/slskd/Application.cs') 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 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/slskd/Application.cs') 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