aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd
diff options
context:
space:
mode:
authorPaul <jappe+github@posteo.de>2026-10-07 02:57:21 +0200
committerGitHub <noreply@github.com>2026-10-07 02:57:21 +0200
commit97bfb7c1777d944859f6c6eeef4894daa18203b8 (patch)
tree51b364fc76f7a0f37b1efcd7fe2295080ceb01cb /src/slskd
parent357effeedf8439459004f113bb532a7011e95fe5 (diff)
parent7c302a753b1814345fcb26eb78dec97db6b698df (diff)
downloadslskd-97bfb7c1777d944859f6c6eeef4894daa18203b8.tar.gz
Merge branch 'master' into fix/upload-retry-button
Diffstat (limited to 'src/slskd')
-rw-r--r--src/slskd/Application.cs11
-rw-r--r--src/slskd/Common/TokenBucket.cs4
-rw-r--r--src/slskd/Core/API/Controllers/LogsController.cs94
-rw-r--r--src/slskd/Files/API/FilesController.cs2
-rw-r--r--src/slskd/Files/FileService.cs55
-rw-r--r--src/slskd/Program.cs5
-rw-r--r--src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs2
-rw-r--r--src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs2
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs2
-rw-r--r--src/slskd/Transfers/Types/Upload.cs2
-rw-r--r--src/slskd/Transfers/Types/UploadGroup.cs6
-rw-r--r--src/slskd/Transfers/Uploads/UploadQueue.cs224
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs3
13 files changed, 288 insertions, 124 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 8de4fe53..c34cd316 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -1749,7 +1749,7 @@ namespace slskd
// note: the following uses cached user data to determine group, so if the user's data
// isn't cached they may get a forecast based on the wrong group. this is a hot path though,
// and we don't want to incur the massive penalties that would caching data for each request.
- var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username);
+ var (groupName, totalSlots, freeSlots, forecastedPosition) = Transfers.Uploads.Queue.ForecastPosition(username);
Log.Debug("Sending search response with {Count} files to {Username} for query '{Query}'", results.Count(), username, query.SearchText);
@@ -1757,7 +1757,7 @@ namespace slskd
Client.Username,
token,
uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed,
- hasFreeUploadSlot: forecastedPosition == 0,
+ hasFreeUploadSlot: freeSlots > 0,
queueLength: forecastedPosition,
fileList: results);
}
@@ -1957,12 +1957,11 @@ namespace slskd
// we are deliberately skipping it here; if the username is watched
// leech detection works and they get accurate info, if not, they won't
var groupName = await Users.GetOrFetchGroupAsync(username);
- var group = Transfers.Uploads.Queue.GetGroupInfo(groupName);
// forecast the position at which this user would enter the queue if they were to request
// a file at this moment. this will be zero if a slot is available and the transfer would
// begin immediately
- var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username);
+ var (group, totalSlots, freeSlots, forecastedPosition) = Transfers.Uploads.Queue.ForecastPosition(username);
// if i get a user's info to determine whether i want to download files from them,
// i want to know how many slots they have, which gives me an idea of how fast their
@@ -1971,9 +1970,9 @@ namespace slskd
// revisited 3 years later: why was it important to leave this comment??
var info = new UserInfo(
description: Options.Soulseek.Description,
- uploadSlots: group.Slots,
+ uploadSlots: totalSlots,
queueLength: forecastedPosition,
- hasFreeUploadSlot: forecastedPosition == 0,
+ hasFreeUploadSlot: freeSlots > 0,
picture: pictureBytes);
return info;
diff --git a/src/slskd/Common/TokenBucket.cs b/src/slskd/Common/TokenBucket.cs
index 11d64b88..440f25ae 100644
--- a/src/slskd/Common/TokenBucket.cs
+++ b/src/slskd/Common/TokenBucket.cs
@@ -92,7 +92,7 @@ namespace slskd
/// </summary>
public class TokenBucket : ITokenBucket, IDisposable
{
- private TaskCompletionSource<bool> waitForReset = new();
+ private TaskCompletionSource<bool> waitForReset = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>
/// Initializes a new instance of the <see cref="TokenBucket"/> class.
@@ -243,6 +243,6 @@ namespace slskd
}
private void Reset()
- => Interlocked.Exchange(ref waitForReset, new TaskCompletionSource<bool>()).SetResult(true);
+ => Interlocked.Exchange(ref waitForReset, new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously)).SetResult(true);
}
}
diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs
index 8055c696..a83e608c 100644
--- a/src/slskd/Core/API/Controllers/LogsController.cs
+++ b/src/slskd/Core/API/Controllers/LogsController.cs
@@ -32,9 +32,16 @@
namespace slskd.Core.API
{
+ using System;
+ using System.IO;
+ using System.Linq;
+ using System.Threading.Tasks;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
+ using Serilog;
+ using slskd.Files;
/// <summary>
/// Logs.
@@ -46,15 +53,98 @@ namespace slskd.Core.API
[Consumes("application/json")]
public class LogsController : ControllerBase
{
+ public LogsController(FileService fileService)
+ {
+ Files = fileService;
+ }
+
+ private FileService Files { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<LogsController>();
+
/// <summary>
/// Gets the last few application logs.
/// </summary>
/// <returns></returns>
- [HttpGet]
- [Authorize(Policy = AuthPolicy.Any)]
+ [HttpGet("live")]
+ [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)]
public IActionResult Logs()
{
return Ok(Program.LogBuffer);
}
+
+ /// <summary>
+ /// Lists the log files currently on disk.
+ /// </summary>
+ /// <returns></returns>
+ [HttpGet("files")]
+ [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)]
+ public async Task<IActionResult> List()
+ {
+ if (!Directory.Exists(Path.GetFullPath(Program.LogDirectory)))
+ {
+ return NotFound();
+ }
+
+ var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions
+ {
+ IgnoreInaccessible = true,
+ AttributesToSkip = FileAttributes.System | FileAttributes.Hidden | FileAttributes.ReparsePoint,
+ RecurseSubdirectories = false,
+ });
+
+ var logs = directory.Files.Where(f => f.Name.EndsWith(".log", StringComparison.OrdinalIgnoreCase));
+
+ return Ok(logs);
+ }
+
+ /// <summary>
+ /// Retrieves the requested log file from disk as plain text.
+ /// </summary>
+ /// <param name="filename">The name of the log file.</param>
+ /// <returns></returns>
+ [HttpGet("files/{filename}")]
+ [Produces("text/plain")]
+ [ProducesResponseType(typeof(string), StatusCodes.Status200OK, contentType: "text/plain")]
+ [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)]
+ public IActionResult Get([FromRoute] string filename)
+ {
+ if (string.IsNullOrWhiteSpace(filename))
+ {
+ return BadRequest("Filename is required");
+ }
+
+ if (filename.ContainsAny('/', '\\'))
+ {
+ return BadRequest("Filename must not contain a path");
+ }
+
+ var sanitizedFilename = FileSafety.GetFileNameSafely(filename, sanitize: true);
+
+ if (!sanitizedFilename.Equals(filename, StringComparison.OrdinalIgnoreCase))
+ {
+ Log.Warning("Input filename {Filename} sanitized to {Sanitized}", filename, sanitizedFilename);
+ return BadRequest("Filename contains one or more invalid characters");
+ }
+
+ if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase))
+ {
+ return StatusCode(StatusCodes.Status403Forbidden, "Only .log files may be retrieved");
+ }
+
+ try
+ {
+ var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename));
+ return File(stream, "text/plain; charset=utf-8", enableRangeProcessing: true);
+ }
+ catch (NotFoundException)
+ {
+ return NotFound();
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to retrieve log file {Filename}: {Message}", filename, ex.Message);
+ return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
+ }
+ }
}
}
diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs
index 8a96d83f..5f30f325 100644
--- a/src/slskd/Files/API/FilesController.cs
+++ b/src/slskd/Files/API/FilesController.cs
@@ -200,7 +200,7 @@ namespace slskd.Files.API
try
{
- var response = await Files.ListContentsAsync(
+ var response = await Files.ListDirectoryContentsAsync(
directory: requestedDir,
enumerationOptions: new EnumerationOptions
{
diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs
index 8450ba48..70bfc293 100644
--- a/src/slskd/Files/FileService.cs
+++ b/src/slskd/Files/FileService.cs
@@ -59,9 +59,11 @@ namespace slskd.Files
private IEnumerable<string> AllowedDirectories => new[]
{
- Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads),
- Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete),
- };
+ OptionsMonitor.CurrentValue.Directories.Downloads,
+ OptionsMonitor.CurrentValue.Directories.Incomplete,
+ Program.LogDirectory,
+ }.Where(x => !string.IsNullOrWhiteSpace(x))
+ .Select(x => Path.GetFullPath(x));
private ILogger Log { get; } = Serilog.Log.ForContext<FileService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
@@ -319,7 +321,7 @@ namespace slskd.Files
/// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception>
/// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception>
/// <exception cref="UnauthorizedException">Thrown if the specified root directory is restricted.</exception>
- public virtual async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null)
+ public virtual async Task<FilesystemDirectory> ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(directory);
@@ -351,7 +353,7 @@ namespace slskd.Files
try
{
- var contents = dir.GetFileSystemInfos("*", enumerationOptions);
+ var contents = dir.GetFileSystemInfos("*", enumerationOptions ?? new EnumerationOptions());
var files = contents
.OfType<FileInfo>()
@@ -384,6 +386,49 @@ namespace slskd.Files
}
/// <summary>
+ /// Retrieves the contents of the specified <paramref name="filename"/> as a stream.
+ /// </summary>
+ /// <param name="filename">The file for which contents are to be retrieved.</param>
+ /// <returns>A Stream containing the contents of the file.</returns>
+ /// <exception cref="ArgumentNullException">Thrown if the specified filename is null or contains only whitespace.</exception>
+ /// <exception cref="ArgumentException">Thrown if the specified filename contains path traversal segments.</exception>
+ /// <exception cref="UnauthorizedException">Thrown if the specified file is not within an allowed directory.</exception>
+ /// <exception cref="NotFoundException">Thrown if the specified file does not exist.</exception>
+ /// <exception cref="IOException">Thrown if the file can't be opened for some reason.</exception>
+ public virtual Stream GetFileContents(string filename)
+ {
+ ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename));
+
+ if (FileSafety.ContainsTraversalSegments(filename))
+ {
+ Log.Warning("Suspicious attempt to read a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename);
+ throw new ArgumentException("Filenames containing traversal segments are not allowed");
+ }
+
+ // important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..'
+ if (!AllowedDirectories.Any(allowed => filename.StartsWith(allowed + Path.DirectorySeparatorChar)))
+ {
+ throw new UnauthorizedException($"Only application-controlled directories can be listed");
+ }
+
+ var info = ResolveFileInfo(filename);
+
+ if (!info.Exists)
+ {
+ throw new NotFoundException();
+ }
+
+ try
+ {
+ return new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
+ }
+ catch (Exception ex)
+ {
+ throw new IOException($"Failed to open file {Path.GetFileName(filename)} for reading: {ex.Message}", ex);
+ }
+ }
+
+ /// <summary>
/// Creates a new file with the specified fully qualified <paramref name="filename"/> and the optional <paramref name="options"/>,
/// returning a <see cref="Stream"/> with which the contents of the file can be written.
/// </summary>
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index b1f57ce4..cfe8bcba 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -1250,9 +1250,10 @@ namespace slskd
e => !OptionsAtStartup.Logger.NoDisk,
config => config.File(
Path.Combine(LogDirectory, $"{AppName}-.log"),
- outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}",
+ outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:yyyy-MM-ddTHH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}",
rollingInterval: RollingInterval.Day,
- retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs))))
+ retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs),
+ shared: true))) // allow log file to be read concurrently
.WriteTo.Conditional(
e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki),
config =>
diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs
index 7af36fcb..3e2c138f 100644
--- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs
+++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs
@@ -1,4 +1,4 @@
-// <copyright file="QueueDownloadBatchRequest.cs" company="JP Dillingham">
+// <copyright file="EnqueueDownloadBatchRequest.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs
index 3d066fe9..924611eb 100644
--- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs
+++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs
@@ -1,4 +1,4 @@
-// <copyright file="QueueDownloadBatchResponse.cs" company="JP Dillingham">
+// <copyright file="EnqueueDownloadBatchResponse.cs" company="JP Dillingham">
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index 30f3c9b1..cb9423bc 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -509,7 +509,7 @@ namespace slskd.Transfers.Downloads
add this to the dictionary before inserting the record, so we are guaranteed to have it
in the right place once the transfer hits the UI
*/
- var enqueuedTcs = new TaskCompletionSource<Transfer>();
+ var enqueuedTcs = new TaskCompletionSource<Transfer>(TaskCreationOptions.RunContinuationsAsynchronously);
// satisfies condition #3; CancellationTokenSource set cancelled by the user (via API call)
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
diff --git a/src/slskd/Transfers/Types/Upload.cs b/src/slskd/Transfers/Types/Upload.cs
index 2e9dc8ef..1e05a88a 100644
--- a/src/slskd/Transfers/Types/Upload.cs
+++ b/src/slskd/Transfers/Types/Upload.cs
@@ -42,7 +42,7 @@ namespace slskd.Transfers
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 TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
public string Username { get; set; }
}
} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs
index fa307b53..0b2b617d 100644
--- a/src/slskd/Transfers/Types/UploadGroup.cs
+++ b/src/slskd/Transfers/Types/UploadGroup.cs
@@ -30,15 +30,17 @@
// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
// </copyright>
+using System.Collections.Generic;
+
namespace slskd.Transfers
{
public sealed record UploadGroup
{
public string Name { get; init; }
public int Priority { get; set; }
- public bool SlotAvailable => UsedSlots < Slots;
+ public bool HasAvailableSlot => UsedSlots.Count < Slots;
public int Slots { get; set; }
public QueueStrategy Strategy { get; set; }
- public int UsedSlots { get; set; }
+ public HashSet<(string Username, string Filename)> UsedSlots { get; set; }
}
}
diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs
index 2dca0d9e..5839fa73 100644
--- a/src/slskd/Transfers/Uploads/UploadQueue.cs
+++ b/src/slskd/Transfers/Uploads/UploadQueue.cs
@@ -54,8 +54,9 @@ namespace slskd.Transfers.Uploads
/// </summary>
/// <param name="username">The username of the remote user.</param>
/// <param name="filename">The filename for which to await the start.</param>
+ /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The operation context.</returns>
- Task AwaitStartAsync(string username, string filename);
+ Task AwaitStartAsync(string username, string filename, CancellationToken cancellationToken = default);
/// <summary>
/// Signals the completion of an upload.
@@ -81,15 +82,13 @@ namespace slskd.Transfers.Uploads
void Enqueue(string username, string filename);
/// <summary>
- /// Gets information about the specified <paramref name="groupName"/>.
- /// </summary>
- /// <param name="groupName">The name of the group.</param>
- /// <returns>The group information.</returns>
- UploadGroup GetGroupInfo(string groupName);
-
- /// <summary>
/// Computes the estimated queue position of the specified <paramref name="filename"/> for the specified <paramref name="username"/>.
/// </summary>
+ /// <remarks>
+ /// The returned position is relative to the user's group only. Higher priority groups are not factored in
+ /// because of the amount of data that would need to be processed to compute a number, and how variable it
+ /// would be due to the interplay of slot availability, number of higher priority users waiting, etc.
+ /// </remarks>
/// <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>
@@ -98,13 +97,18 @@ namespace slskd.Transfers.Uploads
/// <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.
+ /// along with the slot counts for the user's group.
/// </summary>
+ /// <remarks>
+ /// The returned position is relative to the user's group only. Higher priority groups are not factored in
+ /// because of the amount of data that would need to be processed to compute a number, and how variable it
+ /// would be due to the interplay of slot availability, number of higher priority users waiting, etc.
+ /// </remarks>
/// <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.
+ /// The user's group, the group's total and free slots, and the estimated position if the user were to enqueue a file.
/// </returns>
- int ForecastPosition(string username);
+ (string Group, int TotalSlots, int FreeSlots, int Position) ForecastPosition(string username);
}
/// <summary>
@@ -150,8 +154,9 @@ namespace slskd.Transfers.Uploads
/// </remarks>
/// <param name="username">The username of the remote user.</param>
/// <param name="filename">The filename for which to await the start.</param>
+ /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The operation context.</returns>
- public Task AwaitStartAsync(string username, string filename)
+ public Task AwaitStartAsync(string username, string filename, CancellationToken cancellationToken = default)
{
SyncRoot.Wait();
@@ -228,6 +233,13 @@ namespace slskd.Transfers.Uploads
}
list.Remove(upload);
+
+ if (!upload.TaskCompletionSource.Task.IsCompleted)
+ {
+ Log.Debug("Upload {File} for {User} was removed without being completed, so it has been cancelled", Path.GetFileName(upload.Filename));
+ upload.TaskCompletionSource.TrySetCanceled();
+ }
+
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
@@ -236,8 +248,8 @@ namespace slskd.Transfers.Uploads
{
var group = Groups[upload.Group];
- group.UsedSlots = Math.Max(0, group.UsedSlots - 1);
- Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots);
+ group.UsedSlots.Remove((username, filename));
+ Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots.Count, group.Slots);
}
if (list.Count == 0 && UploadDictionary.TryRemove(username, out _))
@@ -265,11 +277,11 @@ namespace slskd.Transfers.Uploads
try
{
- var upload = new Upload() { Username = username, Filename = filename };
+ var upload = new Upload() { Username = username, Filename = filename, Enqueued = DateTime.UtcNow };
UploadDictionary.AddOrUpdate(
key: username,
- addValue: new List<Upload>(new[] { upload }),
+ addValue: [upload],
updateValueFactory: (key, list) =>
{
list.Add(upload);
@@ -287,23 +299,13 @@ namespace slskd.Transfers.Uploads
}
/// <summary>
- /// Gets information about the specified <paramref name="groupName"/>.
- /// </summary>
- /// <param name="groupName">The name of the group.</param>
- /// <returns>The group information.</returns>
- public UploadGroup GetGroupInfo(string groupName)
- {
- if (Groups.TryGetValue(groupName, out var group))
- {
- return group;
- }
-
- throw new NotFoundException($"A group with the name {groupName} could not be found");
- }
-
- /// <summary>
/// Computes the estimated queue position of the specified <paramref name="filename"/> for the specified <paramref name="username"/>.
/// </summary>
+ /// <remarks>
+ /// The returned position is relative to the user's group only. Higher priority groups are not factored in
+ /// because of the amount of data that would need to be processed to compute a number, and how variable it
+ /// would be due to the interplay of slot availability, number of higher priority users waiting, etc.
+ /// </remarks>
/// <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>
@@ -311,16 +313,19 @@ namespace slskd.Transfers.Uploads
public int EstimatePosition(string username, string filename)
{
var groupName = Users.GetGroup(username);
- var groupRecord = Groups.GetValueOrDefault(groupName);
+
+ if (!Groups.TryGetValue(groupName, out var groupRecord))
+ {
+ throw new SlskdException($"Upload group {groupName} doesn't have an entry in upload dictionary. Please report this on GitHub: {Program.IssuesUrl}");
+ }
// the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user
+ // a user's group can change either by user changing the config or updating counts (for leech detection); resist the urge to cache this
var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName);
- // 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)
+ SyncRoot.Wait();
+
+ try
{
// find this user's uploads
if (!UploadDictionary.TryGetValue(username, out var uploadsForUser))
@@ -328,100 +333,123 @@ namespace slskd.Transfers.Uploads
throw new NotFoundException($"File {filename} is not enqueued for user {username}");
}
- // 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);
-
- if (localPosition < 0)
+ // 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)
{
- throw new NotFoundException($"File {filename} is not enqueued for user {username}");
- }
+ // find the position of the requested file in the user's queue
+ // note: backed by List<T>, which is stable and already ordered by enqueue time ASC
+ var localPosition = uploadsForUser
+ .FindIndex(u => u.Username == username && u.Filename == filename);
- // 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 position 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);
+ if (localPosition < 0)
+ {
+ throw new NotFoundException($"File {filename} is not enqueued for user {username}");
+ }
+
+ // 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 position of the file over the carat above, first find the position of it
+ // within its own queue (= 4). assume uploads will process top down, left to right until reaching
+ // this one. that's the 4 ahead of it from d, plus 4 from a, 2 from b, and 4 from c in earlier rounds (= 14).
+ foreach (var group in uploadsForGroup.Where(group => group.Key != username))
+ {
+ position += Math.Min(localPosition, group.Value.Count);
+ }
+
+ // be pessimistic and assume d is last in the rotation; every other user with a file in the same round
+ // goes first. in the example, a and c have a 5th file and b doesn't, putting the file over the carat
+ // at position 16.
+ var usersWithAtLeastAsManyFiles = uploadsForGroup
+ .Count(g => g.Key != username && g.Value.Count() >= localPosition + 1); // localPosition is zero-based
+
+ return position + usersWithAtLeastAsManyFiles;
}
- return position;
- }
+ // find the upload
+ var upload = uploadsForUser.SingleOrDefault(u => u.Username == username && u.Filename == filename);
- // 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();
+ if (upload is null)
+ {
+ throw new NotFoundException($"File {filename} is not enqueued for user {username}");
+ }
- var globalPosition = flattenedSortedUploadsForGroup.FindIndex(upload => upload.Username == username && upload.Filename == filename);
+ // the place in queue is simply the sum of all uploads across all other users in the group that were
+ // enqueued before this upload.
+ var globalPosition = uploadsForGroup.Sum(kvp => kvp.Value.Count(c => c.Enqueued < upload.Enqueued));
- if (globalPosition < 0)
+ return globalPosition;
+ }
+ finally
{
- throw new NotFoundException($"File {filename} is not enqueued for user {username}");
+ SyncRoot.Release();
}
-
- 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.
+ /// along with the slot counts for the user's group.
/// </summary>
+ /// <remarks>
+ /// The returned position is relative to the user's group only. Higher priority groups are not factored in
+ /// because of the amount of data that would need to be processed to compute a number, and how variable it
+ /// would be due to the interplay of slot availability, number of higher priority users waiting, etc.
+ /// </remarks>
/// <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.
+ /// The user's group, the group's total and free slots, and the estimated position if the user were to enqueue a file.
/// </returns>
- public int ForecastPosition(string username)
+ public (string Group, int TotalSlots, int FreeSlots, int Position) ForecastPosition(string username)
{
var groupName = Users.GetGroup(username);
+ if (!Groups.TryGetValue(groupName, out var groupRecord))
+ {
+ throw new SlskdException($"Upload group {groupName} doesn't have an entry in upload dictionary. Please report this on GitHub: {Program.IssuesUrl}");
+ }
+
+ var totalSlots = Math.Min(GlobalSlots, groupRecord.Slots);
+ var freeSlots = Math.Max(0, totalSlots - groupRecord.UsedSlots.Count);
+
// if there's a slot available, the user will enter the queue at position 0 (will start immediately)
- if (Groups.TryGetValue(groupName, out var groupRecord) && groupRecord.SlotAvailable)
+ if (freeSlots > 0)
{
- return 0;
+ return (groupName, totalSlots, freeSlots, 0);
}
// the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user
+ // a user's group can change either by user changing the config or updating counts (for leech detection); resist the urge to cache this
var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName);
// assuming that the queue will be processed in a true round-robin fashion and that the user will be the last in the
- // rotation (worst case), the user's start position will be equal to the number of users downloading or waiting, + 1.
+ // rotation (worst case), the user's start position will be equal to the number of users downloading or waiting.
if (groupRecord.Strategy == QueueStrategy.RoundRobin)
{
- return uploadsForGroup.Count() + 1;
+ return (groupName, totalSlots, freeSlots, uploadsForGroup.Count());
}
// for FIFO queues, the user will enter the queue at the very back. return the total number of uploads in progress and
- // enqueued, + 1.
- return uploadsForGroup
- .SelectMany(group => group.Value)
- .Count() + 1;
+ // enqueued.
+ return (groupName, totalSlots, freeSlots, uploadsForGroup.Sum(kvp => kvp.Value.Count));
}
private void Configure(Options options)
{
- int GetExistingUsedSlotsOrDefault(string group)
- => Groups.ContainsKey(group) ? Groups[group].UsedSlots : 0;
+ HashSet<(string Username, string Filename)> GetExistingUsedSlotsOrDefault(string group)
+ => Groups.ContainsKey(group) ? Groups[group].UsedSlots : [];
SyncRoot.Wait();
@@ -502,7 +530,7 @@ namespace slskd.Transfers.Uploads
// number of global slots, just exit. we *could* proceed, but uploads would stack up behind the
// global semaphore in Soulseek.NET and we wouldn't be able to control the order in which those
// were processed, so don't do that.
- if (Groups.Values.Sum(g => g.UsedSlots) >= GlobalSlots)
+ if (Groups.Values.Sum(g => g.UsedSlots.Count) >= GlobalSlots)
{
return null;
}
@@ -536,7 +564,7 @@ namespace slskd.Transfers.Uploads
// 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())
+ if (group.UsedSlots.Count >= group.Slots || !readyUploadsByGroup.TryGetValue(group.Name, out var uploads) || !uploads.Any())
{
continue;
}
@@ -549,7 +577,7 @@ namespace slskd.Transfers.Uploads
// returned to the proper place upon completion
upload.Started = DateTime.UtcNow;
upload.Group = group.Name;
- group.UsedSlots++;
+ group.UsedSlots.Add((upload.Username, upload.Filename));
// release the upload
upload.TaskCompletionSource.SetResult();
@@ -557,7 +585,7 @@ namespace slskd.Transfers.Uploads
EmitMetrics();
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);
+ Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots.Count, group.Slots);
return upload;
}
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index 5f98afac..b480e764 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -413,7 +413,6 @@ namespace slskd.Transfers.Uploads
lastReportedAverageSpeed = now;
}
-
}
finally
{
@@ -430,7 +429,7 @@ namespace slskd.Transfers.Uploads
disposeInputStreamOnCompletion: true, // note: don't set this to false!
governor: (tx, req, ct) => Governor.GetBytesAsync(tx.Username, req, ct),
reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx.Username, att, grant, act),
- slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename),
+ slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename, ct),
slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename));
// register the cancellation token