aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-06-28 10:36:12 -0500
committerGitHub <noreply@github.com>2022-06-28 10:36:12 -0500
commit77df3572c381150dc60454be03ca3176a940a628 (patch)
treebd28e93414bc580fac30619a994756ad1193d99b /src
parent18e5c8dd9a98862422a46221f99a1091a9314381 (diff)
parent1d211e640b8677753be7fee06f640f43863f8e68 (diff)
downloadslskd-77df3572c381150dc60454be03ca3176a940a628.tar.gz
Merge pull request #534 from slskd/send-stats
Include upload slot and approximate queue position with search results
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs73
-rw-r--r--src/slskd/Common/CommonExtensions.cs (renamed from src/slskd/Common/Extensions.cs)55
-rw-r--r--src/slskd/Common/Compute.cs17
-rw-r--r--src/slskd/Core/CoreExtensions.cs75
-rw-r--r--src/slskd/Core/Options.cs (renamed from src/slskd/Options.cs)1
-rw-r--r--src/slskd/Core/State.cs (renamed from src/slskd/State.cs)1
-rw-r--r--src/slskd/Core/Types/CacheKeys.cs24
-rw-r--r--src/slskd/Core/Types/QueueStrategy.cs (renamed from src/slskd/Common/QueueStrategy.cs)0
-rw-r--r--src/slskd/Messaging/Types/PrivateMessage.cs (renamed from src/slskd/Messaging/Domain/PrivateMessage.cs)0
-rw-r--r--src/slskd/Messaging/Types/Room.cs (renamed from src/slskd/Messaging/Domain/Room.cs)0
-rw-r--r--src/slskd/Messaging/Types/RoomMessage.cs (renamed from src/slskd/Messaging/Domain/RoomMessage.cs)0
-rw-r--r--src/slskd/Properties/analysis.ruleset1
-rw-r--r--src/slskd/Search/Types/File.cs (renamed from src/slskd/Search/Domain/File.cs)0
-rw-r--r--src/slskd/Search/Types/Response.cs (renamed from src/slskd/Search/Domain/Response.cs)0
-rw-r--r--src/slskd/Search/Types/Search.cs (renamed from src/slskd/Search/Domain/Search.cs)0
-rw-r--r--src/slskd/Shares/Types/Share.cs (renamed from src/slskd/Shares/Domain/Share.cs)0
-rw-r--r--src/slskd/Transfers/ITransferTracker.cs9
-rw-r--r--src/slskd/Transfers/TransferTracker.cs20
-rw-r--r--src/slskd/Transfers/Types/Upload.cs33
-rw-r--r--src/slskd/Transfers/Types/UploadGroup.cs29
-rw-r--r--src/slskd/Transfers/Uploads/UploadQueue.cs349
-rw-r--r--src/slskd/Users/Types/Info.cs (renamed from src/slskd/Users/Domain/Info.cs)0
-rw-r--r--src/slskd/Users/Types/Statistics.cs (renamed from src/slskd/Users/Domain/Statistics.cs)0
-rw-r--r--src/slskd/Users/Types/Status.cs (renamed from src/slskd/Users/Domain/Status.cs)0
-rw-r--r--src/slskd/Users/Types/User.cs (renamed from src/slskd/Users/Domain/User.cs)0
25 files changed, 474 insertions, 213 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 3e30c029..d7078bde 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -31,6 +31,7 @@ namespace slskd
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
+ using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
@@ -160,6 +161,7 @@ namespace slskd
private IHubContext<LogsHub> LogHub { get; set; }
private IUserService Users { get; set; }
private IShareService Shares { get; set; }
+ private IMemoryCache Cache { get; set; } = new MemoryCache(new MemoryCacheOptions());
public void CollectGarbage()
{
@@ -283,7 +285,8 @@ namespace slskd
directoryContentsResolver: DirectoryContentsResponseResolver,
enqueueDownload: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker),
searchResponseCache: new SearchResponseCache(),
- searchResponseResolver: SearchResponseResolver);
+ searchResponseResolver: SearchResponseResolver,
+ placeInQueueResolver: PlaceInQueueResolver);
await Client.ReconfigureOptionsAsync(patch);
@@ -442,6 +445,24 @@ namespace slskd
}
}
+ private async Task RefreshUserStatisticsIfNeeded(bool force = false)
+ {
+ if (force || !Cache.TryGetValue(CacheKeys.UserStatisticsToken, out _))
+ {
+ var stats = await Client.GetUserStatisticsAsync(OptionsAtStartup.Soulseek.Username);
+
+ State.SetValue(state => state with
+ {
+ Server = state.Server with
+ {
+ Statistics = stats,
+ },
+ });
+
+ Cache.Set(CacheKeys.UserStatisticsToken, true, TimeSpan.FromHours(4));
+ }
+ }
+
private void Client_LoggedIn(object sender, EventArgs e)
{
Log.Information("Logged in to the Soulseek server as {Username}", Client.Username);
@@ -449,6 +470,9 @@ namespace slskd
// send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero
// initially, but we'll update them when the cache is filled.
_ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files);
+
+ // fetch our average upload speed from the server, so we can provide it along with search results
+ _ = RefreshUserStatisticsIfNeeded(force: true);
}
private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args)
@@ -550,6 +574,20 @@ namespace slskd
Console.WriteLine($"[USER] {args.Username}: {args.Presence}");
}
+ private Task<int?> PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename)
+ {
+ try
+ {
+ var place = Transfers.Uploads.Queue.EstimatePosition(username, filename);
+ return Task.FromResult((int?)place);
+ }
+ catch (Exception ex)
+ {
+ Log.Warning(ex, "Failed to estimate place in queue for {Filename} requested by {Username}", filename, username);
+ return Task.FromResult<int?>(null);
+ }
+ }
+
/// <summary>
/// Creates and returns a <see cref="Soulseek.Directory"/> in response to a remote request.
/// </summary>
@@ -581,6 +619,13 @@ namespace slskd
/// </exception>
private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker)
{
+ // remote clients might sometimes re-request downloads to check the status. don't try to add the download again
+ // if it is already tracked.
+ if (tracker.Contains(TransferDirection.Upload, username, filename))
+ {
+ return;
+ }
+
_ = endpoint;
string localFilename;
FileInfo fileInfo = default;
@@ -604,13 +649,6 @@ namespace slskd
throw new DownloadEnqueueException($"File not shared.");
}
- if (tracker.TryGet(TransferDirection.Upload, username, filename, out _))
- {
- // in this case, a re-requested file is a no-op. normally we'd want to respond with a PlaceInQueueResponse
- Console.WriteLine($"[UPLOAD RE-REQUESTED] [{username}/{filename}]");
- return;
- }
-
// create a new cancellation token source so that we can cancel the upload from the UI.
var cts = new CancellationTokenSource();
var topts = new TransferOptions(
@@ -818,13 +856,6 @@ namespace slskd
/// <returns>A Task resolving a SearchResponse, or null.</returns>
private async Task<SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query)
{
- // some bots continually query for very common strings. blacklist known names here.
- var blacklist = new[] { "Lola45", "Lolo51", "rajah" };
- if (blacklist.Contains(username))
- {
- return null;
- }
-
// some bots and perhaps users search for very short terms. only respond to queries >= 3 characters. sorry, U2 fans.
if (query.Query.Length < 3)
{
@@ -835,14 +866,18 @@ namespace slskd
if (results.Any())
{
- Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText}");
+ await RefreshUserStatisticsIfNeeded();
+
+ var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username);
+
+ Console.WriteLine($"[SENDING SEARCH RESULTS]: {results.Count()} records to {username} for query {query.SearchText} (forecasted position: {forecastedPosition})");
return new SearchResponse(
Client.Username,
token,
- freeUploadSlots: 1,
- uploadSpeed: 0,
- queueLength: 0,
+ uploadSpeed: State.CurrentValue.Server.Statistics.AverageSpeed,
+ freeUploadSlots: forecastedPosition == 0 ? 1 : 0,
+ queueLength: forecastedPosition,
fileList: results);
}
diff --git a/src/slskd/Common/Extensions.cs b/src/slskd/Common/CommonExtensions.cs
index eafc59ff..65949016 100644
--- a/src/slskd/Common/Extensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -1,4 +1,4 @@
-// <copyright file="Extensions.cs" company="slskd Team">
+// <copyright file="CommonExtensions.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
@@ -22,22 +22,19 @@ namespace slskd
using System.Collections.Generic;
using System.IO;
using System.Linq;
- using System.Net.Sockets;
using System.Numerics;
using System.Reflection;
- using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
- using Soulseek;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
/// <summary>
- /// Extensions.
+ /// Common extensions; things not specific to Soulseek or slskd.
/// </summary>
- public static class Extensions
+ public static class CommonExtensions
{
/// <summary>
/// Deeply compares this object with the specified object and returns a list of properties that are different.
@@ -353,52 +350,6 @@ namespace slskd
}
/// <summary>
- /// Redacts this instance of Options, replacing properties marked with <see cref="SecretAttribute"/> with '*****'.
- /// </summary>
- /// <remarks>
- /// Creates a deep clone before redacting.
- /// </remarks>
- /// <param name="options">The Options instance to redact.</param>
- /// <returns>A redacted instance.</returns>
- public static Options Redact(this Options options)
- {
- var redacted = options.ToJson().FromJson<Options>();
- Redactor.Redact(redacted, redactWith: "*****");
- return redacted;
- }
-
- /// <summary>
- /// Creates a copy of this instance with the specified parameters changed.
- /// </summary>
- /// <param name="o">The options instance to copy.</param>
- /// <param name="readBufferSize">The read buffer size for underlying TCP connections.</param>
- /// <param name="writeBufferSize">The write buffer size for underlying TCP connections.</param>
- /// <param name="writeQueueSize">The size of the write queue for double buffered writes.</param>
- /// <param name="connectTimeout">The connection timeout, in milliseconds, for client and peer TCP connections.</param>
- /// <param name="inactivityTimeout">The inactivity timeout, in milliseconds, for peer TCP connections.</param>
- /// <param name="proxyOptions">Optional SOCKS 5 proxy configuration options.</param>
- /// <param name="configureSocketAction">
- /// The delegate invoked during instantiation to configure the server Socket instance.
- /// </param>
- /// <returns>The new instance.</returns>
- public static ConnectionOptions With(
- this ConnectionOptions o,
- int? readBufferSize = null,
- int? writeBufferSize = null,
- int? writeQueueSize = null,
- int? connectTimeout = null,
- int? inactivityTimeout = null,
- ProxyOptions proxyOptions = null,
- Action<Socket> configureSocketAction = null) => new ConnectionOptions(
- readBufferSize: readBufferSize ?? o.ReadBufferSize,
- writeBufferSize: writeBufferSize ?? o.WriteBufferSize,
- writeQueueSize: writeQueueSize ?? o.WriteQueueSize,
- connectTimeout: connectTimeout ?? o.ConnectTimeout,
- inactivityTimeout: inactivityTimeout ?? o.InactivityTimeout,
- proxyOptions: proxyOptions ?? o.ProxyOptions,
- configureSocket: configureSocketAction ?? o.ConfigureSocket);
-
- /// <summary>
/// Deserializes this string from json to an object of type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type to which to deserialize the string.</typeparam>
diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs
index eacaedf1..b9dc882a 100644
--- a/src/slskd/Common/Compute.cs
+++ b/src/slskd/Common/Compute.cs
@@ -44,22 +44,5 @@ namespace slskd
using var sha1 = SHA1.Create();
return BitConverter.ToString(sha1.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty);
}
-
- public static string MaskHash(string str)
- {
- var hash = Sha1Hash(str);
- hash = Convert.ToBase64String(Encoding.UTF8.GetBytes(hash));
- hash = Regex.Replace(hash, @"[\d=]", string.Empty).ToLowerInvariant();
-
- // in some very unlucky circumstances, the sha1 might end up being all or mostly numbers.
- // if this is the case the resulting hash could be fewer than the 5 characters we need,
- // so copy it until we get to 5
- while (hash.Length < 5)
- {
- hash += hash;
- }
-
- return $"@@{hash.Substring(0, 5)}";
- }
}
} \ No newline at end of file
diff --git a/src/slskd/Core/CoreExtensions.cs b/src/slskd/Core/CoreExtensions.cs
new file mode 100644
index 00000000..aef187b8
--- /dev/null
+++ b/src/slskd/Core/CoreExtensions.cs
@@ -0,0 +1,75 @@
+// <copyright file="CoreExtensions.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ using System;
+ using System.Net.Sockets;
+ using Soulseek;
+
+ /// <summary>
+ /// Core extensions; extensions for types specific to Soulseek or slskd.
+ /// </summary>
+ public static class CoreExtensions
+ {
+ /// <summary>
+ /// Redacts this instance of Options, replacing properties marked with <see cref="SecretAttribute"/> with '*****'.
+ /// </summary>
+ /// <remarks>
+ /// Creates a deep clone before redacting.
+ /// </remarks>
+ /// <param name="options">The Options instance to redact.</param>
+ /// <returns>A redacted instance.</returns>
+ public static Options Redact(this Options options)
+ {
+ var redacted = options.ToJson().FromJson<Options>();
+ Redactor.Redact(redacted, redactWith: "*****");
+ return redacted;
+ }
+
+ /// <summary>
+ /// Creates a copy of this instance with the specified parameters changed.
+ /// </summary>
+ /// <param name="o">The options instance to copy.</param>
+ /// <param name="readBufferSize">The read buffer size for underlying TCP connections.</param>
+ /// <param name="writeBufferSize">The write buffer size for underlying TCP connections.</param>
+ /// <param name="writeQueueSize">The size of the write queue for double buffered writes.</param>
+ /// <param name="connectTimeout">The connection timeout, in milliseconds, for client and peer TCP connections.</param>
+ /// <param name="inactivityTimeout">The inactivity timeout, in milliseconds, for peer TCP connections.</param>
+ /// <param name="proxyOptions">Optional SOCKS 5 proxy configuration options.</param>
+ /// <param name="configureSocketAction">
+ /// The delegate invoked during instantiation to configure the server Socket instance.
+ /// </param>
+ /// <returns>The new instance.</returns>
+ public static ConnectionOptions With(
+ this ConnectionOptions o,
+ int? readBufferSize = null,
+ int? writeBufferSize = null,
+ int? writeQueueSize = null,
+ int? connectTimeout = null,
+ int? inactivityTimeout = null,
+ ProxyOptions proxyOptions = null,
+ Action<Socket> configureSocketAction = null) => new ConnectionOptions(
+ readBufferSize: readBufferSize ?? o.ReadBufferSize,
+ writeBufferSize: writeBufferSize ?? o.WriteBufferSize,
+ writeQueueSize: writeQueueSize ?? o.WriteQueueSize,
+ connectTimeout: connectTimeout ?? o.ConnectTimeout,
+ inactivityTimeout: inactivityTimeout ?? o.InactivityTimeout,
+ proxyOptions: proxyOptions ?? o.ProxyOptions,
+ configureSocket: configureSocketAction ?? o.ConfigureSocket);
+ }
+}
diff --git a/src/slskd/Options.cs b/src/slskd/Core/Options.cs
index c4de3554..9deababa 100644
--- a/src/slskd/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -24,7 +24,6 @@ namespace slskd
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
- using System.IO;
using System.Linq;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
diff --git a/src/slskd/State.cs b/src/slskd/Core/State.cs
index 10ed80f6..b15ce7fa 100644
--- a/src/slskd/State.cs
+++ b/src/slskd/Core/State.cs
@@ -58,6 +58,7 @@ namespace slskd
public IPEndPoint IPEndPoint { get; init; }
public SoulseekClientStates State { get; init; }
public string Username { get; init; }
+ public UserStatistics Statistics { get; init; }
public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected);
public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn);
public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn);
diff --git a/src/slskd/Core/Types/CacheKeys.cs b/src/slskd/Core/Types/CacheKeys.cs
new file mode 100644
index 00000000..b5a335c1
--- /dev/null
+++ b/src/slskd/Core/Types/CacheKeys.cs
@@ -0,0 +1,24 @@
+// <copyright file="CacheKeys.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd
+{
+ public static class CacheKeys
+ {
+ public static readonly string UserStatisticsToken = nameof(UserStatisticsToken);
+ }
+}
diff --git a/src/slskd/Common/QueueStrategy.cs b/src/slskd/Core/Types/QueueStrategy.cs
index 50f6cce1..50f6cce1 100644
--- a/src/slskd/Common/QueueStrategy.cs
+++ b/src/slskd/Core/Types/QueueStrategy.cs
diff --git a/src/slskd/Messaging/Domain/PrivateMessage.cs b/src/slskd/Messaging/Types/PrivateMessage.cs
index 236632aa..236632aa 100644
--- a/src/slskd/Messaging/Domain/PrivateMessage.cs
+++ b/src/slskd/Messaging/Types/PrivateMessage.cs
diff --git a/src/slskd/Messaging/Domain/Room.cs b/src/slskd/Messaging/Types/Room.cs
index 459dea2c..459dea2c 100644
--- a/src/slskd/Messaging/Domain/Room.cs
+++ b/src/slskd/Messaging/Types/Room.cs
diff --git a/src/slskd/Messaging/Domain/RoomMessage.cs b/src/slskd/Messaging/Types/RoomMessage.cs
index 7a06a192..7a06a192 100644
--- a/src/slskd/Messaging/Domain/RoomMessage.cs
+++ b/src/slskd/Messaging/Types/RoomMessage.cs
diff --git a/src/slskd/Properties/analysis.ruleset b/src/slskd/Properties/analysis.ruleset
index 3e0f3586..4c308cbf 100644
--- a/src/slskd/Properties/analysis.ruleset
+++ b/src/slskd/Properties/analysis.ruleset
@@ -38,6 +38,7 @@
<Rule Id="S3011" Action="None" />
<Rule Id="S3427" Action="Info" />
<Rule Id="S1643" Action="Info" />
+ <Rule Id="S3241" Action="None" />
</Rules>
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
<Rule Id="SA1008" Action="None" />
diff --git a/src/slskd/Search/Domain/File.cs b/src/slskd/Search/Types/File.cs
index 0a86eec3..0a86eec3 100644
--- a/src/slskd/Search/Domain/File.cs
+++ b/src/slskd/Search/Types/File.cs
diff --git a/src/slskd/Search/Domain/Response.cs b/src/slskd/Search/Types/Response.cs
index ea2e8993..ea2e8993 100644
--- a/src/slskd/Search/Domain/Response.cs
+++ b/src/slskd/Search/Types/Response.cs
diff --git a/src/slskd/Search/Domain/Search.cs b/src/slskd/Search/Types/Search.cs
index 52f97075..52f97075 100644
--- a/src/slskd/Search/Domain/Search.cs
+++ b/src/slskd/Search/Types/Search.cs
diff --git a/src/slskd/Shares/Domain/Share.cs b/src/slskd/Shares/Types/Share.cs
index 6a6d1f66..6a6d1f66 100644
--- a/src/slskd/Shares/Domain/Share.cs
+++ b/src/slskd/Shares/Types/Share.cs
diff --git a/src/slskd/Transfers/ITransferTracker.cs b/src/slskd/Transfers/ITransferTracker.cs
index 4edbdd63..f8715873 100644
--- a/src/slskd/Transfers/ITransferTracker.cs
+++ b/src/slskd/Transfers/ITransferTracker.cs
@@ -53,5 +53,14 @@ namespace slskd.Transfers
/// <param name="transfer"></param>
/// <returns></returns>
bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer);
+
+ /// <summary>
+ /// Gets a value indicating whether a transfer matching the specified information is tracked.
+ /// </summary>
+ /// <param name="direction"></param>
+ /// <param name="username"></param>
+ /// <param name="filename"></param>
+ /// <returns></returns>
+ bool Contains(TransferDirection direction, string username, string filename);
}
} \ No newline at end of file
diff --git a/src/slskd/Transfers/TransferTracker.cs b/src/slskd/Transfers/TransferTracker.cs
index d70717dd..358abf6f 100644
--- a/src/slskd/Transfers/TransferTracker.cs
+++ b/src/slskd/Transfers/TransferTracker.cs
@@ -181,6 +181,26 @@ namespace slskd.Transfers
}
}
+ /// <summary>
+ /// Gets a value indicating whether a transfer matching the specified information is tracked.
+ /// </summary>
+ /// <param name="direction"></param>
+ /// <param name="username"></param>
+ /// <param name="filename"></param>
+ /// <returns></returns>
+ public bool Contains(TransferDirection direction, string username, string filename)
+ {
+ if (Transfers.TryGetValue(direction, out var directionDict))
+ {
+ if (directionDict.TryGetValue(username, out var userDict))
+ {
+ return userDict.Values.Any(record => record.Transfer.Filename == filename);
+ }
+ }
+
+ return false;
+ }
+
private ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> GetNewDictionaryForUser(TransferEventArgs args, CancellationTokenSource cancellationTokenSource)
{
var r = new ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>();
diff --git a/src/slskd/Transfers/Types/Upload.cs b/src/slskd/Transfers/Types/Upload.cs
new file mode 100644
index 00000000..bc2b69b1
--- /dev/null
+++ b/src/slskd/Transfers/Types/Upload.cs
@@ -0,0 +1,33 @@
+// <copyright file="Upload.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Transfers
+{
+ using System;
+ using System.Threading.Tasks;
+
+ public sealed class Upload
+ {
+ public DateTime Enqueued { get; set; } = DateTime.UtcNow;
+ public string Filename { get; set; }
+ public string Group { get; set; }
+ public DateTime? Ready { get; set; } = null;
+ public DateTime? Started { get; set; } = null;
+ public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource();
+ public string Username { get; set; }
+ }
+}
diff --git a/src/slskd/Transfers/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs
new file mode 100644
index 00000000..5696b0f1
--- /dev/null
+++ b/src/slskd/Transfers/Types/UploadGroup.cs
@@ -0,0 +1,29 @@
+// <copyright file="UploadGroup.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Transfers
+{
+ public sealed class UploadGroup
+ {
+ public string Name { get; set; }
+ public int Priority { get; set; }
+ public bool SlotAvailable => UsedSlots < Slots;
+ public int Slots { get; set; }
+ public QueueStrategy Strategy { get; set; }
+ public int UsedSlots { get; set; }
+ }
+}
diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs
index de8cc031..c3b2b3e6 100644
--- a/src/slskd/Transfers/Uploads/UploadQueue.cs
+++ b/src/slskd/Transfers/Uploads/UploadQueue.cs
@@ -36,12 +36,6 @@ namespace slskd.Transfers
public interface IUploadQueue
{
/// <summary>
- /// Enqueues an upload.
- /// </summary>
- /// <param name="transfer">The upload to enqueue.</param>
- void Enqueue(Transfer transfer);
-
- /// <summary>
/// Awaits the start of an upload.
/// </summary>
/// <param name="transfer">The upload for which to wait.</param>
@@ -53,6 +47,31 @@ namespace slskd.Transfers
/// </summary>
/// <param name="transfer">The completed upload.</param>
void Complete(Transfer transfer);
+
+ /// <summary>
+ /// Enqueues an upload.
+ /// </summary>
+ /// <param name="transfer">The upload to enqueue.</param>
+ void Enqueue(Transfer transfer);
+
+ /// <summary>
+ /// Computes the estimated queue position of the specified <paramref name="filename"/> for the specified <paramref name="username"/>.
+ /// </summary>
+ /// <param name="username">The username associated with the file.</param>
+ /// <param name="filename">The filename of the file for which the position is to be estimated.</param>
+ /// <returns>The estimated queue position of the file.</returns>
+ /// <exception cref="FileNotFoundException">Thrown if the specified filename is not enqueued.</exception>
+ int EstimatePosition(string username, string filename);
+
+ /// <summary>
+ /// Computes the estimated queue position of the specified <paramref name="username"/> if they were to enqueue a file,
+ /// or zero if the transfer could start immediately.
+ /// </summary>
+ /// <param name="username">The username for which to estimate.</param>
+ /// <returns>
+ /// The estimated queue position if the user were to enqueue a file, or zero if the transfer could start immediately.
+ /// </returns>
+ int ForecastPosition(string username);
}
/// <summary>
@@ -77,45 +96,15 @@ namespace slskd.Transfers
Configure(OptionsMonitor.CurrentValue);
}
+ private Dictionary<string, UploadGroup> Groups { get; set; } = new Dictionary<string, UploadGroup>();
+ private int LastGlobalSlots { get; set; }
+ private string LastOptionsHash { get; set; }
private ILogger Log { get; } = Serilog.Log.ForContext<UploadQueue>();
- private IUserService Users { get; }
+ private int MaxSlots { get; set; } = 0;
private IOptionsMonitor<Options> OptionsMonitor { get; }
- private string LastOptionsHash { get; set; }
- private int LastGlobalSlots { get; set; }
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1);
- private int MaxSlots { get; set; } = 0;
- private Dictionary<string, Group> Groups { get; set; } = new Dictionary<string, Group>();
private ConcurrentDictionary<string, List<Upload>> Uploads { get; set; } = new ConcurrentDictionary<string, List<Upload>>();
-
- /// <summary>
- /// Enqueues an upload.
- /// </summary>
- /// <param name="transfer">The upload to enqueue.</param>
- public void Enqueue(Transfer transfer)
- {
- SyncRoot.Wait();
-
- try
- {
- var upload = new Upload() { Username = transfer.Username, Filename = transfer.Filename };
-
- Uploads.AddOrUpdate(
- key: transfer.Username,
- addValue: new List<Upload>(new[] { upload }),
- updateValueFactory: (key, list) =>
- {
- list.Add(upload);
- return list;
- });
-
- Log.Debug("Enqueued: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued);
- }
- finally
- {
- SyncRoot.Release();
- Process();
- }
- }
+ private IUserService Users { get; }
/// <summary>
/// Awaits the start of an upload.
@@ -177,8 +166,8 @@ namespace slskd.Transfers
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.
+ // ensure the slot is returned to the group from which it was acquired the group may have been removed during the
+ // transfer. if so, do nothing.
if (Groups.ContainsKey(upload.Group ?? string.Empty))
{
var group = Groups[upload.Group];
@@ -199,80 +188,141 @@ namespace slskd.Transfers
}
}
-#pragma warning disable S3241 // Methods should not return values that are never used
- private Upload Process()
-#pragma warning restore S3241 // Methods should not return values that are never used
+ /// <summary>
+ /// Enqueues an upload.
+ /// </summary>
+ /// <param name="transfer">The upload to enqueue.</param>
+ public void Enqueue(Transfer transfer)
{
SyncRoot.Wait();
try
{
- if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots)
- {
- return null;
- }
+ var upload = new Upload() { Username = transfer.Username, Filename = transfer.Filename };
- // flip the uploads dictionary so that it is keyed by group instead of user.
- // wait until just before we process the queue to do this, and fetch each user's
- // group as we do, to allow users to move between groups at run time. we delay
- // "pinning" an upload to a group (via UsedSlots, below) for the same reason.
- var readyUploadsByGroup = Uploads.Aggregate(
- seed: new ConcurrentDictionary<string, List<Upload>>(),
- func: (groups, user) =>
+ Uploads.AddOrUpdate(
+ key: transfer.Username,
+ addValue: new List<Upload>(new[] { upload }),
+ updateValueFactory: (key, list) =>
{
- var ready = user.Value.Where(u => u.Ready.HasValue && !u.Started.HasValue);
+ list.Add(upload);
+ return list;
+ });
- if (ready.Any())
- {
- var group = Users.GetGroup(user.Key);
+ Log.Debug("Enqueued: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued);
+ }
+ finally
+ {
+ SyncRoot.Release();
+ Process();
+ }
+ }
- groups.AddOrUpdate(
- key: group,
- addValue: new List<Upload>(ready),
- updateValueFactory: (group, list) =>
- {
- list.AddRange(ready);
- return list;
- });
- }
+ /// <summary>
+ /// Computes the estimated queue position of the specified <paramref name="filename"/> for the specified <paramref name="username"/>.
+ /// </summary>
+ /// <param name="username">The username associated with the file.</param>
+ /// <param name="filename">The filename of the file for which the position is to be estimated.</param>
+ /// <returns>The estimated queue position of the file.</returns>
+ /// <exception cref="FileNotFoundException">Thrown if the specified filename is not enqueued.</exception>
+ public int EstimatePosition(string username, string filename)
+ {
+ var groupName = Users.GetGroup(username);
+ var groupRecord = Groups.GetValueOrDefault(groupName);
- return groups;
- });
+ // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user
+ var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName);
- // process each group in ascending order of priority, and stop after the first
- // ready upload is released.
- foreach (var group in Groups.Values.OrderBy(g => g.Priority).ThenBy(g => g.Name))
+ // the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates
+ // for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the
+ // queue twice as fast, too. assume everyone downloads at equal speed for this estimate. also assume that all files
+ // are of equal length.
+ if (groupRecord.Strategy == QueueStrategy.RoundRobin)
+ {
+ // find this user's uploads
+ if (!Uploads.TryGetValue(username, out var uploadsForUser))
{
- if (group.UsedSlots >= group.Slots || !readyUploadsByGroup.TryGetValue(group.Name, out var uploads) || !uploads.Any())
- {
- continue;
- }
-
- var upload = uploads
- .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready)
- .First();
+ throw new FileNotFoundException($"File {filename} is not enqueued for user {username}");
+ }
- // mark the upload as started, and "pin" it to the group from which
- // the slot is obtained, so the slot can be returned to the proper place
- // upon completion
- upload.Started = DateTime.UtcNow;
- upload.Group = group.Name;
- group.UsedSlots++;
+ // find the position of the requested file in the user's queue
+ var localPosition = uploadsForUser
+ .OrderBy(upload => upload.Enqueued)
+ .ToList()
+ .FindIndex(upload => upload.Username == username && upload.Filename == filename);
- // 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);
+ if (localPosition < 0)
+ {
+ throw new FileNotFoundException($"File {filename} is not enqueued for user {username}");
+ }
- return upload;
+ // start the position to the local position within this user's queue; the user's own files must be completed
+ // before this one can start.
+ var position = localPosition;
+
+ // for each other user, add either localPosition or the count of that user's uploads, whichever is less
+ // example:
+ //
+ // aaaaa
+ // bb
+ // cccccccccccc
+ // ddddddd
+ // ^
+ //
+ // if we want the postion of the file over the carat above, first find the position of it
+ // within its own queue (= 5). assume uploads will process top down, left to right until reaching
+ // this one. that's 5 files from a, 2 from b, 5 from c, and the other 4 from d, putting the file over
+ // the carat at position 16. the actual number will vary due to many factors, including where in the
+ // round-robin ordering d is actually positioned (so +/- number of users downloading).
+ foreach (var group in uploadsForGroup.Where(group => group.Key != username))
+ {
+ position += Math.Min(localPosition, group.Value.Count);
}
- return null;
+ return position;
}
- finally
+
+ // for FIFO queues, files are uploaded in the order they are enqueued, so the position should be pretty good estimate.
+ // List ordering is guaranteed, so we are getting an accurate portrayal of where this file is in the queue by order of
+ // time enqueued. this includes uploads that are in progress.
+ var flattenedSortedUploadsForGroup = uploadsForGroup
+ .SelectMany(group => group.Value)
+ .OrderBy(upload => upload.Enqueued)
+ .ToList();
+
+ var globalPosition = flattenedSortedUploadsForGroup.FindIndex(upload => upload.Username == username && upload.Filename == filename);
+
+ if (globalPosition < 0)
{
- SyncRoot.Release();
+ throw new FileNotFoundException($"File {filename} is not enqueued for user {username}");
}
+
+ return globalPosition;
+ }
+
+ /// <summary>
+ /// Computes the estimated queue position of the specified <paramref name="username"/> if they were to enqueue a file,
+ /// or zero if the transfer could start immediately.
+ /// </summary>
+ /// <param name="username">The username for which to estimate.</param>
+ /// <returns>
+ /// The estimated queue position if the user were to enqueue a file, or zero if the transfer could start immediately.
+ /// </returns>
+ public int ForecastPosition(string username)
+ {
+ var group = Users.GetGroup(username);
+
+ // if there's a slot available, the user will enter the queue at position 0 (will start immediately)
+ if (Groups.TryGetValue(group, out var groupRecord) && groupRecord.SlotAvailable)
+ {
+ return 0;
+ }
+
+ // no slots are available for this group, so there's at least as many uploads in progress as there are slots. count all
+ // uploads (in progress or otherwise)
+ var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == group);
+
+ return uploadsForGroup.Count() + 1;
}
private void Configure(Options options)
@@ -294,14 +344,14 @@ namespace slskd.Transfers
MaxSlots = options.Global.Upload.Slots;
// statically add built-in groups
- var groups = new List<Group>()
+ var groups = new List<UploadGroup>()
{
- // 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 privileged users always take priority, regardless of user configuration.
- // the strategy is fixed to FIFO because that gives privileged users the closest experience
- // to the official client, as well as the appearance of fairness once the first upload begins.
- new Group()
+ // the priority group is hard-coded with priority 0, slot count equivalent to the overall max, and a FIFO
+ // strategy. all other groups have a minimum priority of 1 (enforced by options validation) to ensure that
+ // privileged users always take priority, regardless of user configuration. the strategy is fixed to FIFO
+ // because that gives privileged users the closest experience to the official client, as well as the
+ // appearance of fairness once the first upload begins.
+ new UploadGroup()
{
Name = Application.PrivilegedGroup,
Priority = 0,
@@ -309,7 +359,7 @@ namespace slskd.Transfers
UsedSlots = GetExistingUsedSlotsOrDefault(Application.PrivilegedGroup),
Strategy = QueueStrategy.FirstInFirstOut,
},
- new Group()
+ new UploadGroup()
{
Name = Application.DefaultGroup,
Priority = options.Groups.Default.Upload.Priority,
@@ -317,7 +367,7 @@ namespace slskd.Transfers
UsedSlots = GetExistingUsedSlotsOrDefault(Application.DefaultGroup),
Strategy = (QueueStrategy)Enum.Parse(typeof(QueueStrategy), options.Groups.Default.Upload.Strategy, true),
},
- new Group()
+ new UploadGroup()
{
Name = Application.LeecherGroup,
Priority = options.Groups.Leechers.Upload.Priority,
@@ -328,7 +378,7 @@ namespace slskd.Transfers
};
// dynamically add user-defined groups
- groups.AddRange(options.Groups.UserDefined.Select(kvp => new Group()
+ groups.AddRange(options.Groups.UserDefined.Select(kvp => new UploadGroup()
{
Name = kvp.Key,
Priority = kvp.Value.Upload.Priority,
@@ -349,24 +399,75 @@ namespace slskd.Transfers
}
}
- public sealed class Group
+ private Upload Process()
{
- 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; }
- }
+ SyncRoot.Wait();
- public sealed class Upload
- {
- public string Username { get; set; }
- public string Filename { get; set; }
- public string Group { get; set; }
- public DateTime Enqueued { get; set; } = DateTime.UtcNow;
- public DateTime? Ready { get; set; } = null;
- public DateTime? Started { get; set; } = null;
- public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource();
+ try
+ {
+ if (Groups.Values.Sum(g => g.UsedSlots) >= MaxSlots)
+ {
+ return null;
+ }
+
+ // flip the uploads dictionary so that it is keyed by group instead of user. wait until just before we process the
+ // queue to do this, and fetch each user's group as we do, to allow users to move between groups at run time. we
+ // delay "pinning" an upload to a group (via UsedSlots, below) for the same reason.
+ var readyUploadsByGroup = Uploads.Aggregate(
+ seed: new ConcurrentDictionary<string, List<Upload>>(),
+ func: (groups, user) =>
+ {
+ var ready = user.Value.Where(u => u.Ready.HasValue && !u.Started.HasValue);
+
+ if (ready.Any())
+ {
+ var group = Users.GetGroup(user.Key);
+
+ groups.AddOrUpdate(
+ key: group,
+ addValue: new List<Upload>(ready),
+ updateValueFactory: (group, list) =>
+ {
+ list.AddRange(ready);
+ return list;
+ });
+ }
+
+ return groups;
+ });
+
+ // process each group in ascending order of priority, and stop after the first ready upload is released.
+ foreach (var group in Groups.Values.OrderBy(g => g.Priority).ThenBy(g => g.Name))
+ {
+ if (group.UsedSlots >= group.Slots || !readyUploadsByGroup.TryGetValue(group.Name, out var uploads) || !uploads.Any())
+ {
+ continue;
+ }
+
+ var upload = uploads
+ .OrderBy(u => group.Strategy == QueueStrategy.FirstInFirstOut ? u.Enqueued : u.Ready)
+ .First();
+
+ // mark the upload as started, and "pin" it to the group from which the slot is obtained, so the slot can be
+ // returned to the proper place upon completion
+ upload.Started = DateTime.UtcNow;
+ upload.Group = group.Name;
+ group.UsedSlots++;
+
+ // release the upload
+ upload.TaskCompletionSource.SetResult();
+ Log.Debug("Started: {File} for {User} at {Time}", Path.GetFileName(upload.Filename), upload.Username, upload.Enqueued);
+ Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots);
+
+ return upload;
+ }
+
+ return null;
+ }
+ finally
+ {
+ SyncRoot.Release();
+ }
}
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Users/Domain/Info.cs b/src/slskd/Users/Types/Info.cs
index e3969f17..e3969f17 100644
--- a/src/slskd/Users/Domain/Info.cs
+++ b/src/slskd/Users/Types/Info.cs
diff --git a/src/slskd/Users/Domain/Statistics.cs b/src/slskd/Users/Types/Statistics.cs
index a415d3d5..a415d3d5 100644
--- a/src/slskd/Users/Domain/Statistics.cs
+++ b/src/slskd/Users/Types/Statistics.cs
diff --git a/src/slskd/Users/Domain/Status.cs b/src/slskd/Users/Types/Status.cs
index 890afb74..890afb74 100644
--- a/src/slskd/Users/Domain/Status.cs
+++ b/src/slskd/Users/Types/Status.cs
diff --git a/src/slskd/Users/Domain/User.cs b/src/slskd/Users/Types/User.cs
index 2913620c..2913620c 100644
--- a/src/slskd/Users/Domain/User.cs
+++ b/src/slskd/Users/Types/User.cs