aboutsummaryrefslogtreecommitdiffstats
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
parent357effeedf8439459004f113bb532a7011e95fe5 (diff)
parent7c302a753b1814345fcb26eb78dec97db6b698df (diff)
downloadslskd-97bfb7c1777d944859f6c6eeef4894daa18203b8.tar.gz
Merge branch 'master' into fix/upload-retry-button
-rw-r--r--Dockerfile14
-rwxr-xr-xbin/build7
-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
-rw-r--r--src/web/src/components/System/Logs/Explorer.jsx216
-rw-r--r--src/web/src/components/System/Logs/Live.jsx63
-rw-r--r--src/web/src/components/System/Logs/LogTable.jsx64
-rw-r--r--src/web/src/components/System/Logs/index.jsx127
-rw-r--r--src/web/src/lib/logs.js27
-rw-r--r--tests/slskd.Tests.Unit/Files/FileServiceTests.cs6
-rw-r--r--tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs776
22 files changed, 1465 insertions, 247 deletions
diff --git a/Dockerfile b/Dockerfile
index de081302..aad3bd2a 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -4,14 +4,13 @@
# build static web content
# note: pin this to amd64 to speed it up, it is prohibitively slow under QEMU
FROM --platform=$BUILDPLATFORM node:22-alpine AS web
-ARG VERSION=0.0.1.65534-local
WORKDIR /slskd
COPY bin bin/.
COPY src/web src/web/.
-RUN sh ./bin/build --web-only --version $VERSION
+RUN sh ./bin/build --web-only --version 0.0.1.65534-local
# build, test, and publish application binaries
# note: this needs to be pinned to an amd64 image in order to publish armv7 binaries
@@ -37,10 +36,6 @@ RUN bash ./bin/publish --no-prebuild --platform $TARGETPLATFORM --version $VERSI
# application
FROM mcr.microsoft.com/dotnet/runtime-deps:10.0-noble AS slskd
ARG TARGETPLATFORM
-ARG TAG=0.0.1
-ARG VERSION=0.0.1.65534-local
-ARG REVISION=0
-ARG BUILD_DATE
RUN apt-get update && apt-get install --no-install-recommends -y \
jq \
@@ -62,6 +57,11 @@ RUN bash -c 'mkdir -p /.net \
HEALTHCHECK --interval=60s --timeout=3s --start-period=60m --retries=3 CMD wget -q -O - http://localhost:${SLSKD_HTTP_PORT}/health
+ARG TAG=0.0.1
+ARG VERSION=0.0.1.65534-local
+ARG REVISION=0
+ARG BUILD_DATE
+
ENV SHELL=/usr/bin/bash \
DOTNET_EnableDiagnostics=0 \
DOTNET_BUNDLE_EXTRACT_BASE_DIR=/.net \
@@ -81,7 +81,7 @@ ENV SHELL=/usr/bin/bash \
LABEL org.opencontainers.image.title=slskd \
org.opencontainers.image.description="A modern client-server application for the Soulseek file sharing network" \
- org.opencontainers.image.authors="JP Dillingham, slskd Contributors" \
+ org.opencontainers.image.authors="JP Dillingham" \
org.opencontainers.image.vendor="slskd Project" \
org.opencontainers.image.licenses=AGPL-3.0 \
org.opencontainers.image.url=https://slskd.org \
diff --git a/bin/build b/bin/build
index 8283bf25..9a15ca66 100755
--- a/bin/build
+++ b/bin/build
@@ -39,7 +39,12 @@ while test $# -gt 0; do
esac
done
-if [ -z "$version" ]; then
+if [ -z "$version" ]; then
+ if ! command -v git >/dev/null 2>&1; then
+ echo "πŸ’₯ error: git is required to compose the version, but the executable couldn't be found"
+ exit 1
+ fi
+
tag=$(git describe --tags --abbrev=0)
sha=$(git rev-parse --short HEAD)
version=$tag+$sha
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
diff --git a/src/web/src/components/System/Logs/Explorer.jsx b/src/web/src/components/System/Logs/Explorer.jsx
new file mode 100644
index 00000000..b1391da2
--- /dev/null
+++ b/src/web/src/components/System/Logs/Explorer.jsx
@@ -0,0 +1,216 @@
+import '../Files/Files.css';
+import { getFileBlob, list } from '../../../lib/logs';
+import { downloadFile, formatBytes, formatDate } from '../../../lib/util';
+import {
+ ErrorSegment,
+ LoaderSegment,
+ PlaceholderSegment,
+ Switch,
+} from '../../Shared';
+import React, { useEffect, useState } from 'react';
+import { toast } from 'react-toastify';
+import { Header, Icon, Table } from 'semantic-ui-react';
+
+const view = async (filename) => {
+ const tab = window.open('', '_blank');
+
+ if (!tab) {
+ toast.error(
+ 'Unable to open a new window; allow pop-ups for this site to view logs',
+ );
+ return;
+ }
+
+ try {
+ const blob = await getFileBlob({ filename });
+
+ // hack: we can't pass a JWT in a plain link, so we have to fetch the blob
+ // and then shove it into the window rather than just displaying it
+ tab.location.href = window.URL.createObjectURL(
+ new Blob([blob], { type: 'text/plain; charset=utf-8' }),
+ );
+ } catch (error) {
+ tab.close();
+ toast.error(error?.message ?? error);
+ }
+};
+
+const download = async (filename) => {
+ try {
+ const blob = await getFileBlob({ filename });
+
+ downloadFile(blob, filename, 'text/plain');
+ } catch (error) {
+ toast.error(error?.message ?? error);
+ }
+};
+
+const FileRow = ({ length, modifiedAt, name }) => (
+ <Table.Row key={name}>
+ <Table.Cell>
+ <Icon name="file alternate outline" />
+ {name}
+ </Table.Cell>
+ <Table.Cell>{modifiedAt ? formatDate(modifiedAt) : ''}</Table.Cell>
+ <Table.Cell>{length ? formatBytes(length) : ''}</Table.Cell>
+ <Table.Cell style={{ whiteSpace: 'nowrap' }}>
+ <Icon
+ name="external alternate"
+ onClick={() => view(name)}
+ style={{ cursor: 'pointer', marginRight: '0.5em' }}
+ title={`View ${name} in a new window`}
+ />
+ <Icon
+ name="download"
+ onClick={() => download(name)}
+ style={{ cursor: 'pointer' }}
+ title={`Download ${name}`}
+ />
+ </Table.Cell>
+ </Table.Row>
+);
+
+const Explorer = () => {
+ const [files, setFiles] = useState([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(undefined);
+ const [sortColumn, setSortColumn] = useState('date');
+ const [sortDirection, setSortDirection] = useState('descending');
+
+ const fetch = async () => {
+ setLoading(true);
+ setError(undefined);
+
+ try {
+ setFiles(await list());
+ } catch (fetchError) {
+ if (fetchError?.response?.status === 404) {
+ setFiles([]);
+ } else {
+ setError(fetchError?.message ?? fetchError);
+ }
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ useEffect(() => {
+ fetch();
+ }, []); // eslint-disable-line react-hooks/exhaustive-deps
+
+ const handleSort = (column) => {
+ if (sortColumn === column) {
+ setSortDirection(
+ sortDirection === 'ascending' ? 'descending' : 'ascending',
+ );
+ } else {
+ setSortColumn(column);
+ setSortDirection('ascending');
+ }
+ };
+
+ const sortItems = (items) => {
+ if (!items || items.length === 0) return items;
+
+ return [...items].sort((a, b) => {
+ let compareValue = 0;
+
+ if (sortColumn === 'name') {
+ compareValue = a.name.localeCompare(b.name, undefined, {
+ numeric: true,
+ sensitivity: 'base',
+ });
+ } else if (sortColumn === 'date') {
+ const dateA = a.modifiedAt ? new Date(a.modifiedAt) : new Date(0);
+ const dateB = b.modifiedAt ? new Date(b.modifiedAt) : new Date(0);
+ compareValue = dateA - dateB;
+ }
+
+ return sortDirection === 'ascending' ? compareValue : -compareValue;
+ });
+ };
+
+ const sortedFiles = sortItems(files);
+
+ return (
+ <>
+ <Header
+ className="explorer-working-directory"
+ size="small"
+ >
+ <Icon name="folder open" />
+ /logs
+ </Header>
+ <Switch
+ empty={
+ !loading &&
+ !error &&
+ files.length === 0 && (
+ <PlaceholderSegment
+ caption="No log files"
+ icon="file alternate outline"
+ />
+ )
+ }
+ error={error && <ErrorSegment caption={error} />}
+ loading={loading && <LoaderSegment />}
+ >
+ <Table
+ className="unstackable"
+ size="large"
+ >
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell
+ className="explorer-list-name"
+ onClick={() => handleSort('name')}
+ style={{ cursor: 'pointer' }}
+ >
+ Name
+ {sortColumn === 'name' && (
+ <Icon
+ name={
+ sortDirection === 'ascending'
+ ? 'chevron up'
+ : 'chevron down'
+ }
+ />
+ )}
+ </Table.HeaderCell>
+ <Table.HeaderCell
+ className="explorer-list-date"
+ onClick={() => handleSort('date')}
+ style={{ cursor: 'pointer' }}
+ >
+ Date Modified
+ {sortColumn === 'date' && (
+ <Icon
+ name={
+ sortDirection === 'ascending'
+ ? 'chevron up'
+ : 'chevron down'
+ }
+ />
+ )}
+ </Table.HeaderCell>
+ <Table.HeaderCell className="explorer-list-size">
+ Size
+ </Table.HeaderCell>
+ <Table.HeaderCell className="explorer-list-action" />
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {sortedFiles.map((f) => (
+ <FileRow
+ key={f.name}
+ {...f}
+ />
+ ))}
+ </Table.Body>
+ </Table>
+ </Switch>
+ </>
+ );
+};
+
+export default Explorer;
diff --git a/src/web/src/components/System/Logs/Live.jsx b/src/web/src/components/System/Logs/Live.jsx
new file mode 100644
index 00000000..2699a2e3
--- /dev/null
+++ b/src/web/src/components/System/Logs/Live.jsx
@@ -0,0 +1,63 @@
+import '../System.css';
+import { createLogsHubConnection } from '../../../lib/hubFactory';
+import { LoaderSegment } from '../../Shared';
+import LogTable from './LogTable';
+import { Component } from 'react';
+
+const initialState = {
+ connected: false,
+ logs: [],
+};
+
+const maxLogs = 500;
+
+class Live extends Component {
+ constructor(props) {
+ super(props);
+
+ this.state = initialState;
+ }
+
+ componentDidMount() {
+ const logsHub = createLogsHubConnection();
+
+ logsHub.on('buffer', (buffer) => {
+ this.setState({
+ connected: true,
+ logs: buffer.reverse().slice(0, maxLogs).map(this.withId),
+ });
+ });
+
+ logsHub.on('log', (log) => {
+ const record = this.withId(log);
+
+ this.setState((previousState) => ({
+ connected: true,
+ logs: [record].concat(previousState.logs).slice(0, maxLogs),
+ }));
+ });
+
+ logsHub.onreconnecting(() => this.setState({ connected: false }));
+ logsHub.onclose(() => this.setState({ connected: false }));
+ logsHub.onreconnected(() => this.setState({ connected: true }));
+
+ logsHub.start();
+ }
+
+ nextId = 0;
+
+ withId = (log) => ({ ...log, id: this.nextId++ });
+
+ render() {
+ const { connected, logs } = this.state;
+
+ return (
+ <div className="logs">
+ {!connected && <LoaderSegment />}
+ {connected && <LogTable logs={logs} />}
+ </div>
+ );
+ }
+}
+
+export default Live;
diff --git a/src/web/src/components/System/Logs/LogTable.jsx b/src/web/src/components/System/Logs/LogTable.jsx
new file mode 100644
index 00000000..68bf6244
--- /dev/null
+++ b/src/web/src/components/System/Logs/LogTable.jsx
@@ -0,0 +1,64 @@
+import '../System.css';
+import { Table } from 'semantic-ui-react';
+
+const abbreviations = {
+ Debug: 'DBG',
+ Error: 'ERR',
+ Fatal: 'FTL',
+ Information: 'INF',
+ Verbose: 'VRB',
+ Warning: 'WRN',
+};
+
+export const formatTimestamp = (timestamp) => {
+ const date = new Date(timestamp);
+ return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len
+};
+
+const LogTable = ({ emptyMessage = 'No logs', logs }) => (
+ <Table
+ className="logs-table"
+ compact="very"
+ >
+ <Table.Header>
+ <Table.Row>
+ <Table.HeaderCell>Timestamp</Table.HeaderCell>
+ <Table.HeaderCell>Level</Table.HeaderCell>
+ <Table.HeaderCell>Message</Table.HeaderCell>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body className="logs-table-body">
+ {logs?.length === 0 ? (
+ <Table.Row>
+ <Table.Cell
+ colSpan={99}
+ style={{
+ opacity: 0.5,
+ padding: '10px !important',
+ textAlign: 'center',
+ }}
+ >
+ {emptyMessage}
+ </Table.Cell>
+ </Table.Row>
+ ) : (
+ logs.map((log) => (
+ <Table.Row
+ disabled={log.level === 'Debug' || log.level === 'Verbose'}
+ key={log.id}
+ negative={log.level === 'Error' || log.level === 'Fatal'}
+ warning={log.level === 'Warning'}
+ >
+ <Table.Cell>{formatTimestamp(log.timestamp)}</Table.Cell>
+ <Table.Cell>{abbreviations[log.level] || log.level}</Table.Cell>
+ <Table.Cell className="logs-table-message">
+ {log.message}
+ </Table.Cell>
+ </Table.Row>
+ ))
+ )}
+ </Table.Body>
+ </Table>
+);
+
+export default LogTable;
diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx
index f36258ec..f0fa4a58 100644
--- a/src/web/src/components/System/Logs/index.jsx
+++ b/src/web/src/components/System/Logs/index.jsx
@@ -1,98 +1,35 @@
-import '../System.css';
-import { createLogsHubConnection } from '../../../lib/hubFactory';
-import { LoaderSegment } from '../../Shared';
-import React, { Component } from 'react';
-import { Table } from 'semantic-ui-react';
-
-const initialState = {
- connected: false,
- logs: [],
-};
-
-const levels = {
- Debug: 'DBG',
- Error: 'ERR',
- Information: 'INF',
- Warning: 'WRN',
+import Explorer from './Explorer';
+import Live from './Live';
+import React from 'react';
+import { Tab } from 'semantic-ui-react';
+
+const Logs = () => {
+ const panes = [
+ {
+ menuItem: 'Live',
+ render: () => (
+ <Tab.Pane>
+ <Live />
+ </Tab.Pane>
+ ),
+ route: 'live',
+ },
+ {
+ menuItem: 'History',
+ render: () => (
+ <Tab.Pane>
+ <Explorer />
+ </Tab.Pane>
+ ),
+ route: 'history',
+ },
+ ];
+
+ return (
+ <div>
+ <Tab panes={panes} />
+ </div>
+ );
};
-const maxLogs = 500;
-
-class Logs extends Component {
- constructor(props) {
- super(props);
-
- this.state = initialState;
- }
-
- componentDidMount() {
- const logsHub = createLogsHubConnection();
-
- logsHub.on('buffer', (buffer) => {
- this.setState({
- connected: true,
- logs: buffer.reverse().slice(0, maxLogs),
- });
- });
-
- logsHub.on('log', (log) => {
- this.setState((previousState) => ({
- connected: true,
- logs: [log].concat(previousState.logs).slice(0, maxLogs),
- }));
- });
-
- logsHub.onreconnecting(() => this.setState({ connected: false }));
- logsHub.onclose(() => this.setState({ connected: false }));
- logsHub.onreconnected(() => this.setState({ connected: true }));
-
- logsHub.start();
- }
-
- formatTimestamp = (timestamp) => {
- const date = new Date(timestamp);
- return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`; // eslint-disable-line max-len
- };
-
- render() {
- const { connected, logs } = this.state;
-
- return (
- <div className="logs">
- {!connected && <LoaderSegment />}
- {connected && (
- <Table
- className="logs-table"
- compact="very"
- >
- <Table.Header>
- <Table.Row>
- <Table.HeaderCell>Timestamp</Table.HeaderCell>
- <Table.HeaderCell>Level</Table.HeaderCell>
- <Table.HeaderCell>Message</Table.HeaderCell>
- </Table.Row>
- </Table.Header>
- <Table.Body className="logs-table-body">
- {logs.map((log) => (
- <Table.Row
- disabled={log.level === 'Debug'}
- key={log.timestamp}
- negative={log.level === 'Error'}
- warning={log.level === 'Warning'}
- >
- <Table.Cell>{this.formatTimestamp(log.timestamp)}</Table.Cell>
- <Table.Cell>{levels[log.level] || log.level}</Table.Cell>
- <Table.Cell className="logs-table-message">
- {log.message}
- </Table.Cell>
- </Table.Row>
- ))}
- </Table.Body>
- </Table>
- )}
- </div>
- );
- }
-}
-
export default Logs;
diff --git a/src/web/src/lib/logs.js b/src/web/src/lib/logs.js
new file mode 100644
index 00000000..35ae5d84
--- /dev/null
+++ b/src/web/src/lib/logs.js
@@ -0,0 +1,27 @@
+import api from './api';
+
+export const list = async () => {
+ const response = (await api.get('/logs/files')).data;
+
+ return response;
+};
+
+export const getFileText = async ({ filename }) => {
+ const response = (
+ await api.get(`/logs/files/${encodeURIComponent(filename)}`, {
+ responseType: 'text',
+ })
+ ).data;
+
+ return response;
+};
+
+export const getFileBlob = async ({ filename }) => {
+ const response = (
+ await api.get(`/logs/files/${encodeURIComponent(filename)}`, {
+ responseType: 'blob',
+ })
+ ).data;
+
+ return response;
+};
diff --git a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs
index d6c30316..05f967da 100644
--- a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs
+++ b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs
@@ -34,7 +34,7 @@ namespace slskd.Tests.Unit.Files
[Fact]
public async Task ListContentsAsync_Throws_ArgumentException_Given_Relative_Path()
{
- var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: "../"));
+ var ex = await Record.ExceptionAsync(() => FileService.ListDirectoryContentsAsync(directory: "../"));
Assert.NotNull(ex);
Assert.IsType<ArgumentException>(ex);
@@ -53,7 +53,7 @@ namespace slskd.Tests.Unit.Files
}
});
- var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: Path.Combine(Temp, "foo")));
+ var ex = await Record.ExceptionAsync(() => FileService.ListDirectoryContentsAsync(directory: Path.Combine(Temp, "foo")));
Assert.NotNull(ex);
Assert.IsType<UnauthorizedException>(ex);
@@ -71,7 +71,7 @@ namespace slskd.Tests.Unit.Files
}
});
- var ex = await Record.ExceptionAsync(() => FileService.ListContentsAsync(directory: Path.Combine(Temp, "downloads", "foo")));
+ var ex = await Record.ExceptionAsync(() => FileService.ListDirectoryContentsAsync(directory: Path.Combine(Temp, "downloads", "foo")));
Assert.NotNull(ex);
Assert.IsType<NotFoundException>(ex);
diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs
index b1da3a77..f8b2f183 100644
--- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs
+++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs
@@ -39,7 +39,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads
Assert.Equal(Application.PrivilegedGroup, p.Name);
Assert.Equal(0, p.Priority);
Assert.Equal(new Options().Transfers.Upload.Slots, p.Slots);
- Assert.Equal(0, p.UsedSlots);
+ Assert.Empty(p.UsedSlots);
Assert.Equal(QueueStrategy.FirstInFirstOut, p.Strategy);
}
@@ -76,7 +76,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads
Assert.Equal(Application.DefaultGroup, p.Name);
Assert.Equal(priority, p.Priority);
Assert.Equal(slots, p.Slots);
- Assert.Equal(0, p.UsedSlots);
+ Assert.Empty(p.UsedSlots);
Assert.Equal(strategy, p.Strategy);
}
@@ -114,7 +114,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads
Assert.Equal(Application.LeecherGroup, p.Name);
Assert.Equal(priority, p.Priority);
Assert.Equal(slots, p.Slots);
- Assert.Equal(0, p.UsedSlots);
+ Assert.Empty(p.UsedSlots);
Assert.Equal(strategy, p.Strategy);
}
@@ -169,7 +169,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads
Assert.Equal(group1, p.Name);
Assert.Equal(priority1, p.Priority);
Assert.Equal(slots1, p.Slots);
- Assert.Equal(0, p.UsedSlots);
+ Assert.Empty(p.UsedSlots);
Assert.Equal(strategy1, p.Strategy);
p = groups[group2];
@@ -177,7 +177,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads
Assert.Equal(group2, p.Name);
Assert.Equal(priority2, p.Priority);
Assert.Equal(slots2, p.Slots);
- Assert.Equal(0, p.UsedSlots);
+ Assert.Empty(p.UsedSlots);
Assert.Equal(strategy2, p.Strategy);
}
@@ -236,7 +236,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads
Assert.Equal(group, p.Name);
Assert.Equal(priority, p.Priority);
Assert.Equal(slots, p.Slots);
- Assert.Equal(0, p.UsedSlots);
+ Assert.Empty(p.UsedSlots);
Assert.Equal(strategy, p.Strategy);
}
@@ -293,12 +293,12 @@ namespace slskd.Tests.Unit.Transfers.Uploads
Assert.Equal(group, p.Name);
Assert.Equal(priority, p.Priority);
Assert.Equal(42, p.Slots); // clamped to global value
- Assert.Equal(0, p.UsedSlots);
+ Assert.Empty(p.UsedSlots);
Assert.Equal(strategy, p.Strategy);
}
[Theory, AutoData]
- public void Retains_Used_Slot_Count_When_Options_Change(string group, int newPriority, int usedSlots)
+ public void Retains_Used_Slots_When_Options_Change(string group, int newPriority, string user1, string file1, string user2, string file2)
{
var options = new Options()
{
@@ -328,7 +328,8 @@ namespace slskd.Tests.Unit.Transfers.Uploads
var (queue, mocks) = GetFixture(options);
var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
- groups[group].UsedSlots = usedSlots;
+ groups[group].UsedSlots.Add((user1, file1));
+ groups[group].UsedSlots.Add((user2, file2));
// reconfigure with different options to bypass the hash check
options = new Options()
@@ -363,7 +364,9 @@ namespace slskd.Tests.Unit.Transfers.Uploads
var p = groups[group];
- Assert.Equal(usedSlots, p.UsedSlots);
+ Assert.Equal(2, p.UsedSlots.Count);
+ Assert.Contains((user1, file1), p.UsedSlots);
+ Assert.Contains((user2, file2), p.UsedSlots);
Assert.Equal(newPriority, p.Priority);
}
}
@@ -479,7 +482,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads
}
[Theory, AutoData]
- public async Task Decrements_UsedSlots_For_Group(string username, string filename, string filename2)
+ public async Task Releases_Slot_Held_By_Completed_Upload(string username, string filename, string filename2)
{
var (queue, _) = GetFixture();
@@ -491,13 +494,137 @@ namespace slskd.Tests.Unit.Transfers.Uploads
var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
- Assert.Equal(2, groups[Application.DefaultGroup].UsedSlots);
+ Assert.Equal(2, groups[Application.DefaultGroup].UsedSlots.Count);
+ Assert.Contains((username, filename), groups[Application.DefaultGroup].UsedSlots);
+ Assert.Contains((username, filename2), groups[Application.DefaultGroup].UsedSlots);
queue.Complete(username, filename);
groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
- Assert.Equal(1, groups[Application.DefaultGroup].UsedSlots);
+ Assert.Single(groups[Application.DefaultGroup].UsedSlots);
+ Assert.Contains((username, filename2), groups[Application.DefaultGroup].UsedSlots);
+ }
+
+ [Theory, AutoData]
+ public async Task Releases_Slot_To_Pinned_Group_If_Users_Group_Changed(string username, string filename)
+ {
+ var (queue, mocks) = GetFixture();
+
+ queue.Enqueue(username, filename);
+ await queue.AwaitStartAsync(username, filename);
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+
+ Assert.Contains((username, filename), groups[Application.DefaultGroup].UsedSlots);
+
+ // the user moves to a different group mid-transfer
+ mocks.UserService.Setup(m => m.GetGroup(username)).Returns(Application.LeecherGroup);
+
+ queue.Complete(username, filename);
+
+ Assert.Empty(groups[Application.DefaultGroup].UsedSlots);
+ Assert.Empty(groups[Application.LeecherGroup].UsedSlots);
+ }
+
+ [Theory, AutoData]
+ public async Task Does_Not_Release_Slots_Held_By_Other_Uploads_When_Completing_Upload_That_Never_Started(string username, string filename, string other, string otherFilename)
+ {
+ var (queue, _) = GetFixture();
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ groups[Application.DefaultGroup].Slots = 1;
+
+ queue.Enqueue(other, otherFilename);
+ await queue.AwaitStartAsync(other, otherFilename);
+
+ // no slot available; this upload is queued but never started
+ queue.Enqueue(username, filename);
+ var task = queue.AwaitStartAsync(username, filename);
+
+ Assert.False(task.IsCompleted);
+
+ queue.Complete(username, filename);
+
+ Assert.Single(groups[Application.DefaultGroup].UsedSlots);
+ Assert.Contains((other, otherFilename), groups[Application.DefaultGroup].UsedSlots);
+ }
+
+ [Theory, AutoData]
+ public async Task Cancels_Task_Of_Upload_That_Is_Waiting_For_A_Slot(string username, string filename, string other, string otherFilename)
+ {
+ var (queue, _) = GetFixture();
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ groups[Application.DefaultGroup].Slots = 1;
+
+ queue.Enqueue(other, otherFilename);
+ await queue.AwaitStartAsync(other, otherFilename);
+
+ // no slot available; the caller is left waiting on this task
+ queue.Enqueue(username, filename);
+ var task = queue.AwaitStartAsync(username, filename);
+
+ Assert.False(task.IsCompleted);
+
+ queue.Complete(username, filename);
+
+ // continuations run asynchronously, but the task's status is set synchronously
+ Assert.True(task.IsCanceled);
+ }
+
+ [Theory, AutoData]
+ public void Cancels_Task_Of_Upload_That_Was_Never_Ready(string username, string filename)
+ {
+ var (queue, _) = GetFixture();
+
+ queue.Enqueue(username, filename);
+
+ var uploads = queue.GetProperty<ConcurrentDictionary<string, List<Upload>>>("UploadDictionary");
+ var task = uploads[username][0].TaskCompletionSource.Task;
+
+ Assert.False(task.IsCompleted);
+
+ queue.Complete(username, filename);
+
+ Assert.True(task.IsCanceled);
+ }
+
+ [Theory, AutoData]
+ public async Task Does_Not_Cancel_Task_Of_Upload_That_Started(string username, string filename)
+ {
+ var (queue, _) = GetFixture();
+
+ queue.Enqueue(username, filename);
+ var task = queue.AwaitStartAsync(username, filename);
+ await task;
+
+ queue.Complete(username, filename);
+
+ Assert.True(task.IsCompletedSuccessfully);
+ }
+
+ [Theory, AutoData]
+ public async Task Releasing_A_Slot_Starts_The_Next_Ready_Upload(string username, string filename, string other, string otherFilename)
+ {
+ var (queue, _) = GetFixture();
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ groups[Application.DefaultGroup].Slots = 1;
+
+ queue.Enqueue(other, otherFilename);
+ await queue.AwaitStartAsync(other, otherFilename);
+
+ queue.Enqueue(username, filename);
+ var task = queue.AwaitStartAsync(username, filename);
+
+ Assert.False(task.IsCompleted);
+
+ queue.Complete(other, otherFilename);
+
+ Assert.True(task.IsCompletedSuccessfully);
+ Assert.Single(groups[Application.DefaultGroup].UsedSlots);
+ Assert.Contains((username, filename), groups[Application.DefaultGroup].UsedSlots);
}
[Theory, AutoData]
@@ -562,6 +689,526 @@ namespace slskd.Tests.Unit.Transfers.Uploads
Assert.Equal(task, uploads[username][0].TaskCompletionSource.Task);
}
+
+ [Theory, AutoData]
+ public void Occupies_Slot_When_Upload_Is_Released(string username, string filename)
+ {
+ var (queue, _) = GetFixture();
+
+ queue.Enqueue(username, filename);
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+
+ // enqueueing alone does not consume a slot; the upload must be ready first
+ Assert.Empty(groups[Application.DefaultGroup].UsedSlots);
+
+ var task = queue.AwaitStartAsync(username, filename);
+
+ Assert.True(task.IsCompletedSuccessfully);
+ Assert.Single(groups[Application.DefaultGroup].UsedSlots);
+ Assert.Contains((username, filename), groups[Application.DefaultGroup].UsedSlots);
+ }
+
+ [Theory, AutoData]
+ public void Does_Not_Occupy_Slot_When_No_Slot_Is_Available(string username, string filename, string other, string otherFilename)
+ {
+ var (queue, _) = GetFixture();
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ groups[Application.DefaultGroup].Slots = 1;
+ groups[Application.DefaultGroup].UsedSlots.Add((other, otherFilename));
+
+ queue.Enqueue(username, filename);
+ var task = queue.AwaitStartAsync(username, filename);
+
+ Assert.False(task.IsCompleted);
+ Assert.Single(groups[Application.DefaultGroup].UsedSlots);
+ Assert.DoesNotContain((username, filename), groups[Application.DefaultGroup].UsedSlots);
+ }
+ }
+
+ public class EstimatePosition
+ {
+ private static readonly DateTime Now = DateTime.UtcNow;
+
+ [Theory]
+ [InlineAutoData(QueueStrategy.RoundRobin)]
+ [InlineAutoData(QueueStrategy.FirstInFirstOut)]
+ public void Throws_NotFoundException_If_User_Has_No_Uploads(QueueStrategy strategy, string username, string filename)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, strategy);
+
+ var ex = Record.Exception(() => queue.EstimatePosition(username, filename));
+
+ Assert.IsType<NotFoundException>(ex);
+ }
+
+ [Theory]
+ [InlineAutoData(QueueStrategy.RoundRobin)]
+ [InlineAutoData(QueueStrategy.FirstInFirstOut)]
+ public void Throws_NotFoundException_If_File_Is_Not_Enqueued(QueueStrategy strategy, string username, string filename, string otherFilename)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, strategy);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+
+ uploads.TryAdd(username, new List<Upload>()
+ {
+ new Upload() { Username = username, Filename = otherFilename, Enqueued = Now },
+ });
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ var ex = Record.Exception(() => queue.EstimatePosition(username, filename));
+
+ Assert.IsType<NotFoundException>(ex);
+ }
+
+ [Theory, AutoData]
+ public void Throws_SlskdException_If_Group_Does_Not_Exist(string username, string filename, string groupName)
+ {
+ var (queue, mocks) = GetFixture();
+
+ mocks.UserService.Setup(m => m.GetGroup(username)).Returns(groupName);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(username, CreateUploads(username, count: 1));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ var ex = Record.Exception(() => queue.EstimatePosition(username, "file0"));
+
+ Assert.IsType<SlskdException>(ex);
+ }
+
+ [Theory, AutoData]
+ public void RoundRobin_Returns_Local_Position_If_User_Is_Alone_In_Group(string username)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.RoundRobin);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(username, CreateUploads(username, count: 3));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(0, queue.EstimatePosition(username, "file0"));
+ Assert.Equal(1, queue.EstimatePosition(username, "file1"));
+ Assert.Equal(2, queue.EstimatePosition(username, "file2"));
+ }
+
+ [Theory, AutoData]
+ public void RoundRobin_First_File_Is_Behind_Every_Other_User_With_Queued_Files(string username, string other1, string other2)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.RoundRobin);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(other1, CreateUploads(other1, count: 10, offset: -100));
+ uploads.TryAdd(other2, CreateUploads(other2, count: 1, offset: -100));
+ uploads.TryAdd(username, CreateUploads(username, count: 3));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ // pessimistic; both other users have a file in round 0, and are assumed to go first
+ Assert.Equal(2, queue.EstimatePosition(username, "file0"));
+ }
+
+ [Theory, AutoData]
+ public void RoundRobin_Adds_Lesser_Of_Local_Position_And_Upload_Count_For_Each_Other_User(string a, string b, string c, string d)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.RoundRobin);
+
+ // aaaaa
+ // bb
+ // cccccccccccc
+ // ddddddd
+ // ^ (local position 4)
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(a, CreateUploads(a, count: 5));
+ uploads.TryAdd(b, CreateUploads(b, count: 2));
+ uploads.TryAdd(c, CreateUploads(c, count: 12));
+ uploads.TryAdd(d, CreateUploads(d, count: 7));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ // 4 (local) + min(4, 5) + min(4, 2) + min(4, 12), + 1 each for a and c, which have a file in round 4
+ Assert.Equal(4 + 4 + 2 + 4 + 2, queue.EstimatePosition(d, "file4"));
+ }
+
+ [Theory]
+ [InlineAutoData(1, 3)]
+ [InlineAutoData(2, 4)]
+ [InlineAutoData(3, 5)]
+ [InlineAutoData(10, 5)]
+ public void RoundRobin_Counts_Other_User_As_Ahead_Only_If_They_Have_A_File_In_The_Same_Round(int otherCount, int expected, string username, string other)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.RoundRobin);
+
+ // the requested file is at local position 2 (round 2). the other user contends for round 2 only if they
+ // have more than 2 files: 2 (local) + min(2, otherCount) + (otherCount > 2 ? 1 : 0)
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(username, CreateUploads(username, count: 3));
+ uploads.TryAdd(other, CreateUploads(other, count: otherCount));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(expected, queue.EstimatePosition(username, "file2"));
+ }
+
+ [Theory, AutoData]
+ public void RoundRobin_Ignores_Users_In_Other_Groups(string username, string other)
+ {
+ var (queue, mocks) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.RoundRobin);
+
+ mocks.UserService.Setup(m => m.GetGroup(other)).Returns(Application.PrivilegedGroup);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(other, CreateUploads(other, count: 10));
+ uploads.TryAdd(username, CreateUploads(username, count: 3));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(2, queue.EstimatePosition(username, "file2"));
+ }
+
+ [Theory, AutoData]
+ public void FirstInFirstOut_Returns_Zero_If_Upload_Is_Earliest_In_Group(string username, string other)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.FirstInFirstOut);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(username, CreateUploads(username, count: 1));
+ uploads.TryAdd(other, CreateUploads(other, count: 5, offset: 10));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(0, queue.EstimatePosition(username, "file0"));
+ }
+
+ [Theory, AutoData]
+ public void FirstInFirstOut_Counts_All_Uploads_In_Group_Enqueued_Earlier(string a, string b, string c)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.FirstInFirstOut);
+
+ // enqueued at:
+ // a: 0, 3, 6
+ // b: 1, 4, 7
+ // c: 2, 5, 8
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(a, CreateUploads(a, count: 3, offset: 0, step: 3));
+ uploads.TryAdd(b, CreateUploads(b, count: 3, offset: 1, step: 3));
+ uploads.TryAdd(c, CreateUploads(c, count: 3, offset: 2, step: 3));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(0, queue.EstimatePosition(a, "file0"));
+ Assert.Equal(4, queue.EstimatePosition(b, "file1"));
+ Assert.Equal(8, queue.EstimatePosition(c, "file2"));
+ }
+
+ [Theory, AutoData]
+ public void FirstInFirstOut_Counts_Uploads_In_Progress(string username, string other)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.FirstInFirstOut);
+
+ var started = CreateUploads(other, count: 2);
+ started.ForEach(u => u.Started = Now);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(other, started);
+ uploads.TryAdd(username, CreateUploads(username, count: 1, offset: 10));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(2, queue.EstimatePosition(username, "file0"));
+ }
+
+ [Theory, AutoData]
+ public void FirstInFirstOut_Ignores_Users_In_Other_Groups(string username, string other)
+ {
+ var (queue, mocks) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.FirstInFirstOut);
+
+ mocks.UserService.Setup(m => m.GetGroup(other)).Returns(Application.PrivilegedGroup);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(other, CreateUploads(other, count: 10, offset: -100));
+ uploads.TryAdd(username, CreateUploads(username, count: 3));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(2, queue.EstimatePosition(username, "file2"));
+ }
+ }
+
+ public class ForecastPosition
+ {
+ [Theory]
+ [InlineAutoData(QueueStrategy.RoundRobin)]
+ [InlineAutoData(QueueStrategy.FirstInFirstOut)]
+ public void Returns_Zero_If_Slot_Is_Available_Regardless_Of_Queue(QueueStrategy strategy, string username, string other)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, strategy);
+ SetSlotAvailable(queue, true);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(other, CreateUploads(other, count: 10));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(0, queue.ForecastPosition(username).Position);
+ }
+
+ [Theory]
+ [InlineAutoData(QueueStrategy.RoundRobin)]
+ [InlineAutoData(QueueStrategy.FirstInFirstOut)]
+ public void Returns_Zero_Without_Free_Slot_If_No_Slot_Is_Available_And_Queue_Is_Empty(QueueStrategy strategy, string username)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, strategy);
+ SetSlotAvailable(queue, false);
+
+ var (_, _, freeSlots, position) = queue.ForecastPosition(username);
+
+ // nothing is ahead, but the transfer can't start immediately; callers use FreeSlots to tell the difference
+ Assert.Equal(0, position);
+ Assert.Equal(0, freeSlots);
+ }
+
+ [Theory, AutoData]
+ public void RoundRobin_Returns_Number_Of_Users_In_Group(string username, string other1, string other2)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.RoundRobin);
+ SetSlotAvailable(queue, false);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(other1, CreateUploads(other1, count: 10));
+ uploads.TryAdd(other2, CreateUploads(other2, count: 1));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ // worst case; the new file is last in the rotation. file counts don't matter
+ Assert.Equal(2, queue.ForecastPosition(username).Position);
+ }
+
+ [Theory, AutoData]
+ public void RoundRobin_Counts_Requesting_User_Once_Regardless_Of_Their_Queued_Files(string username, string other)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.RoundRobin);
+ SetSlotAvailable(queue, false);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(username, CreateUploads(username, count: 10));
+ uploads.TryAdd(other, CreateUploads(other, count: 1));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(2, queue.ForecastPosition(username).Position);
+ }
+
+ [Theory, AutoData]
+ public void RoundRobin_Ignores_Users_In_Other_Groups(string username, string other1, string other2)
+ {
+ var (queue, mocks) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.RoundRobin);
+ SetSlotAvailable(queue, false);
+
+ mocks.UserService.Setup(m => m.GetGroup(other2)).Returns(Application.PrivilegedGroup);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(other1, CreateUploads(other1, count: 1));
+ uploads.TryAdd(other2, CreateUploads(other2, count: 1));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(1, queue.ForecastPosition(username).Position);
+ }
+
+ [Theory, AutoData]
+ public void FirstInFirstOut_Returns_Number_Of_Uploads_In_Group(string username, string other1, string other2)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.FirstInFirstOut);
+ SetSlotAvailable(queue, false);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(username, CreateUploads(username, count: 2));
+ uploads.TryAdd(other1, CreateUploads(other1, count: 3));
+ uploads.TryAdd(other2, CreateUploads(other2, count: 4));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ // the new file goes to the back of the queue, behind every upload in the group, including the user's own
+ Assert.Equal(2 + 3 + 4, queue.ForecastPosition(username).Position);
+ }
+
+ [Theory, AutoData]
+ public void FirstInFirstOut_Counts_Uploads_In_Progress(string username, string other)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.FirstInFirstOut);
+ SetSlotAvailable(queue, false);
+
+ var started = CreateUploads(other, count: 2);
+ started.ForEach(u => u.Started = Now);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(other, started);
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(2, queue.ForecastPosition(username).Position);
+ }
+
+ [Theory, AutoData]
+ public void FirstInFirstOut_Ignores_Users_In_Other_Groups(string username, string other1, string other2)
+ {
+ var (queue, mocks) = GetFixture();
+
+ SetStrategy(queue, QueueStrategy.FirstInFirstOut);
+ SetSlotAvailable(queue, false);
+
+ mocks.UserService.Setup(m => m.GetGroup(other2)).Returns(Application.PrivilegedGroup);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(other1, CreateUploads(other1, count: 3));
+ uploads.TryAdd(other2, CreateUploads(other2, count: 10));
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ Assert.Equal(3, queue.ForecastPosition(username).Position);
+ }
+
+ [Theory]
+ [InlineAutoData(QueueStrategy.RoundRobin)]
+ [InlineAutoData(QueueStrategy.FirstInFirstOut)]
+ public void Returns_Group_And_Slot_Counts_If_No_Slot_Is_Available(QueueStrategy strategy, string username)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, strategy);
+ SetSlotAvailable(queue, false);
+
+ var (group, totalSlots, freeSlots, _) = queue.ForecastPosition(username);
+
+ Assert.Equal(Application.DefaultGroup, group);
+ Assert.Equal(1, totalSlots);
+ Assert.Equal(0, freeSlots);
+ }
+
+ [Theory, AutoData]
+ public void Returns_Group_And_Slot_Counts_If_Slot_Is_Available(string username)
+ {
+ var (queue, _) = GetFixture();
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ groups[Application.DefaultGroup].Slots = 3;
+ FillSlots(groups[Application.DefaultGroup], 1);
+
+ var (group, totalSlots, freeSlots, position) = queue.ForecastPosition(username);
+
+ Assert.Equal(Application.DefaultGroup, group);
+ Assert.Equal(3, totalSlots);
+ Assert.Equal(2, freeSlots);
+ Assert.Equal(0, position);
+ }
+
+ [Theory, AutoData]
+ public void Ignores_Slots_Used_By_Other_Groups(string username)
+ {
+ var (queue, _) = GetFixture();
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ var globalSlots = queue.GetProperty<int>("GlobalSlots");
+
+ // every global slot is held by the privileged group, but the default group's own slots are free
+ FillSlots(groups[Application.PrivilegedGroup], globalSlots);
+ groups[Application.DefaultGroup].Slots = 2;
+
+ var (group, totalSlots, freeSlots, position) = queue.ForecastPosition(username);
+
+ Assert.Equal(Application.DefaultGroup, group);
+ Assert.Equal(2, totalSlots);
+ Assert.Equal(2, freeSlots);
+ Assert.Equal(0, position);
+ }
+
+ [Theory, AutoData]
+ public void Limits_Total_Slots_To_Global_Slots(string username)
+ {
+ var (queue, _) = GetFixture();
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ var globalSlots = queue.GetProperty<int>("GlobalSlots");
+
+ groups[Application.DefaultGroup].Slots = globalSlots + 10;
+
+ var (_, totalSlots, freeSlots, _) = queue.ForecastPosition(username);
+
+ Assert.Equal(globalSlots, totalSlots);
+ Assert.Equal(globalSlots, freeSlots);
+ }
+
+ [Theory, AutoData]
+ public void Free_Slots_Is_Never_Negative(QueueStrategy strategy, string username)
+ {
+ var (queue, _) = GetFixture();
+
+ SetStrategy(queue, strategy);
+
+ // the group holds more slots than it is allowed, for instance after its slot count was reduced at run time
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ groups[Application.DefaultGroup].Slots = 1;
+ FillSlots(groups[Application.DefaultGroup], 3);
+
+ var (_, totalSlots, freeSlots, position) = queue.ForecastPosition(username);
+
+ Assert.Equal(1, totalSlots);
+ Assert.Equal(0, freeSlots);
+ Assert.Equal(0, position);
+ }
+
+ [Theory, AutoData]
+ public void Throws_SlskdException_If_Group_Does_Not_Exist(string username, string groupName)
+ {
+ var (queue, mocks) = GetFixture();
+
+ mocks.UserService.Setup(m => m.GetGroup(username)).Returns(groupName);
+
+ var ex = Record.Exception(() => queue.ForecastPosition(username));
+
+ Assert.IsType<SlskdException>(ex);
+ }
}
public class Process
@@ -573,13 +1220,36 @@ namespace slskd.Tests.Unit.Transfers.Uploads
var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
- groups[Application.DefaultGroup].UsedSlots = int.MaxValue;
+ FillSlots(groups[Application.DefaultGroup], queue.GetProperty<int>("GlobalSlots"));
var result = queue.InvokeMethod<UploadGroup>("Process");
Assert.Null(result);
}
+ [Theory, AutoData]
+ public void Does_Not_Release_Upload_If_Global_Slots_Are_Consumed_Across_Groups(string user1, string file1)
+ {
+ var (queue, _) = GetFixture();
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ var globalSlots = queue.GetProperty<int>("GlobalSlots");
+
+ // split the global slots between two groups; neither group is full on its own
+ FillSlots(groups[Application.PrivilegedGroup], globalSlots - 1);
+ FillSlots(groups[Application.LeecherGroup], 1);
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(user1, new List<Upload>() { new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow } });
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ var result = queue.InvokeMethod<Upload>("Process");
+
+ Assert.Null(result);
+ Assert.Empty(groups[Application.DefaultGroup].UsedSlots);
+ }
+
[Fact]
public void Does_Nothing_If_No_Uploads()
{
@@ -615,7 +1285,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads
}
[Theory, AutoData]
- public void Increments_UsedSlots_Of_Group(string user1, string file1)
+ public void Occupies_Slot_In_Group_Of_Released_Upload(string user1, string file1)
{
var (queue, mocks) = GetFixture();
@@ -634,7 +1304,33 @@ namespace slskd.Tests.Unit.Transfers.Uploads
var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
- Assert.Equal(1, groups[Application.PrivilegedGroup].UsedSlots);
+ Assert.Single(groups[Application.PrivilegedGroup].UsedSlots);
+ Assert.Contains((user1, file1), groups[Application.PrivilegedGroup].UsedSlots);
+
+ // no other group is charged for the slot
+ Assert.All(groups.Values.Where(g => g.Name != Application.PrivilegedGroup), g => Assert.Empty(g.UsedSlots));
+ }
+
+ [Theory, AutoData]
+ public void Does_Not_Release_Upload_That_Already_Started(string user1, string file1)
+ {
+ var (queue, _) = GetFixture();
+
+ var uploads = new ConcurrentDictionary<string, List<Upload>>();
+ uploads.TryAdd(user1, new List<Upload>()
+ {
+ new Upload() { Username = user1, Filename = file1, Ready = DateTime.UtcNow, Started = DateTime.UtcNow, Group = Application.DefaultGroup },
+ });
+
+ queue.SetProperty("UploadDictionary", uploads);
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ groups[Application.DefaultGroup].UsedSlots.Add((user1, file1));
+
+ var result = queue.InvokeMethod<Upload>("Process");
+
+ Assert.Null(result);
+ Assert.Single(groups[Application.DefaultGroup].UsedSlots);
}
[Theory, AutoData]
@@ -663,6 +1359,11 @@ namespace slskd.Tests.Unit.Transfers.Uploads
Assert.Equal(user1, result.Username);
Assert.Equal(file1, result.Filename);
+
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+
+ Assert.Contains((user1, file1), groups[Application.PrivilegedGroup].UsedSlots);
+ Assert.Empty(groups[Application.DefaultGroup].UsedSlots);
}
[Theory, AutoData]
@@ -691,13 +1392,16 @@ namespace slskd.Tests.Unit.Transfers.Uploads
// all default group slots consumed
var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
groups[Application.DefaultGroup].Slots = 1;
- groups[Application.DefaultGroup].UsedSlots = 1;
+ FillSlots(groups[Application.DefaultGroup], 1);
var result = queue.InvokeMethod<Upload>("Process");
// leecher group upload released
Assert.Equal(user2, result.Username);
Assert.Equal(file2, result.Filename);
+
+ Assert.Contains((user2, file2), groups[Application.LeecherGroup].UsedSlots);
+ Assert.DoesNotContain((user1, file1), groups[Application.DefaultGroup].UsedSlots);
}
[Theory, AutoData]
@@ -765,6 +1469,44 @@ namespace slskd.Tests.Unit.Transfers.Uploads
}
}
+ private static readonly DateTime Now = DateTime.UtcNow;
+
+ private static void SetStrategy(UploadQueue queue, QueueStrategy strategy)
+ {
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ groups[Application.DefaultGroup].Strategy = strategy;
+ }
+
+ private static void SetSlotAvailable(UploadQueue queue, bool available)
+ {
+ var groups = queue.GetProperty<Dictionary<string, UploadGroup>>("Groups");
+ groups[Application.DefaultGroup].Slots = 1;
+ groups[Application.DefaultGroup].UsedSlots.Clear();
+ FillSlots(groups[Application.DefaultGroup], available ? 0 : 1);
+ }
+
+ // occupies the specified number of slots in the group with placeholder uploads
+ private static void FillSlots(UploadGroup group, int count)
+ {
+ for (int i = 0; i < count; i++)
+ {
+ group.UsedSlots.Add(($"placeholder-user-{i}", $"placeholder-file-{i}"));
+ }
+ }
+
+ // creates uploads named file0..fileN, enqueued at Now + offset + (i * step) seconds, in ascending order
+ private static List<Upload> CreateUploads(string username, int count, int offset = 0, int step = 1)
+ {
+ return Enumerable.Range(0, count)
+ .Select(i => new Upload()
+ {
+ Username = username,
+ Filename = $"file{i}",
+ Enqueued = Now.AddSeconds(offset + (i * step)),
+ })
+ .ToList();
+ }
+
private static (UploadQueue queue, Mocks mocks) GetFixture(Options options = null)
{
var mocks = new Mocks(options);