From aa3401f33bb0a6e55324f1f0b67c9946a2df86db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:18:11 -0500 Subject: whitelist log directory --- src/slskd/Files/FileService.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 62d17f20..6ab2328a 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -61,6 +61,7 @@ namespace slskd.Files { Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), + Path.GetFullPath(Program.LogDirectory), }; private ILogger Log { get; } = Serilog.Log.ForContext(); -- cgit v1.2.3 From 96420adbda382a91406c71ecfdddd5878bfb8f9d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:18:43 -0500 Subject: rename method for clarity --- src/slskd/Files/API/FilesController.cs | 2 +- src/slskd/Files/FileService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') 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 6ab2328a..f348e658 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -301,7 +301,7 @@ namespace slskd.Files /// Thrown if the specified directory has a relative path. /// Thrown if the specified directory does not exist. /// Thrown if the specified root directory is restricted. - public virtual async Task ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) + public virtual async Task ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); -- cgit v1.2.3 From 514911ad65d3bdad6c05eedeef1d0aa3213803ca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:18:57 -0500 Subject: warnings --- src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs | 2 +- src/slskd/Transfers/API/DTO/EnqueueDownloadBatchResponse.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) (limited to 'src') 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 @@ -// +// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ 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 @@ -// +// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 5f98afac..1c2b85b5 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 { -- cgit v1.2.3 From 1f6c6b1bf962dd03c66f55098704530bb5c4620a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:19:09 -0500 Subject: stub function to return file contents --- src/slskd/Files/FileService.cs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index f348e658..a78d4dd4 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -365,6 +365,39 @@ namespace slskd.Files }); } + 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); + } + catch (Exception ex) + { + throw new IOException($"Failed to open file {Path.GetFileName(filename)} for reading: {ex.Message}", ex); + } + } + /// /// Creates a new file with the specified fully qualified and the optional , /// returning a with which the contents of the file can be written. -- cgit v1.2.3 From 91ad4826bbd0d89f69276ea0789e1498f2a92801 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 02:19:36 -0500 Subject: stub endpoints to list and read log files --- src/slskd/Core/API/Controllers/LogsController.cs | 59 +++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 8055c696..a12d9187 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -32,9 +32,14 @@ namespace slskd.Core.API { + using System; + using System.IO; + using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Serilog; + using slskd.Files; /// /// Logs. @@ -46,15 +51,67 @@ namespace slskd.Core.API [Consumes("application/json")] public class LogsController : ControllerBase { + public LogsController( + FileService fileService, + OptionsAtStartup optionsAtStartup) + { + Files = fileService; + OptionsAtStartup = optionsAtStartup; + } + + private FileService Files { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + /// /// Gets the last few application logs. /// /// - [HttpGet] + [HttpGet("buffer")] [Authorize(Policy = AuthPolicy.Any)] public IActionResult Logs() { return Ok(Program.LogBuffer); } + + [HttpGet] + [Authorize(Policy = AuthPolicy.Any)] + public async Task List() + { + var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + { + AttributesToSkip = FileAttributes.System, + RecurseSubdirectories = false, + }); + + return Ok(directory.Files); + } + + [HttpGet("{filename}")] + [Authorize(Policy = AuthPolicy.Any)] + public async Task Get(string filename, [FromQuery] bool download = false) + { + filename = FileSafety.GetFileNameSafely(filename); + + try + { + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, filename)); + + if (download) + { + return File(stream, "text/plain", filename); + } + + return File(stream, "text/plain"); + } + catch (UnauthorizedException) + { + return NotFound(); + } + catch (NotFoundException) + { + return NotFound(); + } + } } } -- cgit v1.2.3 From 8133ee872bfe07e859fc09bf6ea7062c08249ecb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:08:06 -0500 Subject: docs for GetFileContents --- src/slskd/Files/FileService.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index a78d4dd4..c100c7e9 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -365,6 +365,16 @@ namespace slskd.Files }); } + /// + /// Retrieves the contents of the specified as a stream. + /// + /// The file for which contents are to be retrieved. + /// A Stream containing the contents of the file. + /// Thrown if the specified filename is null or contains only whitespace. + /// Thrown if the specified filename contains path traversal segments. + /// Thrown if the specified file is not within an allowed directory. + /// Thrown if the specified file does not exist. + /// Thrown if the file can't be opened for some reason. public virtual Stream GetFileContents(string filename) { ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); -- cgit v1.2.3 From 2c719dd8f5f330de61caf850c9087b5b989c1611 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:10:29 -0500 Subject: docs, change routes, lock endpoints down to administrators only --- src/slskd/Core/API/Controllers/LogsController.cs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index a12d9187..465993c1 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -67,15 +67,19 @@ namespace slskd.Core.API /// Gets the last few application logs. /// /// - [HttpGet("buffer")] - [Authorize(Policy = AuthPolicy.Any)] + [HttpGet("live")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public IActionResult Logs() { return Ok(Program.LogBuffer); } - [HttpGet] - [Authorize(Policy = AuthPolicy.Any)] + /// + /// Lists the log files currently on disk. + /// + /// + [HttpGet("files")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task List() { var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions @@ -87,8 +91,14 @@ namespace slskd.Core.API return Ok(directory.Files); } - [HttpGet("{filename}")] - [Authorize(Policy = AuthPolicy.Any)] + /// + /// Retrieves the requested log file from disk. + /// + /// + /// + /// + [HttpGet("files/{filename}")] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task Get(string filename, [FromQuery] bool download = false) { filename = FileSafety.GetFileNameSafely(filename); -- cgit v1.2.3 From f76b210689cf1d0bc8b3f0d971194263eb66b3d7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 18:25:11 -0500 Subject: remove uneccessary import --- src/slskd/Core/API/Controllers/LogsController.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 465993c1..590ee6b7 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -52,15 +52,12 @@ namespace slskd.Core.API public class LogsController : ControllerBase { public LogsController( - FileService fileService, - OptionsAtStartup optionsAtStartup) + FileService fileService) { Files = fileService; - OptionsAtStartup = optionsAtStartup; } private FileService Files { get; } - private OptionsAtStartup OptionsAtStartup { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); /// -- cgit v1.2.3 From bb25e7accb1e47bfea4ddbb998106ad7365a88a6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 19:08:47 -0500 Subject: add log file fetch and download --- src/slskd/Core/API/Controllers/LogsController.cs | 92 ++++++++++++++++++++++-- 1 file changed, 88 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 590ee6b7..43300e63 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -98,27 +98,111 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task Get(string filename, [FromQuery] bool download = false) { - filename = FileSafety.GetFileNameSafely(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"); + } try { - var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, filename)); + var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); if (download) { return File(stream, "text/plain", filename); } - return File(stream, "text/plain"); + var logs = await ParseLogEntriesAsync(stream); + + return Ok(logs); } catch (UnauthorizedException) { - return NotFound(); + return Unauthorized(); } catch (NotFoundException) { return NotFound(); } } + + private async Task> ParseLogEntriesAsync(Stream stream) + { + Dictionary levels = new() + { + ["VRB"] = nameof(Serilog.Events.LogEventLevel.Verbose), + ["DBG"] = nameof(Serilog.Events.LogEventLevel.Debug), + ["INF"] = nameof(Serilog.Events.LogEventLevel.Information), + ["WRN"] = nameof(Serilog.Events.LogEventLevel.Warning), + ["ERR"] = nameof(Serilog.Events.LogEventLevel.Error), + ["FTL"] = nameof(Serilog.Events.LogEventLevel.Fatal), + }; + + var list = new List(); + + var reader = new StreamReader(stream); + string line; + + while ((line = await reader.ReadLineAsync()) is not null) + { + if (line.Length == 0) + { + continue; + } + + try + { + // if the line isn't a log, append it to the previous message + if (!line.StartsWith('[')) + { + var lastIndex = list.Count - 1; + + if (lastIndex >= 0) + { + var old = list[lastIndex]; + + list[lastIndex] = new LogRecord + { + Timestamp = old.Timestamp, + Level = old.Level, + Message = old.Message + '\n' + line, + }; + } + + continue; + } + + var parts = line.TrimStart('[').Split(']', count: 2); + var meta = parts[0].Split(' '); + + list.Add(new LogRecord + { + Timestamp = DateTime.Parse(meta[0]), + Level = levels[meta[1]], + Message = parts[1].TrimStart(), + }); + } + catch (Exception ex) + { + Log.Warning(ex, "Error parsing log message: {Message}", ex.Message); + continue; + } + } + + return list; + } } } -- cgit v1.2.3 From 3b2d0c62f410a4db800055b831bf37c1e512c1b7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 23 Aug 2026 19:10:36 -0500 Subject: wip of log zip --- src/slskd/Core/API/Controllers/LogsController.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 43300e63..569848b2 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -33,7 +33,10 @@ namespace slskd.Core.API { using System; + using System.Collections.Generic; using System.IO; + using System.IO.Compression; + using System.Threading; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -77,7 +80,7 @@ namespace slskd.Core.API /// [HttpGet("files")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task List() + public async Task List(CancellationToken cancellationToken, [FromQuery] bool download = false) { var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { @@ -85,6 +88,16 @@ namespace slskd.Core.API RecurseSubdirectories = false, }); + if (download) + { + var stream = new MemoryStream(); + await ZipFile.CreateFromDirectoryAsync(Program.LogDirectory, stream, cancellationToken: cancellationToken); + + var now = DateTime.UtcNow; + + return File(stream, "application/zip", $"logs-{now:yyyyMMdd}-{new DateTimeOffset(now).ToUnixTimeMilliseconds}.zip"); + } + return Ok(directory.Files); } -- cgit v1.2.3 From e5a8ae30b640212386cbb4e1fffd2ae937234793 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 08:55:24 -0500 Subject: forget about downloading a zip --- src/slskd/Core/API/Controllers/LogsController.cs | 11 ----------- 1 file changed, 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 569848b2..a35c6097 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -35,7 +35,6 @@ namespace slskd.Core.API using System; using System.Collections.Generic; using System.IO; - using System.IO.Compression; using System.Threading; using System.Threading.Tasks; using Asp.Versioning; @@ -88,16 +87,6 @@ namespace slskd.Core.API RecurseSubdirectories = false, }); - if (download) - { - var stream = new MemoryStream(); - await ZipFile.CreateFromDirectoryAsync(Program.LogDirectory, stream, cancellationToken: cancellationToken); - - var now = DateTime.UtcNow; - - return File(stream, "application/zip", $"logs-{now:yyyyMMdd}-{new DateTimeOffset(now).ToUnixTimeMilliseconds}.zip"); - } - return Ok(directory.Files); } -- cgit v1.2.3 From e427bc851f09fbda5768ef427de83286ee1b4822 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 17:56:57 -0500 Subject: use r/w fileshare --- src/slskd/Files/FileService.cs | 2 +- src/web/src/components/System/Logs/Live.jsx | 98 ++++++++++++++++++++++++++++ src/web/src/components/System/Logs/index.jsx | 98 ---------------------------- 3 files changed, 99 insertions(+), 99 deletions(-) create mode 100644 src/web/src/components/System/Logs/Live.jsx delete mode 100644 src/web/src/components/System/Logs/index.jsx (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index c100c7e9..e3479210 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -400,7 +400,7 @@ namespace slskd.Files try { - return new FileStream(filename, FileMode.Open, FileAccess.Read); + return new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); } catch (Exception ex) { 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..f36258ec --- /dev/null +++ b/src/web/src/components/System/Logs/Live.jsx @@ -0,0 +1,98 @@ +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', +}; + +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 ( +
+ {!connected && } + {connected && ( + + + + Timestamp + Level + Message + + + + {logs.map((log) => ( + + {this.formatTimestamp(log.timestamp)} + {levels[log.level] || log.level} + + {log.message} + + + ))} + +
+ )} +
+ ); + } +} + +export default Logs; diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx deleted file mode 100644 index f36258ec..00000000 --- a/src/web/src/components/System/Logs/index.jsx +++ /dev/null @@ -1,98 +0,0 @@ -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', -}; - -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 ( -
- {!connected && } - {connected && ( - - - - Timestamp - Level - Message - - - - {logs.map((log) => ( - - {this.formatTimestamp(log.timestamp)} - {levels[log.level] || log.level} - - {log.message} - - - ))} - -
- )} -
- ); - } -} - -export default Logs; -- cgit v1.2.3 From f3dca154f98a9f37c9323b2e276e4f6d5540850c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 18:01:56 -0500 Subject: share logs --- src/slskd/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 5260760f..778502a2 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1247,7 +1247,8 @@ namespace slskd Path.Combine(LogDirectory, $"{AppName}-.log"), outputTemplate: (OptionsAtStartup.Debug ? "[{SourceContext}] " : string.Empty) + "[{Timestamp:HH:mm:ss} {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 => -- cgit v1.2.3 From 556b588197f31ed98c0e3dec7a9ceeddf8eb10e3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 18:04:46 -0500 Subject: enable disk logging by default --- config/slskd.example.yml | 2 +- src/slskd/Core/Options.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index af2871e2..442d0ce3 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -195,7 +195,7 @@ # circuit_breaker: 500 # maximum number of pending search requests # response_file_limit: 500 # maximum number of files to return in a single search response # logger: -# disk: false +# disk: true # no_color: false # loki: ~ # metrics: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index d1062a2c..84dafe29 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1458,11 +1458,11 @@ namespace slskd /// /// Gets a value indicating whether to write logs to disk. /// - [Argument(default, "disk-logger")] - [EnvironmentVariable("DISK_LOGGER")] - [Description("enable logging to disk")] + [Argument(default, "no-disk-logger")] + [EnvironmentVariable("NO_DISK_LOGGER")] + [Description("disable logging to disk")] [RequiresRestart] - public bool Disk { get; init; } = false; + public bool Disk { get; init; } = true; /// /// Gets a value indicating whether to suppress colorization of console logs. -- cgit v1.2.3 From 42e69540d07af2819b74735c1aea194eb344ac46 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 24 Aug 2026 18:05:56 -0500 Subject: reduce default log retention to 30 days, increase minimum to 7 --- src/slskd/Core/Options.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 84dafe29..3499e564 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1500,8 +1500,8 @@ namespace slskd /// /// Gets the time to retain logs, in days. /// - [Range(1, maximum: int.MaxValue)] - public int Logs { get; init; } = 180; + [Range(7, maximum: int.MaxValue)] + public int Logs { get; init; } = 30; /// /// Transfer retention options. -- cgit v1.2.3 From 216c8ab2bcf84c2e11b8fa6fa640a9fdaa37f472 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:14 -0500 Subject: add date and milliseconds to disk logs --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 778502a2..def4c2aa 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1245,7 +1245,7 @@ namespace slskd e => OptionsAtStartup.Logger.Disk, 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), shared: true))) // allow log file to be read concurrently -- cgit v1.2.3 From ec02691a206451e9e9c11a2f305ab928c6f9676b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:38 -0500 Subject: add regex for parsing log lines --- src/slskd/Core/API/Controllers/LogsController.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index a35c6097..fff5e843 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -35,6 +35,7 @@ namespace slskd.Core.API using System; using System.Collections.Generic; using System.IO; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Asp.Versioning; @@ -61,6 +62,7 @@ namespace slskd.Core.API private FileService Files { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private Regex LogLineParseRegex { get; } = new Regex(@"^(\[?([a-zA-Z\.]*)\]?\s)?(\[((\d{4}-\d{2}-\d{2})T)?(\d{2}:\d{2}:\d{2}(?:.\d{3})?)\s([A-Z]+)\]\s)?(.*)", RegexOptions.Compiled); /// /// Gets the last few application logs. -- cgit v1.2.3 From 5b063c478b5d5f8e694a5cdea76af0d8eada3150 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:11:53 -0500 Subject: leave note about streaming optimization --- src/slskd/Core/API/Controllers/LogsController.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index fff5e843..13f8ab95 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -129,6 +129,10 @@ namespace slskd.Core.API return File(stream, "text/plain", filename); } + // future optimization: use IAsyncEnumerable to 'stream' the log records instead of beating up + // memory to build a list. save each log in memory and then emit it when the next log + // (starting with '[') is read, which indicates that it's not multi-line. in other words, a 1-log buffer + // that is flushed when the next log is read, or the file is complete var logs = await ParseLogEntriesAsync(stream); return Ok(logs); -- cgit v1.2.3 From ea4ca200cd6dda759917dcd76d47d2bddfa5d2f5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:12:23 -0500 Subject: break if the file is being appended to avoid an endless loop --- src/slskd/Core/API/Controllers/LogsController.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 13f8ab95..d7e011eb 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -161,6 +161,8 @@ namespace slskd.Core.API var list = new List(); + var currentLength = stream.Length; + var reader = new StreamReader(stream); string line; @@ -171,6 +173,15 @@ namespace slskd.Core.API continue; } + if (stream.Position > currentLength) + { + // if we're reading the latest file, Serilog can append it while we're inside of this loop, + // or worse, a problem inside this loop appends lines. if this happens the position will grow + // beyond the length at the start + Log.Information("Parsing of log file {Filename} stopped before end of file; log was appended during the read"); + break; + } + try { // if the line isn't a log, append it to the previous message -- cgit v1.2.3 From e2bc14a1572c4a3d035ac7a4ffe47cff35fd2e16 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:12:39 -0500 Subject: parse logs with the regex --- src/slskd/Core/API/Controllers/LogsController.cs | 48 +++++++++++++++++++++--- 1 file changed, 43 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index d7e011eb..1c1f057b 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -204,14 +204,52 @@ namespace slskd.Core.API continue; } - var parts = line.TrimStart('[').Split(']', count: 2); - var meta = parts[0].Split(' '); + /* + there should be 3 possible line types: + + debug: + [Some.Context] [2000-1-1T11:11:11 WRN] foo bar + + info: + [2000-1-1T11:11:11 WRN] foo bar + + line wrap/newline: + foo bar + + additionally, date was added to disk log files around 9/1/26, so we need to gracefully handle + cases where the timestamp contains only hh:mm:ss, and substitute the unix epoch for the date + + the regex includes 8 matching groups (hopefully this comment and the regex don't diverge!) + using the debug log as an example, the groups are: + + 0. [Some.Context] [2026-08-29T11:11:11 WRN] foo bar + 1. [Some.Context] + 2. Some.Context + 3. [2000-01-01T11:11:11 WRN] + 4. 2000-01-01T + 5. 2000-01-01 + 6. 11:11:11 + 7. WRN + 8. foo bar + + the final group in the regex is simply `.*`, so we're guaranteed to get a match for every line + */ + match = LogLineParseRegex.Match(line); + + var grp = match.Groups; + + var date = grp[5].Success ? DateOnly.Parse(grp[5].Value) : DateOnly.FromDateTime(DateTime.UnixEpoch); + var time = grp[6].Success ? TimeOnly.Parse(grp[6].Value) : TimeOnly.FromDateTime(DateTime.UnixEpoch); + var dateTime = date.ToDateTime(time); + + var level = levels.ContainsKey(grp[7].Value) ? levels[grp[7].Value] : null; list.Add(new LogRecord { - Timestamp = DateTime.Parse(meta[0]), - Level = levels[meta[1]], - Message = parts[1].TrimStart(), + Context = grp[2].Value, + Timestamp = dateTime, + Level = level, + Message = grp[8].Value, }); } catch (Exception ex) -- cgit v1.2.3 From 0ef9cd71e115642cce876372c76fd3a1d8de6a4b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 29 Aug 2026 19:13:02 -0500 Subject: wip --- src/slskd/Core/API/Controllers/LogsController.cs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 1c1f057b..1a3e027f 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -165,6 +165,7 @@ namespace slskd.Core.API var reader = new StreamReader(stream); string line; + Match match = default; while ((line = await reader.ReadLineAsync()) is not null) { @@ -251,14 +252,31 @@ namespace slskd.Core.API Level = level, Message = grp[8].Value, }); + + Log.Information("Added: {Text}", grp[8].Value); } catch (Exception ex) { - Log.Warning(ex, "Error parsing log message: {Message}", ex.Message); - continue; + Log.Debug("Error parsing log message: {Message}. Line: {Line}", ex.Message, line); + + Log.Warning("Got {GroupCount} groups", match.Groups.Count); + + foreach (var key in match.Groups.Keys) + { + Log.Warning("Key: {Key}, Success: {Success}, Value: {Value}", key, match.Groups[key].Success, match.Groups[key].Value); + } + + break; + + list.Add(new LogRecord + { + Message = line, + }); } } + Log.Information("Returned {Lines}", list.Count); + return list; } } -- cgit v1.2.3 From ca02e5352f17ed89142c456c27b70d7e8f1a50ad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 5 Sep 2026 18:45:38 -0500 Subject: wip --- src/web/src/components/System/Logs/Controls.jsx | 83 ++++++++ .../src/components/System/Logs/FileNavigator.jsx | 64 ++++++ src/web/src/components/System/Logs/History.jsx | 216 +++++++++++++++++++++ src/web/src/components/System/Logs/Live.jsx | 61 ++---- src/web/src/components/System/Logs/LogTable.jsx | 90 +++++++++ src/web/src/components/System/Logs/Logs.css | 49 +++++ src/web/src/components/System/Logs/index.jsx | 35 ++++ src/web/src/lib/logs.js | 29 +++ 8 files changed, 581 insertions(+), 46 deletions(-) create mode 100644 src/web/src/components/System/Logs/Controls.jsx create mode 100644 src/web/src/components/System/Logs/FileNavigator.jsx create mode 100644 src/web/src/components/System/Logs/History.jsx create mode 100644 src/web/src/components/System/Logs/LogTable.jsx create mode 100644 src/web/src/components/System/Logs/Logs.css create mode 100644 src/web/src/components/System/Logs/index.jsx create mode 100644 src/web/src/lib/logs.js (limited to 'src') diff --git a/src/web/src/components/System/Logs/Controls.jsx b/src/web/src/components/System/Logs/Controls.jsx new file mode 100644 index 00000000..f5d7a030 --- /dev/null +++ b/src/web/src/components/System/Logs/Controls.jsx @@ -0,0 +1,83 @@ +import './Logs.css'; +import React from 'react'; +import { Dropdown, Input, Segment } from 'semantic-ui-react'; + +/** + * Serilog's levels, ordered least to most severe. Selecting a level displays + * that level and everything below it in this list. + */ +export const levels = [ + 'Verbose', + 'Debug', + 'Information', + 'Warning', + 'Error', + 'Fatal', +]; + +const levelOptions = levels.map((level, index) => ({ + key: level, + text: index === 0 ? `${level} (all)` : `${level} and above`, + value: level, +})); + +export const perPageOptions = [50, 100, 200, 500, 1_000].map((count) => ({ + key: count, + text: `${count} per page`, + value: count, +})); + +export const defaultPerPage = 200; + +const Controls = ({ + filter, + level, + onFilterChange, + onLevelChange, + onPerPageChange, + perPage, +}) => { + return ( + + onLevelChange(value)} + options={levelOptions} + text={levelOptions.find((o) => o.value === level)?.text} + /> + onPerPageChange(value)} + options={perPageOptions} + text={perPageOptions.find((o) => o.value === perPage)?.text} + /> + onFilterChange(''), + } + } + className="logs-filter" + label={{ content: 'Filter', icon: 'filter' }} + onChange={(_event, data) => onFilterChange(data.value)} + placeholder="Show only lines matching this text" + value={filter} + /> + + ); +}; + +export default Controls; diff --git a/src/web/src/components/System/Logs/FileNavigator.jsx b/src/web/src/components/System/Logs/FileNavigator.jsx new file mode 100644 index 00000000..81c0e77c --- /dev/null +++ b/src/web/src/components/System/Logs/FileNavigator.jsx @@ -0,0 +1,64 @@ +import './Logs.css'; +import { formatBytes, formatDate } from '../../../lib/util'; +import React from 'react'; +import { Button, Dropdown } from 'semantic-ui-react'; + +/** + * Sits just above the log display. The dropdown selects a file directly; the + * arrow buttons step through the newest-to-oldest sorted file list one at a + * time, left toward newer files and right toward older ones. + */ +const FileNavigator = ({ file, files, onChange }) => { + const index = files.findIndex((f) => f.name === file); + + const options = files.map((f) => ({ + description: `${formatBytes(f.length)} · ${formatDate(f.modifiedAt)}`, + key: f.name, + text: f.name, + value: f.name, + })); + + const goNewer = () => { + if (index > 0) { + onChange(files[index - 1].name); + } + }; + + const goOlder = () => { + if (index !== -1 && index < files.length - 1) { + onChange(files[index + 1].name); + } + }; + + return ( +
+
+ ); +}; + +export default FileNavigator; diff --git a/src/web/src/components/System/Logs/History.jsx b/src/web/src/components/System/Logs/History.jsx new file mode 100644 index 00000000..1bf4976c --- /dev/null +++ b/src/web/src/components/System/Logs/History.jsx @@ -0,0 +1,216 @@ +import './Logs.css'; +import '../System.css'; +import { getLogFile, getLogFiles } from '../../../lib/logs'; +import { ErrorSegment, LoaderSegment } from '../../Shared'; +import Controls, { defaultPerPage, levels } from './Controls'; +import FileNavigator from './FileNavigator'; +import LogTable from './LogTable'; +import React, { useEffect, useMemo, useState } from 'react'; +import { Pagination } from 'semantic-ui-react'; + +/** + * Sorts log files newest first, so that the most recent is selected by default + * and sits at the top of the file dropdown. + */ +const newestFirst = (files) => + [...files].sort((a, b) => { + const dateA = a.modifiedAt ? new Date(a.modifiedAt) : new Date(0); + const dateB = b.modifiedAt ? new Date(b.modifiedAt) : new Date(0); + + return dateB - dateA; + }); + +const History = () => { + const [files, setFiles] = useState([]); + const [file, setFile] = useState(undefined); + const [logs, setLogs] = useState([]); + const [loadingFiles, setLoadingFiles] = useState(true); + const [loadingLogs, setLoadingLogs] = useState(false); + const [error, setError] = useState(undefined); + + const [level, setLevel] = useState(levels[0]); + const [filter, setFilter] = useState(''); + const [sortDirection, setSortDirection] = useState('descending'); + const [page, setPage] = useState(1); + const [perPage, setPerPage] = useState(defaultPerPage); + + // fetch the list of files on mount, and select the most recent + useEffect(() => { + const fetch = async () => { + setLoadingFiles(true); + + try { + const sorted = newestFirst(await getLogFiles()); + + setFiles(sorted); + setFile(sorted[0]?.name); + } catch (fetchError) { + setError(fetchError); + } finally { + setLoadingFiles(false); + } + }; + + fetch(); + }, []); + + // load the contents of the selected file whenever the selection changes + useEffect(() => { + if (!file) { + return; + } + + const fetch = async () => { + setLoadingLogs(true); + setError(undefined); + + try { + const records = await getLogFile({ filename: file }); + + setLogs(records); + } catch (fetchError) { + setError(fetchError); + setLogs([]); + } finally { + setLoadingLogs(false); + } + }; + + fetch(); + }, [file]); + + // apply the level filter, text filter, and sort. log files can be large, so + // memoize this to keep typing in the filter responsive + const filteredLogs = useMemo(() => { + const minimumSeverity = levels.indexOf(level); + const text = filter.trim().toLowerCase(); + + return logs + .filter((log) => levels.indexOf(log.level) >= minimumSeverity) + .filter( + (log) => + !text || + log.message?.toLowerCase().includes(text) || + log.level?.toLowerCase().includes(text), + ) + .sort((a, b) => { + // timestamps are only second precision, so fall back to position in the + // file to keep lines logged within the same second in the right order + const compareValue = + new Date(a.timestamp) - new Date(b.timestamp) || a.id - b.id; + + return sortDirection === 'ascending' ? compareValue : -compareValue; + }); + }, [filter, level, logs, sortDirection]); + + const totalPages = Math.ceil(filteredLogs.length / perPage); + + // anything that changes the shape of the result set resets pagination, so a + // user is never left looking at a page that no longer exists + const currentPage = Math.min(page, Math.max(totalPages, 1)); + + const pagedLogs = useMemo( + () => + filteredLogs.slice((currentPage - 1) * perPage, currentPage * perPage), + [currentPage, filteredLogs, perPage], + ); + + const changeFile = (value) => { + setFile(value); + setPage(1); + }; + + const changeLevel = (value) => { + setLevel(value); + setPage(1); + }; + + const changeFilter = (value) => { + setFilter(value); + setPage(1); + }; + + const changePerPage = (value) => { + setPerPage(value); + setPage(1); + }; + + const toggleSort = () => { + setSortDirection( + sortDirection === 'ascending' ? 'descending' : 'ascending', + ); + setPage(1); + }; + + const paginationChanged = ({ activePage }) => { + if (activePage >= 1) { + setPage(activePage); + } + }; + + if (loadingFiles) { + return ; + } + + const hiddenCount = logs.length - filteredLogs.length; + const firstOnPage = (currentPage - 1) * perPage + 1; + const lastOnPage = firstOnPage + pagedLogs.length - 1; + + return ( +
+ + + {error ? ( + + ) : loadingLogs ? ( + + ) : ( + <> + {totalPages > 1 && ( +
+ paginationChanged({ ...data })} + siblingRange={1} + totalPages={totalPages} + /> +
+ )} + + {filteredLogs.length > 0 && ( +
+ {`Showing ${firstOnPage}-${lastOnPage} of ${filteredLogs.length} lines` + + (hiddenCount > 0 + ? ` (${hiddenCount} of ${logs.length} hidden by filter(s))` + : '')} +
+ )} + + )} +
+ ); +}; + +export default History; diff --git a/src/web/src/components/System/Logs/Live.jsx b/src/web/src/components/System/Logs/Live.jsx index f36258ec..2c4b42db 100644 --- a/src/web/src/components/System/Logs/Live.jsx +++ b/src/web/src/components/System/Logs/Live.jsx @@ -1,24 +1,17 @@ import '../System.css'; import { createLogsHubConnection } from '../../../lib/hubFactory'; import { LoaderSegment } from '../../Shared'; +import LogTable from './LogTable'; 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', -}; - const maxLogs = 500; -class Logs extends Component { +class Live extends Component { constructor(props) { super(props); @@ -31,14 +24,16 @@ class Logs extends Component { logsHub.on('buffer', (buffer) => { this.setState({ connected: true, - logs: buffer.reverse().slice(0, maxLogs), + logs: buffer.reverse().slice(0, maxLogs).map(this.withId), }); }); logsHub.on('log', (log) => { + const record = this.withId(log); + this.setState((previousState) => ({ connected: true, - logs: [log].concat(previousState.logs).slice(0, maxLogs), + logs: [record].concat(previousState.logs).slice(0, maxLogs), })); }); @@ -49,10 +44,13 @@ class Logs extends Component { 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 - }; + // log records carry nothing unique; timestamps are second precision and the + // same line can repeat within a second. tag each record as it arrives so the + // table has a stable, unique key. never reset, so records from a replayed + // buffer can't collide with those already rendered. + nextId = 0; + + withId = (log) => ({ ...log, id: this.nextId++ }); render() { const { connected, logs } = this.state; @@ -60,39 +58,10 @@ class Logs extends Component { return (
{!connected && } - {connected && ( - - - - Timestamp - Level - Message - - - - {logs.map((log) => ( - - {this.formatTimestamp(log.timestamp)} - {levels[log.level] || log.level} - - {log.message} - - - ))} - -
- )} + {connected && }
); } } -export default Logs; +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..468187b8 --- /dev/null +++ b/src/web/src/components/System/Logs/LogTable.jsx @@ -0,0 +1,90 @@ +import '../System.css'; +import React from 'react'; +import { Icon, 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 +}; + +/** + * Renders log records. Shared by the Live and History views; both consume the + * same record shape ({ timestamp, level, message }), the former from the logs + * hub and the latter from the logs API. + * + * Passing onSortChange makes the Timestamp column sortable; omitting it (as the + * Live view does) renders a static header. + */ +const LogTable = ({ + emptyMessage = 'No logs', + logs, + onSortChange, + sortDirection, +}) => ( + + + + onSortChange() : undefined} + style={onSortChange ? { cursor: 'pointer' } : undefined} + > + Timestamp + {Boolean(onSortChange) && ( + + )} + + Level + Message + + + + {logs?.length === 0 ? ( + + + {emptyMessage} + + + ) : ( + logs.map((log) => ( + + {formatTimestamp(log.timestamp)} + {abbreviations[log.level] || log.level} + + {log.message} + + + )) + )} + +
+); + +export default LogTable; diff --git a/src/web/src/components/System/Logs/Logs.css b/src/web/src/components/System/Logs/Logs.css new file mode 100644 index 00000000..8e97e592 --- /dev/null +++ b/src/web/src/components/System/Logs/Logs.css @@ -0,0 +1,49 @@ +.logs-file-navigator { + display: flex; + align-items: center; + gap: 0.5rem; + margin-bottom: 1rem; +} + +.logs-file-navigator-dropdown { + flex: 1 1 auto; +} + +.logs-options { + margin-top: 0px !important; +} + +.logs-filter { + width: 100%; + margin-top: 1rem; +} + +.logs-options-per-page { + margin-left: 1rem !important; +} + +.logs-pagination { + margin-top: 14px; + text-align: right; +} + +.logs-count { + margin-top: 1rem; + font-size: smaller; + opacity: 0.5; +} + +@media only screen and (max-width: 684px) { + .logs-pagination .ui.pagination.menu { + font-size: smaller; + } + + .logs-options-level, .logs-options-per-page { + width: 100%; + margin-left: 0px !important; + } + + .logs-options-per-page { + margin-top: 1rem !important; + } +} diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx new file mode 100644 index 00000000..ca3938c0 --- /dev/null +++ b/src/web/src/components/System/Logs/index.jsx @@ -0,0 +1,35 @@ +import History from './History'; +import Live from './Live'; +import React from 'react'; +import { Tab } from 'semantic-ui-react'; + +const Logs = () => { + const panes = [ + { + menuItem: 'Live', + render: () => ( + + + + ), + route: 'live', + }, + { + menuItem: 'History', + render: () => ( + + + + ), + route: 'history', + }, + ]; + + return ( +
+ +
+ ); +}; + +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..8616ce8c --- /dev/null +++ b/src/web/src/lib/logs.js @@ -0,0 +1,29 @@ +import api from './api'; + +export const getLogFiles = async () => { + const response = (await api.get('/logs/files')).data; + + return response; +}; + +export const getLogFile = async ({ filename }) => { + const response = ( + await api.get(`/logs/files/${encodeURIComponent(filename)}`) + ).data; + + // log records carry nothing unique; timestamps are second precision and the + // same line can repeat within a second. tag each with its position in the + // file so the UI has a stable, unique key to render and sort with. + return response.map((record, index) => ({ ...record, id: index })); +}; + +export const downloadLogFile = async ({ filename }) => { + const response = ( + await api.get(`/logs/files/${encodeURIComponent(filename)}`, { + params: { download: true }, + responseType: 'blob', + }) + ).data; + + return response; +}; -- cgit v1.2.3 From 58a289bcdcf4d649d94ee6058c40ee7197d95209 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 25 Sep 2026 09:29:34 -0500 Subject: strip out complicated parsing --- src/slskd/Core/API/Controllers/LogsController.cs | 176 +++-------------------- 1 file changed, 21 insertions(+), 155 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 1a3e027f..6ef4a7b6 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -33,10 +33,8 @@ namespace slskd.Core.API { using System; - using System.Collections.Generic; using System.IO; - using System.Text.RegularExpressions; - using System.Threading; + using System.Linq; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -54,15 +52,13 @@ namespace slskd.Core.API [Consumes("application/json")] public class LogsController : ControllerBase { - public LogsController( - FileService fileService) + public LogsController(FileService fileService) { Files = fileService; } private FileService Files { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private Regex LogLineParseRegex { get; } = new Regex(@"^(\[?([a-zA-Z\.]*)\]?\s)?(\[((\d{4}-\d{2}-\d{2})T)?(\d{2}:\d{2}:\d{2}(?:.\d{3})?)\s([A-Z]+)\]\s)?(.*)", RegexOptions.Compiled); /// /// Gets the last few application logs. @@ -81,26 +77,29 @@ namespace slskd.Core.API /// [HttpGet("files")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task List(CancellationToken cancellationToken, [FromQuery] bool download = false) + public async Task List() { - var directory = await Files.ListDirectoryContentsAsync(System.IO.Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { - AttributesToSkip = FileAttributes.System, + IgnoreInaccessible = true, + AttributesToSkip = FileAttributes.System | FileAttributes.Hidden | FileAttributes.ReparsePoint, RecurseSubdirectories = false, }); - return Ok(directory.Files); + var logs = directory.Files.Where(f => f.Name.EndsWith(".log", StringComparison.OrdinalIgnoreCase)); + + return Ok(logs); } /// - /// Retrieves the requested log file from disk. + /// Retrieves the requested log file from disk as plain text. /// - /// - /// + /// The name of the log file. + /// A value indicating whether the file should be sent as an attachment. /// [HttpGet("files/{filename}")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public async Task Get(string filename, [FromQuery] bool download = false) + public IActionResult Get(string filename, [FromQuery] bool download = false) { if (string.IsNullOrWhiteSpace(filename)) { @@ -120,22 +119,22 @@ namespace slskd.Core.API return BadRequest("Filename contains one or more invalid characters"); } + if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) + { + return BadRequest("Only .log files may be retrieved"); + } + try { var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); + const string contentType = "text/plain; charset=utf-8"; if (download) { - return File(stream, "text/plain", filename); + return File(stream, contentType, filename); } - // future optimization: use IAsyncEnumerable to 'stream' the log records instead of beating up - // memory to build a list. save each log in memory and then emit it when the next log - // (starting with '[') is read, which indicates that it's not multi-line. in other words, a 1-log buffer - // that is flushed when the next log is read, or the file is complete - var logs = await ParseLogEntriesAsync(stream); - - return Ok(logs); + return File(stream, contentType); } catch (UnauthorizedException) { @@ -146,138 +145,5 @@ namespace slskd.Core.API return NotFound(); } } - - private async Task> ParseLogEntriesAsync(Stream stream) - { - Dictionary levels = new() - { - ["VRB"] = nameof(Serilog.Events.LogEventLevel.Verbose), - ["DBG"] = nameof(Serilog.Events.LogEventLevel.Debug), - ["INF"] = nameof(Serilog.Events.LogEventLevel.Information), - ["WRN"] = nameof(Serilog.Events.LogEventLevel.Warning), - ["ERR"] = nameof(Serilog.Events.LogEventLevel.Error), - ["FTL"] = nameof(Serilog.Events.LogEventLevel.Fatal), - }; - - var list = new List(); - - var currentLength = stream.Length; - - var reader = new StreamReader(stream); - string line; - Match match = default; - - while ((line = await reader.ReadLineAsync()) is not null) - { - if (line.Length == 0) - { - continue; - } - - if (stream.Position > currentLength) - { - // if we're reading the latest file, Serilog can append it while we're inside of this loop, - // or worse, a problem inside this loop appends lines. if this happens the position will grow - // beyond the length at the start - Log.Information("Parsing of log file {Filename} stopped before end of file; log was appended during the read"); - break; - } - - try - { - // if the line isn't a log, append it to the previous message - if (!line.StartsWith('[')) - { - var lastIndex = list.Count - 1; - - if (lastIndex >= 0) - { - var old = list[lastIndex]; - - list[lastIndex] = new LogRecord - { - Timestamp = old.Timestamp, - Level = old.Level, - Message = old.Message + '\n' + line, - }; - } - - continue; - } - - /* - there should be 3 possible line types: - - debug: - [Some.Context] [2000-1-1T11:11:11 WRN] foo bar - - info: - [2000-1-1T11:11:11 WRN] foo bar - - line wrap/newline: - foo bar - - additionally, date was added to disk log files around 9/1/26, so we need to gracefully handle - cases where the timestamp contains only hh:mm:ss, and substitute the unix epoch for the date - - the regex includes 8 matching groups (hopefully this comment and the regex don't diverge!) - using the debug log as an example, the groups are: - - 0. [Some.Context] [2026-08-29T11:11:11 WRN] foo bar - 1. [Some.Context] - 2. Some.Context - 3. [2000-01-01T11:11:11 WRN] - 4. 2000-01-01T - 5. 2000-01-01 - 6. 11:11:11 - 7. WRN - 8. foo bar - - the final group in the regex is simply `.*`, so we're guaranteed to get a match for every line - */ - match = LogLineParseRegex.Match(line); - - var grp = match.Groups; - - var date = grp[5].Success ? DateOnly.Parse(grp[5].Value) : DateOnly.FromDateTime(DateTime.UnixEpoch); - var time = grp[6].Success ? TimeOnly.Parse(grp[6].Value) : TimeOnly.FromDateTime(DateTime.UnixEpoch); - var dateTime = date.ToDateTime(time); - - var level = levels.ContainsKey(grp[7].Value) ? levels[grp[7].Value] : null; - - list.Add(new LogRecord - { - Context = grp[2].Value, - Timestamp = dateTime, - Level = level, - Message = grp[8].Value, - }); - - Log.Information("Added: {Text}", grp[8].Value); - } - catch (Exception ex) - { - Log.Debug("Error parsing log message: {Message}. Line: {Line}", ex.Message, line); - - Log.Warning("Got {GroupCount} groups", match.Groups.Count); - - foreach (var key in match.Groups.Keys) - { - Log.Warning("Key: {Key}, Success: {Success}, Value: {Value}", key, match.Groups[key].Success, match.Groups[key].Value); - } - - break; - - list.Add(new LogRecord - { - Message = line, - }); - } - } - - Log.Information("Returned {Lines}", list.Count); - - return list; - } } } -- cgit v1.2.3 From edf1ee43c596a7986700cd14db17c9b8fe7d19ca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Sep 2026 15:11:56 -0500 Subject: add logs lib --- src/web/src/lib/logs.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/web/src/lib/logs.js (limited to 'src') diff --git a/src/web/src/lib/logs.js b/src/web/src/lib/logs.js new file mode 100644 index 00000000..9b742c2d --- /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 getFile = 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; +}; -- cgit v1.2.3 From 7ce8b280b9d0f82e326ca0fe536716b657b2e68a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Sep 2026 15:12:15 -0500 Subject: make text-returning function more obvious --- src/web/src/lib/logs.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/web/src/lib/logs.js b/src/web/src/lib/logs.js index 9b742c2d..35ae5d84 100644 --- a/src/web/src/lib/logs.js +++ b/src/web/src/lib/logs.js @@ -6,7 +6,7 @@ export const list = async () => { return response; }; -export const getFile = async ({ filename }) => { +export const getFileText = async ({ filename }) => { const response = ( await api.get(`/logs/files/${encodeURIComponent(filename)}`, { responseType: 'text', -- cgit v1.2.3 From 897cf768b18ed95a394b84ad172edabf20c6a92d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Sep 2026 15:17:06 -0500 Subject: add a LogTable component for live logs --- src/web/src/components/System/Logs/LogTable.jsx | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/web/src/components/System/Logs/LogTable.jsx (limited to 'src') 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 }) => ( + + + + Timestamp + Level + Message + + + + {logs?.length === 0 ? ( + + + {emptyMessage} + + + ) : ( + logs.map((log) => ( + + {formatTimestamp(log.timestamp)} + {abbreviations[log.level] || log.level} + + {log.message} + + + )) + )} + +
+); + +export default LogTable; -- cgit v1.2.3 From 0ff0c4eb7d795ee27f97c0abf5973ba5baa31f82 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Sep 2026 16:17:45 -0500 Subject: reuse the explorer from /files --- src/web/src/components/System/Logs/Explorer.jsx | 202 ++++++++++++++++++++++++ src/web/src/components/System/Logs/Live.jsx | 59 ++----- src/web/src/components/System/Logs/index.jsx | 35 ++++ 3 files changed, 249 insertions(+), 47 deletions(-) create mode 100644 src/web/src/components/System/Logs/Explorer.jsx create mode 100644 src/web/src/components/System/Logs/index.jsx (limited to 'src') 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..ac6d982f --- /dev/null +++ b/src/web/src/components/System/Logs/Explorer.jsx @@ -0,0 +1,202 @@ +import '../Files/Files.css'; +import { getFileBlob, list } from '../../../lib/logs'; +import { downloadFile, formatBytes, formatDate } from '../../../lib/util'; +import { LoaderSegment } 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'); + + 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 }) => ( + + + + {name} + + {modifiedAt ? formatDate(modifiedAt) : ''} + {length ? formatBytes(length) : ''} + + view(name)} + style={{ cursor: 'pointer', marginRight: '0.5em' }} + title={`View ${name} in a new window`} + /> + download(name)} + style={{ cursor: 'pointer' }} + title={`Download ${name}`} + /> + + +); + +const Explorer = () => { + const [files, setFiles] = useState([]); + const [loading, setLoading] = useState(false); + const [sortColumn, setSortColumn] = useState('date'); + const [sortDirection, setSortDirection] = useState('descending'); + + const fetch = async () => { + setLoading(true); + + try { + setFiles(await list()); + } catch (error) { + toast.error(error?.message ?? error); + } 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; + }); + }; + + if (loading) { + return ; + } + + const sortedFiles = sortItems(files); + + return ( + <> +
+ + /logs +
+ + + + handleSort('name')} + style={{ cursor: 'pointer' }} + > + Name + {sortColumn === 'name' && ( + + )} + + handleSort('date')} + style={{ cursor: 'pointer' }} + > + Date Modified + {sortColumn === 'date' && ( + + )} + + + Size + + + + + + {files.length === 0 ? ( + + + No log files + + + ) : ( + sortedFiles.map((f) => ( + + )) + )} + +
+ + ); +}; + +export default Explorer; diff --git a/src/web/src/components/System/Logs/Live.jsx b/src/web/src/components/System/Logs/Live.jsx index f36258ec..2699a2e3 100644 --- a/src/web/src/components/System/Logs/Live.jsx +++ b/src/web/src/components/System/Logs/Live.jsx @@ -1,24 +1,17 @@ import '../System.css'; import { createLogsHubConnection } from '../../../lib/hubFactory'; import { LoaderSegment } from '../../Shared'; -import React, { Component } from 'react'; -import { Table } from 'semantic-ui-react'; +import LogTable from './LogTable'; +import { Component } from 'react'; const initialState = { connected: false, logs: [], }; -const levels = { - Debug: 'DBG', - Error: 'ERR', - Information: 'INF', - Warning: 'WRN', -}; - const maxLogs = 500; -class Logs extends Component { +class Live extends Component { constructor(props) { super(props); @@ -31,14 +24,16 @@ class Logs extends Component { logsHub.on('buffer', (buffer) => { this.setState({ connected: true, - logs: buffer.reverse().slice(0, maxLogs), + logs: buffer.reverse().slice(0, maxLogs).map(this.withId), }); }); logsHub.on('log', (log) => { + const record = this.withId(log); + this.setState((previousState) => ({ connected: true, - logs: [log].concat(previousState.logs).slice(0, maxLogs), + logs: [record].concat(previousState.logs).slice(0, maxLogs), })); }); @@ -49,10 +44,9 @@ class Logs extends Component { 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 - }; + nextId = 0; + + withId = (log) => ({ ...log, id: this.nextId++ }); render() { const { connected, logs } = this.state; @@ -60,39 +54,10 @@ class Logs extends Component { return (
{!connected && } - {connected && ( - - - - Timestamp - Level - Message - - - - {logs.map((log) => ( - - {this.formatTimestamp(log.timestamp)} - {levels[log.level] || log.level} - - {log.message} - - - ))} - -
- )} + {connected && }
); } } -export default Logs; +export default Live; diff --git a/src/web/src/components/System/Logs/index.jsx b/src/web/src/components/System/Logs/index.jsx new file mode 100644 index 00000000..f0fa4a58 --- /dev/null +++ b/src/web/src/components/System/Logs/index.jsx @@ -0,0 +1,35 @@ +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: () => ( + + + + ), + route: 'live', + }, + { + menuItem: 'History', + render: () => ( + + + + ), + route: 'history', + }, + ]; + + return ( +
+ +
+ ); +}; + +export default Logs; -- cgit v1.2.3 From a4b82eb80f672095d0d699c5ce3ea8352c66fd28 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 27 Sep 2026 16:25:24 -0500 Subject: remove stale files --- src/web/src/components/System/Logs/Controls.jsx | 83 -------- .../src/components/System/Logs/FileNavigator.jsx | 64 ------ src/web/src/components/System/Logs/History.jsx | 216 --------------------- src/web/src/components/System/Logs/Logs.css | 49 ----- 4 files changed, 412 deletions(-) delete mode 100644 src/web/src/components/System/Logs/Controls.jsx delete mode 100644 src/web/src/components/System/Logs/FileNavigator.jsx delete mode 100644 src/web/src/components/System/Logs/History.jsx delete mode 100644 src/web/src/components/System/Logs/Logs.css (limited to 'src') diff --git a/src/web/src/components/System/Logs/Controls.jsx b/src/web/src/components/System/Logs/Controls.jsx deleted file mode 100644 index f5d7a030..00000000 --- a/src/web/src/components/System/Logs/Controls.jsx +++ /dev/null @@ -1,83 +0,0 @@ -import './Logs.css'; -import React from 'react'; -import { Dropdown, Input, Segment } from 'semantic-ui-react'; - -/** - * Serilog's levels, ordered least to most severe. Selecting a level displays - * that level and everything below it in this list. - */ -export const levels = [ - 'Verbose', - 'Debug', - 'Information', - 'Warning', - 'Error', - 'Fatal', -]; - -const levelOptions = levels.map((level, index) => ({ - key: level, - text: index === 0 ? `${level} (all)` : `${level} and above`, - value: level, -})); - -export const perPageOptions = [50, 100, 200, 500, 1_000].map((count) => ({ - key: count, - text: `${count} per page`, - value: count, -})); - -export const defaultPerPage = 200; - -const Controls = ({ - filter, - level, - onFilterChange, - onLevelChange, - onPerPageChange, - perPage, -}) => { - return ( - - onLevelChange(value)} - options={levelOptions} - text={levelOptions.find((o) => o.value === level)?.text} - /> - onPerPageChange(value)} - options={perPageOptions} - text={perPageOptions.find((o) => o.value === perPage)?.text} - /> - onFilterChange(''), - } - } - className="logs-filter" - label={{ content: 'Filter', icon: 'filter' }} - onChange={(_event, data) => onFilterChange(data.value)} - placeholder="Show only lines matching this text" - value={filter} - /> - - ); -}; - -export default Controls; diff --git a/src/web/src/components/System/Logs/FileNavigator.jsx b/src/web/src/components/System/Logs/FileNavigator.jsx deleted file mode 100644 index 81c0e77c..00000000 --- a/src/web/src/components/System/Logs/FileNavigator.jsx +++ /dev/null @@ -1,64 +0,0 @@ -import './Logs.css'; -import { formatBytes, formatDate } from '../../../lib/util'; -import React from 'react'; -import { Button, Dropdown } from 'semantic-ui-react'; - -/** - * Sits just above the log display. The dropdown selects a file directly; the - * arrow buttons step through the newest-to-oldest sorted file list one at a - * time, left toward newer files and right toward older ones. - */ -const FileNavigator = ({ file, files, onChange }) => { - const index = files.findIndex((f) => f.name === file); - - const options = files.map((f) => ({ - description: `${formatBytes(f.length)} · ${formatDate(f.modifiedAt)}`, - key: f.name, - text: f.name, - value: f.name, - })); - - const goNewer = () => { - if (index > 0) { - onChange(files[index - 1].name); - } - }; - - const goOlder = () => { - if (index !== -1 && index < files.length - 1) { - onChange(files[index + 1].name); - } - }; - - return ( -
-
- ); -}; - -export default FileNavigator; diff --git a/src/web/src/components/System/Logs/History.jsx b/src/web/src/components/System/Logs/History.jsx deleted file mode 100644 index 1bf4976c..00000000 --- a/src/web/src/components/System/Logs/History.jsx +++ /dev/null @@ -1,216 +0,0 @@ -import './Logs.css'; -import '../System.css'; -import { getLogFile, getLogFiles } from '../../../lib/logs'; -import { ErrorSegment, LoaderSegment } from '../../Shared'; -import Controls, { defaultPerPage, levels } from './Controls'; -import FileNavigator from './FileNavigator'; -import LogTable from './LogTable'; -import React, { useEffect, useMemo, useState } from 'react'; -import { Pagination } from 'semantic-ui-react'; - -/** - * Sorts log files newest first, so that the most recent is selected by default - * and sits at the top of the file dropdown. - */ -const newestFirst = (files) => - [...files].sort((a, b) => { - const dateA = a.modifiedAt ? new Date(a.modifiedAt) : new Date(0); - const dateB = b.modifiedAt ? new Date(b.modifiedAt) : new Date(0); - - return dateB - dateA; - }); - -const History = () => { - const [files, setFiles] = useState([]); - const [file, setFile] = useState(undefined); - const [logs, setLogs] = useState([]); - const [loadingFiles, setLoadingFiles] = useState(true); - const [loadingLogs, setLoadingLogs] = useState(false); - const [error, setError] = useState(undefined); - - const [level, setLevel] = useState(levels[0]); - const [filter, setFilter] = useState(''); - const [sortDirection, setSortDirection] = useState('descending'); - const [page, setPage] = useState(1); - const [perPage, setPerPage] = useState(defaultPerPage); - - // fetch the list of files on mount, and select the most recent - useEffect(() => { - const fetch = async () => { - setLoadingFiles(true); - - try { - const sorted = newestFirst(await getLogFiles()); - - setFiles(sorted); - setFile(sorted[0]?.name); - } catch (fetchError) { - setError(fetchError); - } finally { - setLoadingFiles(false); - } - }; - - fetch(); - }, []); - - // load the contents of the selected file whenever the selection changes - useEffect(() => { - if (!file) { - return; - } - - const fetch = async () => { - setLoadingLogs(true); - setError(undefined); - - try { - const records = await getLogFile({ filename: file }); - - setLogs(records); - } catch (fetchError) { - setError(fetchError); - setLogs([]); - } finally { - setLoadingLogs(false); - } - }; - - fetch(); - }, [file]); - - // apply the level filter, text filter, and sort. log files can be large, so - // memoize this to keep typing in the filter responsive - const filteredLogs = useMemo(() => { - const minimumSeverity = levels.indexOf(level); - const text = filter.trim().toLowerCase(); - - return logs - .filter((log) => levels.indexOf(log.level) >= minimumSeverity) - .filter( - (log) => - !text || - log.message?.toLowerCase().includes(text) || - log.level?.toLowerCase().includes(text), - ) - .sort((a, b) => { - // timestamps are only second precision, so fall back to position in the - // file to keep lines logged within the same second in the right order - const compareValue = - new Date(a.timestamp) - new Date(b.timestamp) || a.id - b.id; - - return sortDirection === 'ascending' ? compareValue : -compareValue; - }); - }, [filter, level, logs, sortDirection]); - - const totalPages = Math.ceil(filteredLogs.length / perPage); - - // anything that changes the shape of the result set resets pagination, so a - // user is never left looking at a page that no longer exists - const currentPage = Math.min(page, Math.max(totalPages, 1)); - - const pagedLogs = useMemo( - () => - filteredLogs.slice((currentPage - 1) * perPage, currentPage * perPage), - [currentPage, filteredLogs, perPage], - ); - - const changeFile = (value) => { - setFile(value); - setPage(1); - }; - - const changeLevel = (value) => { - setLevel(value); - setPage(1); - }; - - const changeFilter = (value) => { - setFilter(value); - setPage(1); - }; - - const changePerPage = (value) => { - setPerPage(value); - setPage(1); - }; - - const toggleSort = () => { - setSortDirection( - sortDirection === 'ascending' ? 'descending' : 'ascending', - ); - setPage(1); - }; - - const paginationChanged = ({ activePage }) => { - if (activePage >= 1) { - setPage(activePage); - } - }; - - if (loadingFiles) { - return ; - } - - const hiddenCount = logs.length - filteredLogs.length; - const firstOnPage = (currentPage - 1) * perPage + 1; - const lastOnPage = firstOnPage + pagedLogs.length - 1; - - return ( -
- - - {error ? ( - - ) : loadingLogs ? ( - - ) : ( - <> - {totalPages > 1 && ( -
- paginationChanged({ ...data })} - siblingRange={1} - totalPages={totalPages} - /> -
- )} - - {filteredLogs.length > 0 && ( -
- {`Showing ${firstOnPage}-${lastOnPage} of ${filteredLogs.length} lines` + - (hiddenCount > 0 - ? ` (${hiddenCount} of ${logs.length} hidden by filter(s))` - : '')} -
- )} - - )} -
- ); -}; - -export default History; diff --git a/src/web/src/components/System/Logs/Logs.css b/src/web/src/components/System/Logs/Logs.css deleted file mode 100644 index 8e97e592..00000000 --- a/src/web/src/components/System/Logs/Logs.css +++ /dev/null @@ -1,49 +0,0 @@ -.logs-file-navigator { - display: flex; - align-items: center; - gap: 0.5rem; - margin-bottom: 1rem; -} - -.logs-file-navigator-dropdown { - flex: 1 1 auto; -} - -.logs-options { - margin-top: 0px !important; -} - -.logs-filter { - width: 100%; - margin-top: 1rem; -} - -.logs-options-per-page { - margin-left: 1rem !important; -} - -.logs-pagination { - margin-top: 14px; - text-align: right; -} - -.logs-count { - margin-top: 1rem; - font-size: smaller; - opacity: 0.5; -} - -@media only screen and (max-width: 684px) { - .logs-pagination .ui.pagination.menu { - font-size: smaller; - } - - .logs-options-level, .logs-options-per-page { - width: 100%; - margin-left: 0px !important; - } - - .logs-options-per-page { - margin-top: 1rem !important; - } -} -- cgit v1.2.3 From f32f73b402e9bfd5aca47cb94a245fccbd21482f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Oct 2026 18:40:32 -0500 Subject: tweak controller --- src/slskd/Core/API/Controllers/LogsController.cs | 33 ++++++++++++------------ 1 file changed, 17 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/LogsController.cs b/src/slskd/Core/API/Controllers/LogsController.cs index 6ef4a7b6..a83e608c 100644 --- a/src/slskd/Core/API/Controllers/LogsController.cs +++ b/src/slskd/Core/API/Controllers/LogsController.cs @@ -38,6 +38,7 @@ namespace slskd.Core.API using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Files; @@ -58,7 +59,7 @@ namespace slskd.Core.API } private FileService Files { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Gets the last few application logs. @@ -79,6 +80,11 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] public async Task List() { + if (!Directory.Exists(Path.GetFullPath(Program.LogDirectory))) + { + return NotFound(); + } + var directory = await Files.ListDirectoryContentsAsync(Path.GetFullPath(Program.LogDirectory), enumerationOptions: new EnumerationOptions { IgnoreInaccessible = true, @@ -95,11 +101,12 @@ namespace slskd.Core.API /// Retrieves the requested log file from disk as plain text. /// /// The name of the log file. - /// A value indicating whether the file should be sent as an attachment. /// [HttpGet("files/{filename}")] + [Produces("text/plain")] + [ProducesResponseType(typeof(string), StatusCodes.Status200OK, contentType: "text/plain")] [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)] - public IActionResult Get(string filename, [FromQuery] bool download = false) + public IActionResult Get([FromRoute] string filename) { if (string.IsNullOrWhiteSpace(filename)) { @@ -121,29 +128,23 @@ namespace slskd.Core.API if (!sanitizedFilename.EndsWith(".log", StringComparison.OrdinalIgnoreCase)) { - return BadRequest("Only .log files may be retrieved"); + return StatusCode(StatusCodes.Status403Forbidden, "Only .log files may be retrieved"); } try { var stream = Files.GetFileContents(FileSafety.CombineSafely(Program.LogDirectory, sanitizedFilename)); - const string contentType = "text/plain; charset=utf-8"; - - if (download) - { - return File(stream, contentType, filename); - } - - return File(stream, contentType); - } - catch (UnauthorizedException) - { - return Unauthorized(); + 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); + } } } } -- cgit v1.2.3 From ffd4a8c60476fe75d3c37d8323b51b4367fb7492 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Oct 2026 18:42:06 -0500 Subject: show errors, toast if popup blocked --- src/web/src/components/System/Logs/Explorer.jsx | 150 +++++++++++++----------- 1 file changed, 82 insertions(+), 68 deletions(-) (limited to 'src') diff --git a/src/web/src/components/System/Logs/Explorer.jsx b/src/web/src/components/System/Logs/Explorer.jsx index ac6d982f..b1391da2 100644 --- a/src/web/src/components/System/Logs/Explorer.jsx +++ b/src/web/src/components/System/Logs/Explorer.jsx @@ -1,7 +1,12 @@ import '../Files/Files.css'; import { getFileBlob, list } from '../../../lib/logs'; import { downloadFile, formatBytes, formatDate } from '../../../lib/util'; -import { LoaderSegment } from '../../Shared'; +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'; @@ -9,6 +14,13 @@ 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 }); @@ -60,17 +72,23 @@ const FileRow = ({ length, modifiedAt, name }) => ( const Explorer = () => { const [files, setFiles] = useState([]); - const [loading, setLoading] = useState(false); + 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 (error) { - toast.error(error?.message ?? error); + } catch (fetchError) { + if (fetchError?.response?.status === 404) { + setFiles([]); + } else { + setError(fetchError?.message ?? fetchError); + } } finally { setLoading(false); } @@ -112,10 +130,6 @@ const Explorer = () => { }); }; - if (loading) { - return ; - } - const sortedFiles = sortItems(files); return ( @@ -127,74 +141,74 @@ const Explorer = () => { /logs - + ) + } + error={error && } + loading={loading && } > - - - handleSort('name')} - style={{ cursor: 'pointer' }} - > - Name - {sortColumn === 'name' && ( - - )} - - handleSort('date')} - style={{ cursor: 'pointer' }} - > - Date Modified - {sortColumn === 'date' && ( - - )} - - - Size - - - - - - {files.length === 0 ? ( +
+ - handleSort('name')} + style={{ cursor: 'pointer' }} + > + Name + {sortColumn === 'name' && ( + + )} + + handleSort('date')} + style={{ cursor: 'pointer' }} > - No log files - + Date Modified + {sortColumn === 'date' && ( + + )} + + + Size + + - ) : ( - sortedFiles.map((f) => ( + + + {sortedFiles.map((f) => ( - )) - )} - -
+ ))} + + + ); }; -- cgit v1.2.3 From 400108c9a4a88edb6738309e0b83c9299ca36072 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Oct 2026 19:04:22 -0500 Subject: make enumeration options default as intended --- src/slskd/Files/FileService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 665fe919..584aab08 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -320,7 +320,7 @@ namespace slskd.Files /// Thrown if the specified directory has a relative path. /// Thrown if the specified directory does not exist. /// Thrown if the specified root directory is restricted. - public virtual async Task ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions) + public virtual async Task ListDirectoryContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { ArgumentException.ThrowIfNullOrWhiteSpace(directory); @@ -352,7 +352,7 @@ namespace slskd.Files try { - var contents = dir.GetFileSystemInfos("*", enumerationOptions); + var contents = dir.GetFileSystemInfos("*", enumerationOptions ?? new EnumerationOptions()); var files = contents .OfType() -- cgit v1.2.3 From c2a9302741e79165978fa91da040b6f7e689cc48 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 13:51:32 -0500 Subject: compensate for late-populated LogDirectory --- src/slskd/Files/FileService.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 584aab08..70bfc293 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -59,10 +59,11 @@ namespace slskd.Files private IEnumerable AllowedDirectories => new[] { - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Downloads), - Path.GetFullPath(OptionsMonitor.CurrentValue.Directories.Incomplete), - Path.GetFullPath(Program.LogDirectory), - }; + 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(); private IOptionsMonitor OptionsMonitor { get; } -- cgit v1.2.3 From 8e54514ba244f7acd3ad0a74dd9690421aff91b9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 14:38:17 -0500 Subject: fix bug that could throw if list changes during SelectMany --- src/slskd/Transfers/Uploads/UploadQueue.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 2dca0d9e..7491034a 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -413,9 +413,7 @@ namespace slskd.Transfers.Uploads // 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; + return uploadsForGroup.Sum(kvp => kvp.Value.Count) + 1; } private void Configure(Options options) -- cgit v1.2.3 From 9d77c403e002e46679c66586067fd040b56b420d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 14:40:26 -0500 Subject: accept cancellationtoken in AwaitStartAsync --- src/slskd/Transfers/Uploads/UploadQueue.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 7491034a..d0f2815f 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -54,8 +54,9 @@ namespace slskd.Transfers.Uploads ///
/// The username of the remote user. /// The filename for which to await the start. + /// The token to monitor for cancellation requests. /// The operation context. - Task AwaitStartAsync(string username, string filename); + Task AwaitStartAsync(string username, string filename, CancellationToken cancellationToken = default); /// /// Signals the completion of an upload. @@ -150,8 +151,9 @@ namespace slskd.Transfers.Uploads /// /// The username of the remote user. /// The filename for which to await the start. + /// The token to monitor for cancellation requests. /// The operation context. - public Task AwaitStartAsync(string username, string filename) + public Task AwaitStartAsync(string username, string filename, CancellationToken cancellationToken = default) { SyncRoot.Wait(); -- cgit v1.2.3 From 767221c5ba23d49778b5aba478ade61b264dbe31 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 14:40:41 -0500 Subject: pass cancellation token to AwaitStartAsync --- src/slskd/Transfers/Uploads/UploadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 5f98afac..7bc889ba 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -430,7 +430,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 -- cgit v1.2.3 From 4e40b1935624a1ff4d436544cc44cdf64aefbaf9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 16:16:34 -0500 Subject: add remark about position estimation --- src/slskd/Transfers/Uploads/UploadQueue.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index d0f2815f..fa3bb68c 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -306,6 +306,11 @@ namespace slskd.Transfers.Uploads /// /// Computes the estimated queue position of the specified for the specified . /// + /// + /// 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. + /// /// The username associated with the file. /// The filename of the file for which the position is to be estimated. /// The estimated queue position of the file. -- cgit v1.2.3 From efc33e19a7e33c38d59f7d3d26a0b93318af9a26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 19:34:01 -0500 Subject: synchronize EstimatePosition, reduce memory pressure --- src/slskd/Transfers/Uploads/UploadQueue.cs | 108 ++++++++++++++++------------- 1 file changed, 59 insertions(+), 49 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index fa3bb68c..441bc368 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -91,6 +91,11 @@ namespace slskd.Transfers.Uploads /// /// Computes the estimated queue position of the specified for the specified . /// + /// + /// 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. + /// /// The username associated with the file. /// The filename of the file for which the position is to be estimated. /// The estimated queue position of the file. @@ -323,11 +328,9 @@ namespace slskd.Transfers.Uploads // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user 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)) @@ -335,59 +338,66 @@ 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, 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 (= 5). assume uploads will process top down, left to right until reaching + // this one. that's 5 files from a, 2 from b, 5 from c, and the other 4 from d, putting the file over + // the carat at position 16. the actual number will vary due to many factors, including where in the + // round-robin ordering d is actually positioned (so +/- number of users downloading). + foreach (var group in uploadsForGroup.Where(group => group.Key != username)) + { + position += Math.Min(localPosition, group.Value.Count); + } + + return position; } - 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; } /// -- cgit v1.2.3 From 3b76fbbf168d2ec9798f36ac8be6beda8675e022 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 19:35:27 -0500 Subject: make it more clear that uploads are initialized with Enqueued set --- src/slskd/Transfers/Uploads/UploadQueue.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 441bc368..2494f5c1 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -272,11 +272,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(new[] { upload }), + addValue: [upload], updateValueFactory: (key, list) => { list.Add(upload); -- cgit v1.2.3 From 54b0de8d76d383dcd32cb0a485e6222fb50b783f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 21:48:59 -0500 Subject: throw if we can't find a users group --- src/slskd/Transfers/Uploads/UploadQueue.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 2494f5c1..1cefe74f 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -419,8 +419,14 @@ namespace slskd.Transfers.Uploads } // 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); + if (groupRecord is null) + { + throw new SlskdException($"Upload group {groupName} doesn't have an entry in upload dictionary. Please report this on GitHub: {Program.IssuesUrl}"); + } + // 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. if (groupRecord.Strategy == QueueStrategy.RoundRobin) -- cgit v1.2.3 From cafcd731584a69dcdddf184e1258043f34bf967c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 21:49:38 -0500 Subject: be pessimistic when estimating (assume round robin selects user last) --- src/slskd/Transfers/Uploads/UploadQueue.cs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 1cefe74f..8f083c5d 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -326,6 +326,7 @@ namespace slskd.Transfers.Uploads var groupRecord = Groups.GetValueOrDefault(groupName); // 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); SyncRoot.Wait(); @@ -368,16 +369,20 @@ namespace slskd.Transfers.Uploads // ^ // // 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). + // 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); } - return position; + // 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; } // find the upload -- cgit v1.2.3 From 2f3f183bfbabcf4f389d16763ea06a0027a38e35 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 23:48:31 -0500 Subject: switch UsedSlots to a HashSet --- src/slskd/Transfers/Types/UploadGroup.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs index fa307b53..e416dd00 100644 --- a/src/slskd/Transfers/Types/UploadGroup.cs +++ b/src/slskd/Transfers/Types/UploadGroup.cs @@ -30,15 +30,17 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // +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 SlotAvailable => 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; } } } -- cgit v1.2.3 From cfc361b1fbbbfbd4c2715d92d4a3a9d0682576a2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 23:48:55 -0500 Subject: clone UploadGroup before returning --- src/slskd/Transfers/Uploads/UploadQueue.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 8f083c5d..1c419921 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -302,7 +302,16 @@ namespace slskd.Transfers.Uploads { if (Groups.TryGetValue(groupName, out var group)) { - return group; + SyncRoot.Wait(); + + try + { + return group with { UsedSlots = [.. group.UsedSlots] }; + } + finally + { + SyncRoot.Release(); + } } throw new NotFoundException($"A group with the name {groupName} could not be found"); -- cgit v1.2.3 From 81c02f254492e7b8ec989843265883210a068481 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Oct 2026 00:01:59 -0500 Subject: disambiguate available slot bool --- src/slskd/Transfers/Types/UploadGroup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs index e416dd00..0b2b617d 100644 --- a/src/slskd/Transfers/Types/UploadGroup.cs +++ b/src/slskd/Transfers/Types/UploadGroup.cs @@ -38,7 +38,7 @@ namespace slskd.Transfers { public string Name { get; init; } public int Priority { get; set; } - public bool SlotAvailable => UsedSlots.Count < Slots; + public bool HasAvailableSlot => UsedSlots.Count < Slots; public int Slots { get; set; } public QueueStrategy Strategy { get; set; } public HashSet<(string Username, string Filename)> UsedSlots { get; set; } -- cgit v1.2.3 From eced0a86fe511e0d098b3606ecbed5b17a8c116a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Oct 2026 00:03:59 -0500 Subject: use hashset instead of int for used slots --- src/slskd/Transfers/Uploads/UploadQueue.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 1c419921..b7db1c42 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -243,8 +243,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 _)) @@ -455,8 +455,8 @@ namespace slskd.Transfers.Uploads 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(); @@ -537,7 +537,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; } @@ -571,7 +571,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; } @@ -584,7 +584,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(); @@ -592,7 +592,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; } -- cgit v1.2.3 From 8fcbce62d709c82d7bd345deb4901d3213022d4a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Oct 2026 02:46:23 -0500 Subject: got ahead of myself --- src/slskd/Transfers/Types/UploadGroup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs index 0b2b617d..e416dd00 100644 --- a/src/slskd/Transfers/Types/UploadGroup.cs +++ b/src/slskd/Transfers/Types/UploadGroup.cs @@ -38,7 +38,7 @@ namespace slskd.Transfers { public string Name { get; init; } public int Priority { get; set; } - public bool HasAvailableSlot => UsedSlots.Count < Slots; + public bool SlotAvailable => UsedSlots.Count < Slots; public int Slots { get; set; } public QueueStrategy Strategy { get; set; } public HashSet<(string Username, string Filename)> UsedSlots { get; set; } -- cgit v1.2.3 From 06939533b71112ba6a8eb3b95f6b892a5c9505a4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Oct 2026 02:55:02 -0500 Subject: get rid of GetGroupInfo, return group info in Forecast --- src/slskd/Application.cs | 7 +- src/slskd/Transfers/Uploads/UploadQueue.cs | 46 ++---- .../Transfers/Uploads/UploadQueueTests.cs | 162 +++++++++++++++++++++ 3 files changed, 174 insertions(+), 41 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 8de4fe53..f8e92bc2 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); @@ -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,7 +1970,7 @@ 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, picture: pictureBytes); diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index b7db1c42..9fc48497 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -81,13 +81,6 @@ namespace slskd.Transfers.Uploads /// The filename to enqueue. void Enqueue(string username, string filename); - /// - /// Gets information about the specified . - /// - /// The name of the group. - /// The group information. - UploadGroup GetGroupInfo(string groupName); - /// /// Computes the estimated queue position of the specified for the specified . /// @@ -110,7 +103,7 @@ namespace slskd.Transfers.Uploads /// /// The estimated queue position if the user were to enqueue a file, or zero if the transfer could start immediately. /// - int ForecastPosition(string username); + (string Group, int TotalSlots, int FreeSlots, int Position) ForecastPosition(string username); } /// @@ -293,30 +286,6 @@ namespace slskd.Transfers.Uploads } } - /// - /// Gets information about the specified . - /// - /// The name of the group. - /// The group information. - public UploadGroup GetGroupInfo(string groupName) - { - if (Groups.TryGetValue(groupName, out var group)) - { - SyncRoot.Wait(); - - try - { - return group with { UsedSlots = [.. group.UsedSlots] }; - } - finally - { - SyncRoot.Release(); - } - } - - throw new NotFoundException($"A group with the name {groupName} could not be found"); - } - /// /// Computes the estimated queue position of the specified for the specified . /// @@ -422,16 +391,19 @@ namespace slskd.Transfers.Uploads /// /// The estimated queue position if the user were to enqueue a file, or zero if the transfer could start immediately. /// - public int ForecastPosition(string username) + public (string Group, int TotalSlots, int FreeSlots, int Position) ForecastPosition(string username) { var groupName = Users.GetGroup(username); // 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 (Groups.TryGetValue(groupName, out var groupRecord) && groupRecord.HasAvailableSlot) { - return 0; + return (string.Empty, 0, 0, 0); } + var totalSlots = groupRecord.Slots; + var freeSlots = totalSlots - groupRecord.UsedSlots.Count; + // 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); @@ -445,12 +417,12 @@ namespace slskd.Transfers.Uploads // rotation (worst case), the user's start position will be equal to the number of users downloading or waiting, + 1. if (groupRecord.Strategy == QueueStrategy.RoundRobin) { - return uploadsForGroup.Count() + 1; + return (groupName, totalSlots, freeSlots, uploadsForGroup.Count() + 1); } // 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.Sum(kvp => kvp.Value.Count) + 1; + return (groupName, totalSlots, freeSlots, uploadsForGroup.Sum(kvp => kvp.Value.Count) + 1); } private void Configure(Options options) diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index 6174932d..e31d5711 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -890,6 +890,168 @@ namespace slskd.Tests.Unit.Transfers.Uploads } } + 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>(); + 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_One_If_No_Slot_Is_Available_And_Queue_Is_Empty(QueueStrategy strategy, string username) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + SetSlotAvailable(queue, false); + + Assert.Equal(1, queue.ForecastPosition(username).Position); + } + + [Theory, AutoData] + public void RoundRobin_Returns_Number_Of_Users_In_Group_Plus_One(string username, string other1, string other2) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + SetSlotAvailable(queue, false); + + var uploads = new ConcurrentDictionary>(); + 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(3, 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>(); + uploads.TryAdd(username, CreateUploads(username, count: 10)); + uploads.TryAdd(other, CreateUploads(other, count: 1)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(3, 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>(); + uploads.TryAdd(other1, CreateUploads(other1, count: 1)); + uploads.TryAdd(other2, CreateUploads(other2, count: 1)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(2, queue.ForecastPosition(username).Position); + } + + [Theory, AutoData] + public void FirstInFirstOut_Returns_Number_Of_Uploads_In_Group_Plus_One(string username, string other1, string other2) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + SetSlotAvailable(queue, false); + + var uploads = new ConcurrentDictionary>(); + 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 + 1, 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>(); + uploads.TryAdd(other, started); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(3, 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>(); + uploads.TryAdd(other1, CreateUploads(other1, count: 3)); + uploads.TryAdd(other2, CreateUploads(other2, count: 10)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(4, 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); + } + } + public class Process { [Fact] -- cgit v1.2.3 From 7425c704ef3e1f21efe41fbe5de6dc963f22c1ee Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Oct 2026 02:55:35 -0500 Subject: back to HasAvailableSlot --- src/slskd/Transfers/Types/UploadGroup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/UploadGroup.cs b/src/slskd/Transfers/Types/UploadGroup.cs index e416dd00..0b2b617d 100644 --- a/src/slskd/Transfers/Types/UploadGroup.cs +++ b/src/slskd/Transfers/Types/UploadGroup.cs @@ -38,7 +38,7 @@ namespace slskd.Transfers { public string Name { get; init; } public int Priority { get; set; } - public bool SlotAvailable => UsedSlots.Count < Slots; + public bool HasAvailableSlot => UsedSlots.Count < Slots; public int Slots { get; set; } public QueueStrategy Strategy { get; set; } public HashSet<(string Username, string Filename)> UsedSlots { get; set; } -- cgit v1.2.3 From 1ad32bdda6f0dd234b3675ae525e77200a1be29a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Oct 2026 14:38:02 -0500 Subject: run continuations async --- src/slskd/Transfers/Types/Upload.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') 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 -- cgit v1.2.3 From 05d82deee08aa1788ce1d0910648cf6f942a7ba3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Oct 2026 16:34:40 -0500 Subject: consider GlobalSlots when forecasting --- src/slskd/Transfers/Uploads/UploadQueue.cs | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 9fc48497..42d70194 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -99,6 +99,11 @@ namespace slskd.Transfers.Uploads /// Computes the estimated queue position of the specified if they were to enqueue a file, /// or zero if the transfer could start immediately. /// + /// + /// 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. + /// /// The username for which to estimate. /// /// The estimated queue position if the user were to enqueue a file, or zero if the transfer could start immediately. @@ -387,6 +392,11 @@ namespace slskd.Transfers.Uploads /// Computes the estimated queue position of the specified if they were to enqueue a file, /// or zero if the transfer could start immediately. /// + /// + /// 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. + /// /// The username for which to estimate. /// /// The estimated queue position if the user were to enqueue a file, or zero if the transfer could start immediately. @@ -395,24 +405,24 @@ namespace slskd.Transfers.Uploads { var groupName = Users.GetGroup(username); - // 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.HasAvailableSlot) + if (!Groups.TryGetValue(groupName, out var groupRecord)) { - return (string.Empty, 0, 0, 0); + throw new SlskdException($"Upload group {groupName} doesn't have an entry in upload dictionary. Please report this on GitHub: {Program.IssuesUrl}"); } - var totalSlots = groupRecord.Slots; - var freeSlots = totalSlots - groupRecord.UsedSlots.Count; + 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 (freeSlots > 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); - if (groupRecord is null) - { - throw new SlskdException($"Upload group {groupName} doesn't have an entry in upload dictionary. Please report this on GitHub: {Program.IssuesUrl}"); - } - // 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. if (groupRecord.Strategy == QueueStrategy.RoundRobin) -- cgit v1.2.3 From 67999bda3007baf735b5a14926c1b6e4c22e4a55 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 4 Oct 2026 17:45:30 -0500 Subject: fail loudly if groups desync --- src/slskd/Transfers/Uploads/UploadQueue.cs | 6 +++++- .../Transfers/Uploads/UploadQueueTests.cs | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 42d70194..ccd1f5f2 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -306,7 +306,11 @@ 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 diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index c063d82f..fbf9754f 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -714,6 +714,23 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.IsType(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>(); + uploads.TryAdd(username, CreateUploads(username, count: 1)); + + queue.SetProperty("UploadDictionary", uploads); + + var ex = Record.Exception(() => queue.EstimatePosition(username, "file0")); + + Assert.IsType(ex); + } + [Theory, AutoData] public void RoundRobin_Returns_Local_Position_If_User_Is_Alone_In_Group(string username) { -- cgit v1.2.3 From b38d9f01862b4fc27874bf99d4b24b53a6577bd0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Oct 2026 09:11:44 -0500 Subject: make forecast zero-based to match estimation (and to make it more suitable for gauging queue depth) --- src/slskd/Transfers/Uploads/UploadQueue.cs | 16 ++++++------- .../Transfers/Uploads/UploadQueueTests.cs | 26 +++++++++++++--------- 2 files changed, 23 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index ccd1f5f2..cb071d25 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -97,7 +97,7 @@ namespace slskd.Transfers.Uploads /// /// Computes the estimated queue position of the specified 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. /// /// /// The returned position is relative to the user's group only. Higher priority groups are not factored in @@ -106,7 +106,7 @@ namespace slskd.Transfers.Uploads /// /// The username for which to estimate. /// - /// 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. /// (string Group, int TotalSlots, int FreeSlots, int Position) ForecastPosition(string username); } @@ -394,7 +394,7 @@ namespace slskd.Transfers.Uploads /// /// Computes the estimated queue position of the specified 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. /// /// /// The returned position is relative to the user's group only. Higher priority groups are not factored in @@ -403,7 +403,7 @@ namespace slskd.Transfers.Uploads /// /// The username for which to estimate. /// - /// 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. /// public (string Group, int TotalSlots, int FreeSlots, int Position) ForecastPosition(string username) { @@ -428,15 +428,15 @@ namespace slskd.Transfers.Uploads 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 (groupName, totalSlots, freeSlots, 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 (groupName, totalSlots, freeSlots, uploadsForGroup.Sum(kvp => kvp.Value.Count) + 1); + // enqueued. + return (groupName, totalSlots, freeSlots, uploadsForGroup.Sum(kvp => kvp.Value.Count)); } private void Configure(Options options) diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index fbf9754f..c6fadc82 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -930,18 +930,22 @@ namespace slskd.Tests.Unit.Transfers.Uploads [Theory] [InlineAutoData(QueueStrategy.RoundRobin)] [InlineAutoData(QueueStrategy.FirstInFirstOut)] - public void Returns_One_If_No_Slot_Is_Available_And_Queue_Is_Empty(QueueStrategy strategy, string username) + 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); - Assert.Equal(1, queue.ForecastPosition(username).Position); + 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_Plus_One(string username, string other1, string other2) + public void RoundRobin_Returns_Number_Of_Users_In_Group(string username, string other1, string other2) { var (queue, _) = GetFixture(); @@ -955,7 +959,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads queue.SetProperty("UploadDictionary", uploads); // worst case; the new file is last in the rotation. file counts don't matter - Assert.Equal(3, queue.ForecastPosition(username).Position); + Assert.Equal(2, queue.ForecastPosition(username).Position); } [Theory, AutoData] @@ -972,7 +976,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads queue.SetProperty("UploadDictionary", uploads); - Assert.Equal(3, queue.ForecastPosition(username).Position); + Assert.Equal(2, queue.ForecastPosition(username).Position); } [Theory, AutoData] @@ -991,11 +995,11 @@ namespace slskd.Tests.Unit.Transfers.Uploads queue.SetProperty("UploadDictionary", uploads); - Assert.Equal(2, queue.ForecastPosition(username).Position); + Assert.Equal(1, queue.ForecastPosition(username).Position); } [Theory, AutoData] - public void FirstInFirstOut_Returns_Number_Of_Uploads_In_Group_Plus_One(string username, string other1, string other2) + public void FirstInFirstOut_Returns_Number_Of_Uploads_In_Group(string username, string other1, string other2) { var (queue, _) = GetFixture(); @@ -1010,7 +1014,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads 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 + 1, queue.ForecastPosition(username).Position); + Assert.Equal(2 + 3 + 4, queue.ForecastPosition(username).Position); } [Theory, AutoData] @@ -1029,7 +1033,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads queue.SetProperty("UploadDictionary", uploads); - Assert.Equal(3, queue.ForecastPosition(username).Position); + Assert.Equal(2, queue.ForecastPosition(username).Position); } [Theory, AutoData] @@ -1048,7 +1052,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads queue.SetProperty("UploadDictionary", uploads); - Assert.Equal(4, queue.ForecastPosition(username).Position); + Assert.Equal(3, queue.ForecastPosition(username).Position); } [Theory] @@ -1137,7 +1141,7 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(1, totalSlots); Assert.Equal(0, freeSlots); - Assert.Equal(1, position); + Assert.Equal(0, position); } [Theory, AutoData] -- cgit v1.2.3 From 85d99db5f390af5df211101fa83ce256bb16ba95 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Oct 2026 09:12:04 -0500 Subject: run continuations async --- src/slskd/Common/TokenBucket.cs | 4 ++-- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') 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 /// public class TokenBucket : ITokenBucket, IDisposable { - private TaskCompletionSource waitForReset = new(); + private TaskCompletionSource waitForReset = new(TaskCreationOptions.RunContinuationsAsynchronously); /// /// Initializes a new instance of the class. @@ -243,6 +243,6 @@ namespace slskd } private void Reset() - => Interlocked.Exchange(ref waitForReset, new TaskCompletionSource()).SetResult(true); + => Interlocked.Exchange(ref waitForReset, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).SetResult(true); } } 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(); + var enqueuedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); // satisfies condition #3; CancellationTokenSource set cancelled by the user (via API call) var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); -- cgit v1.2.3 From 11767ab706c308f4a0d24738693a0f6a68271cb1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Oct 2026 09:12:40 -0500 Subject: use slots instead of inferring from position --- src/slskd/Application.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index f8e92bc2..c34cd316 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -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); } @@ -1972,7 +1972,7 @@ namespace slskd description: Options.Soulseek.Description, uploadSlots: totalSlots, queueLength: forecastedPosition, - hasFreeUploadSlot: forecastedPosition == 0, + hasFreeUploadSlot: freeSlots > 0, picture: pictureBytes); return info; -- cgit v1.2.3 From 11d65d328fa2e27cd856f6f11d1ce4a84cc973b3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Oct 2026 09:49:19 -0500 Subject: add backstop for potential scenario where an upload is removed from the queue without its TCS being completed, causing a hang --- src/slskd/Transfers/Uploads/UploadQueue.cs | 7 +++ .../Transfers/Uploads/UploadQueueTests.cs | 54 ++++++++++++++++++++++ 2 files changed, 61 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index cb071d25..d10ce38b 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -233,6 +233,13 @@ namespace slskd.Transfers.Uploads } list.Remove(upload); + + if (!upload.TaskCompletionSource.Task.IsCompleted) + { + Log.Warning("Upload {File} for {User} was removed without being completed, so it has been cancelled. Please report this on GitHub: {IssuesUrl}", Path.GetFileName(upload.Filename), upload.Username, Program.IssuesUrl); + 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 diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index c6fadc82..f8b2f183 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -550,6 +550,60 @@ namespace slskd.Tests.Unit.Transfers.Uploads 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>("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>>("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) { -- cgit v1.2.3 From b0ca0504c8c13bbe73401ac00d16e13d5a4fda70 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 5 Oct 2026 10:07:24 -0500 Subject: make cancellation a debug message for now --- src/slskd/Transfers/Uploads/UploadQueue.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index d10ce38b..5839fa73 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -236,7 +236,7 @@ namespace slskd.Transfers.Uploads if (!upload.TaskCompletionSource.Task.IsCompleted) { - Log.Warning("Upload {File} for {User} was removed without being completed, so it has been cancelled. Please report this on GitHub: {IssuesUrl}", Path.GetFileName(upload.Filename), upload.Username, Program.IssuesUrl); + Log.Debug("Upload {File} for {User} was removed without being completed, so it has been cancelled", Path.GetFileName(upload.Filename)); upload.TaskCompletionSource.TrySetCanceled(); } -- cgit v1.2.3