aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-01-11 16:37:02 -0600
committerGitHub <noreply@github.com>2026-01-11 16:37:02 -0600
commit358a6b1912681d656ff3ff569ddc5bf1bb6a6ef7 (patch)
treeae86b9040faf8771c13b50406392dafbe50c506a /src
parent8849d78cbe7057dacad9c00c471691af8e367cd9 (diff)
parent0f2df52cbfe2b8afd517a598cbaf9fc55c36083c (diff)
downloadslskd-358a6b1912681d656ff3ff569ddc5bf1bb6a6ef7.tar.gz
Merge branch 'master' into paths
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs258
-rw-r--r--src/slskd/Common/Authentication/ApiKeyAuthentication.cs9
-rw-r--r--src/slskd/Common/Logging/Checkpointer.cs94
-rw-r--r--src/slskd/Common/Validation/IPAddressAttribute.cs32
-rw-r--r--src/slskd/Core/API/Controllers/SessionController.cs4
-rw-r--r--src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs93
-rw-r--r--src/slskd/Core/Data/Migrator.cs1
-rw-r--r--src/slskd/Core/Options.cs112
-rw-r--r--src/slskd/Core/Security/SecurityService.cs171
-rw-r--r--src/slskd/Program.cs99
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs4
-rw-r--r--src/slskd/Telemetry/Metrics.cs68
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs30
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs95
-rw-r--r--src/slskd/Transfers/TransfersDbContext.cs18
-rw-r--r--src/slskd/Transfers/Types/TransferStateCategories.cs116
-rw-r--r--src/slskd/Transfers/Types/UserUploadStatistics.cs35
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs138
-rw-r--r--src/web/package-lock.json159
-rw-r--r--src/web/src/components/System/Files/Explorer.jsx70
-rw-r--r--src/web/src/components/Transfers/TransferDetails.jsx107
-rw-r--r--src/web/src/components/Transfers/TransferList.jsx43
-rw-r--r--src/web/src/components/Transfers/Transfers.css5
23 files changed, 1467 insertions, 294 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 1a18790f..a93afafe 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -40,7 +40,6 @@ namespace slskd
using Serilog.Events;
using slskd.Configuration;
using slskd.Core.API;
- using slskd.Events;
using slskd.Files;
using slskd.Integrations.Pushbullet;
using slskd.Messaging;
@@ -83,6 +82,11 @@ namespace slskd
private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down";
+#pragma warning disable SA1306 // Field names should begin with lower-case letter
+ private static int EnqueueQueueDepth = 0;
+ private static double CurrentEnqueueLatency = 0;
+#pragma warning restore SA1306 // Field names should begin with lower-case letter
+
public Application(
OptionsAtStartup optionsAtStartup,
IOptionsMonitor<Options> optionsMonitor,
@@ -220,7 +224,9 @@ namespace slskd
private OptionsAtStartup OptionsAtStartup { get; set; }
private IOptionsMonitor<Options> OptionsMonitor { get; set; }
private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1);
- private SemaphoreSlim EnqueueRequestRateLimiter { get; } = new SemaphoreSlim(20, 20);
+ private SemaphoreSlim GlobalEnqueueSemaphore { get; } = new SemaphoreSlim(10, 10);
+ private SemaphoreSlim UserEnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(1, 1);
+ private ConcurrentDictionary<string, SemaphoreSlim> UserEnqueueSemaphores { get; } = new ConcurrentDictionary<string, SemaphoreSlim>();
private Options PreviousOptions { get; set; }
private IPushbulletService Pushbullet { get; }
private DateTime SharesRefreshStarted { get; set; }
@@ -312,7 +318,7 @@ namespace slskd
// records to be updated if the application has started to shut down so that we can do this cleanup and properly
// disposition them as having failed due to an application shutdown, instead of some random exception thrown while
// things are being disposed.
- var activeUploads = Transfers.Uploads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true);
+ var activeUploads = Transfers.Uploads.List(t => t.EndedAt == null || !TransferStateCategories.Completed.Contains(t.State), includeRemoved: true);
foreach (var upload in activeUploads)
{
@@ -323,7 +329,7 @@ namespace slskd
Transfers.Uploads.Update(upload);
}
- var activeDownloads = Transfers.Downloads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true);
+ var activeDownloads = Transfers.Downloads.List(t => t.EndedAt == null || !TransferStateCategories.Completed.Contains(t.State), includeRemoved: true);
foreach (var download in activeDownloads)
{
@@ -534,24 +540,85 @@ namespace slskd
}
}
- // todo: consider moving this somewhere else; it's pretty long and complicated
private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename)
{
+ Metrics.Enqueue.RequestsReceived.Inc(1);
+
+ /*
+ circuit breaker/failsafe:
+
+ if it would take longer than three minutes to process this request based on the number of waiting requests
+ and the average processing latency, reject the request automatically to alleviate pressure on the system.
+
+ the requesting client will almost certainly consider any file for which it hasn't gotten confirmation
+ in over a minute to be failed, over 3 minutes is a safety buffer.
+ */
+ if (EnqueueQueueDepth * CurrentEnqueueLatency > 180_000)
+ {
+ Metrics.Enqueue.RequestsDropped.Inc(1);
+ throw new DownloadEnqueueException("Overwhelmed with requests; try again later.");
+ }
+
var stopwatch = new Stopwatch();
var decisionStopwatch = new Stopwatch();
- await EnqueueRequestRateLimiter.WaitAsync();
+ SemaphoreSlim userSemaphore = null;
+ Task userSemaphoreWaitTask;
+ bool userSemaphoreAcquired = false;
+
+ bool enqueueRequestsSemaphoreAcquired = false;
try
{
- stopwatch.Start();
-
if (Users.IsBlacklisted(username, endpoint.Address))
{
Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address);
throw new DownloadEnqueueException("File not shared.");
}
+ /*
+ for limits to work properly (and to help alleviate strain from the db, make incoming requests 'fair' among competing users),
+ we need to ensure that we process only one request per user at a time.
+
+ it's important that we obtain the user semaphore FIRST (before the global semaphore) to prevent one user
+ from monopolizing the request queue; users must 'go to the back of the line' for each request
+
+ hopefully this process takes < 10ms on most systems, but on low-spec systems with high traffic, this
+ round-robin approach helps guarantee the best QoS for peers
+ */
+ Interlocked.Increment(ref EnqueueQueueDepth); // any request waiting on any semaphore counts
+
+ try
+ {
+ // obtain exclusive access over the user dictionary. if this blocks it'll only be for a few ns
+ // we should also only be holding it for a few ns per request
+ await UserEnqueueSemaphoreSyncRoot.WaitAsync();
+
+ try
+ {
+ // get the user's semaphore and START waiting; if we wait we'll tie up the sync root
+ userSemaphore = UserEnqueueSemaphores.GetOrAdd(username, new SemaphoreSlim(initialCount: 1, maxCount: 1));
+ userSemaphoreWaitTask = userSemaphore.WaitAsync();
+ }
+ finally
+ {
+ UserEnqueueSemaphoreSyncRoot.Release();
+ }
+
+ await userSemaphoreWaitTask;
+ userSemaphoreAcquired = true;
+
+ await GlobalEnqueueSemaphore.WaitAsync();
+ enqueueRequestsSemaphoreAcquired = true;
+ }
+ finally
+ {
+ Interlocked.Decrement(ref EnqueueQueueDepth);
+ Metrics.Enqueue.CurrentQueueDepth.Set(EnqueueQueueDepth);
+ }
+
+ stopwatch.Start();
+
// in order to properly determine if the requested file would exceed any limits, we need to know the size of the file
// it helps, too, that this will tell us whether the file is even shared.
(string Host, string Filename, long Size) resolved;
@@ -611,45 +678,48 @@ namespace slskd
* 3) that did not end due to an error (state includes errored, exception column is set)
*/
(bool Files, bool Megabytes) OverLimits(
- (int Files, long Bytes) stats,
+ int files,
+ long bytes,
Options.LimitsOptions.Limits options,
Options.LimitsOptions.Limits defaults,
long size)
{
- var files = false;
- var megabytes = false;
+ var filesOver = false;
+ var megabytesOver = false;
var byteLimitInMegabytes = options?.Megabytes ?? defaults?.Megabytes;
- if (byteLimitInMegabytes is not null && (stats.Bytes + size) > (byteLimitInMegabytes * 1000L * 1000L))
+ if (byteLimitInMegabytes is not null && (bytes + size) > (byteLimitInMegabytes * 1000L * 1000L))
{
- Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimitInMegabytes * 1000L * 1000L);
- megabytes = true;
+ Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", bytes + size, byteLimitInMegabytes * 1000L * 1000L);
+ megabytesOver = true;
}
var fileLimit = options?.Files ?? defaults?.Files;
- if (fileLimit is not null && (stats.Files + 1) > fileLimit)
+ if (fileLimit is not null && (files + 1) > fileLimit)
{
- Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, fileLimit);
- files = true;
+ Log.Debug("Projected file count {Files} exceeds limit {Limit}", files + 1, fileLimit);
+ filesOver = true;
}
- return (files, megabytes);
+ return (filesOver, megabytesOver);
}
decisionStopwatch.Start();
+ var stats = Transfers.Uploads.GetUserStatistics(username, DateTime.UtcNow);
+
// start with the queue, since that should contain the fewest files and should be the least expensive to check
// "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set
// for terminal transfers.
if (!IsNull(limits?.Queued, global?.Queued))
{
- var queued = Transfers.Uploads.Summarize(
- expression: t => t.Username == username && t.EndedAt == null);
-
- Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, decisionStopwatch.ElapsedMilliseconds);
-
- var over = OverLimits(queued, limits?.Queued, global?.Queued, resolved.Size);
+ var over = OverLimits(
+ files: stats.QueuedFiles,
+ bytes: stats.QueuedBytes,
+ options: limits?.Queued,
+ defaults: global?.Queued,
+ size: resolved.Size);
if (over.Files || over.Megabytes)
{
@@ -668,35 +738,20 @@ namespace slskd
// * that were not errored
if (!IsNull(limits?.Weekly, global?.Weekly))
{
- var erroredState = TransferStates.Completed | TransferStates.Errored;
- var cutoffDateTime = DateTime.UtcNow.AddDays(-7);
-
- var failures = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && (t.State.HasFlag(erroredState) || t.Exception != null));
-
- Log.Debug("Fetched weekly failures: {Failures} ({Time}ms)", failures.Files, decisionStopwatch.ElapsedMilliseconds);
-
var failureLimit = limits?.Weekly?.Failures ?? global?.Weekly?.Failures;
- if (failureLimit is not null && failures.Files >= failureLimit)
+ if (failureLimit is not null && stats.WeeklyFailedFiles >= failureLimit)
{
Log.Information("Rejected enqueue request for user {Username}: Weekly failure limit met or exceeded", username);
throw new DownloadEnqueueException("Too many failed transfers this week");
}
- var weekly = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && !t.State.HasFlag(erroredState)
- && t.Exception == null);
-
- Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, decisionStopwatch.ElapsedMilliseconds);
-
- var over = OverLimits(weekly, limits?.Weekly, global?.Weekly, resolved.Size);
+ var over = OverLimits(
+ files: stats.WeeklySucceededFiles,
+ bytes: stats.WeeklySucceededBytes,
+ options: limits?.Weekly,
+ defaults: global?.Weekly,
+ size: resolved.Size);
if (over.Files || over.Megabytes)
{
@@ -709,35 +764,20 @@ namespace slskd
// of the previous 7.
if (!IsNull(limits?.Daily, global?.Daily))
{
- var erroredState = TransferStates.Completed | TransferStates.Errored;
- var cutoffDateTime = DateTime.UtcNow.AddDays(-1);
-
- var failures = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && (t.State.HasFlag(erroredState) || t.Exception != null));
-
- Log.Debug("Fetched daily failures: {Failures} ({Time}ms)", failures.Files, decisionStopwatch.ElapsedMilliseconds);
-
var failureLimit = limits?.Daily?.Failures ?? global?.Daily?.Failures;
- if (failureLimit is not null && failures.Files >= failureLimit)
+ if (failureLimit is not null && stats.DailyFailedFiles >= failureLimit)
{
Log.Information("Rejected enqueue request for user {Username}: Daily failure limit met or exceeded", username);
throw new DownloadEnqueueException("Too many failed transfers today");
}
- var daily = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && !t.State.HasFlag(erroredState)
- && t.Exception == null);
-
- Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, decisionStopwatch.ElapsedMilliseconds);
-
- var over = OverLimits(daily, limits?.Daily, global?.Daily, resolved.Size);
+ var over = OverLimits(
+ files: stats.DailySucceededFiles,
+ bytes: stats.DailySucceededBytes,
+ options: limits?.Daily,
+ defaults: global?.Daily,
+ size: resolved.Size);
if (over.Files || over.Megabytes)
{
@@ -746,16 +786,47 @@ namespace slskd
}
}
+ decisionStopwatch.Stop();
+
await Transfers.Uploads.EnqueueAsync(username, filename);
+
+ stopwatch.Stop();
+
+ // we only report metrics for successes so that each value is guaranteed to include the enqueue latency
+ Metrics.Enqueue.RequestsAccepted.Inc(1);
+ Metrics.Enqueue.Latency.Observe(stopwatch.ElapsedMilliseconds);
+ Metrics.Enqueue.CurrentLatency.Update(stopwatch.ElapsedMilliseconds);
+
+ Interlocked.Exchange(ref CurrentEnqueueLatency, Metrics.Enqueue.CurrentLatency.Value);
+
+ Log.Information("Enqueue of {Filename} to {Username} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", filename, username, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds);
+ }
+ catch (DownloadEnqueueException)
+ {
+ Metrics.Enqueue.RequestsRejected.Inc(1);
+ throw;
}
finally
{
- decisionStopwatch.Stop();
- stopwatch.Stop();
+ if (decisionStopwatch.IsRunning)
+ {
+ decisionStopwatch.Stop();
+ }
- EnqueueRequestRateLimiter.Release();
+ // decision latency is reported here so that we can track both successes and failures; they do the same
+ // work so lumping them together gives us the clearest picture
+ Metrics.Enqueue.DecisionLatency.Observe(decisionStopwatch.ElapsedMilliseconds);
+ Metrics.Enqueue.CurrentDecisionLatency.Update(decisionStopwatch.ElapsedMilliseconds);
- Log.Debug("EnqueueDownload for {Username}/{Filename} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", username, filename, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds);
+ if (userSemaphoreAcquired)
+ {
+ userSemaphore.Release();
+ }
+
+ if (enqueueRequestsSemaphoreAcquired)
+ {
+ GlobalEnqueueSemaphore.Release();
+ }
}
}
@@ -1040,6 +1111,9 @@ namespace slskd
{
Metrics.DistributedNetwork.BroadcastLatency.Observe(Client.DistributedNetwork.AverageBroadcastLatency ?? 0);
Metrics.DistributedNetwork.CurrentBroadcastLatency.Set(Client.DistributedNetwork.AverageBroadcastLatency ?? 0);
+
+ _ = Task.Run(() => CleanupUserEnqueueSemaphoresAsync())
+ .ContinueWith(task => Log.Error(task.Exception, "Failed to clean up user enqueue semaphore(s): {Message}", task.Exception?.Message), TaskContinuationOptions.OnlyOnFaulted);
}
private void Clock_EveryFiveMinutes(object sender, ClockEventArgs e)
@@ -1152,19 +1226,19 @@ namespace slskd
{
var options = OptionsMonitor.CurrentValue.Retention;
- void PruneUpload(int? age, TransferStates state)
+ void PruneUpload(int? age, params TransferStates[] states)
{
if (age.HasValue)
{
- Transfers.Uploads.Prune(age.Value, TransferStates.Completed | state);
+ Transfers.Uploads.Prune(age.Value, [.. states.Select(s => TransferStates.Completed | s)]);
}
}
- void PruneDownload(int? age, TransferStates state)
+ void PruneDownload(int? age, params TransferStates[] states)
{
if (age.HasValue)
{
- Transfers.Downloads.Prune(age.Value, TransferStates.Completed | state);
+ Transfers.Downloads.Prune(age.Value, [.. states.Select(s => TransferStates.Completed | s)]);
}
}
@@ -1172,11 +1246,13 @@ namespace slskd
{
PruneUpload(options.Transfers.Upload.Succeeded, TransferStates.Succeeded);
PruneUpload(options.Transfers.Upload.Cancelled, TransferStates.Cancelled);
- PruneUpload(options.Transfers.Upload.Errored, TransferStates.Errored);
+ PruneUpload(options.Transfers.Upload.Errored, TransferStates.Errored, TransferStates.Aborted, TransferStates.Rejected, TransferStates.TimedOut);
+ PruneUpload(options.Transfers.Upload.Failed, [.. TransferStateCategories.Failed]);
PruneDownload(options.Transfers.Download.Succeeded, TransferStates.Succeeded);
PruneDownload(options.Transfers.Download.Cancelled, TransferStates.Cancelled);
- PruneDownload(options.Transfers.Download.Errored, TransferStates.Errored);
+ PruneDownload(options.Transfers.Download.Errored, TransferStates.Errored, TransferStates.Aborted, TransferStates.TimedOut);
+ PruneDownload(options.Transfers.Download.Failed, [.. TransferStateCategories.Failed]);
}
catch
{
@@ -1750,5 +1826,31 @@ namespace slskd
throw;
}
}
+
+ private async Task CleanupUserEnqueueSemaphoresAsync()
+ {
+ // don't wait if we can't get exclusive access immediately; we'll get it eventually
+ if (await UserEnqueueSemaphoreSyncRoot.WaitAsync(0).ConfigureAwait(false))
+ {
+ try
+ {
+ foreach (var kvp in UserEnqueueSemaphores)
+ {
+ // if we're able to obtain the semaphore immediately, there's nothing waiting on it
+ // and we're safe to dispose of it. the sync root saves us from concurrency issues here
+ if (await kvp.Value.WaitAsync(0).ConfigureAwait(false))
+ {
+ UserEnqueueSemaphores.TryRemove(kvp.Key, out var removed);
+ removed.Dispose();
+ Log.Debug($"Cleaned up enqueue semaphore for user {kvp.Key}");
+ }
+ }
+ }
+ finally
+ {
+ UserEnqueueSemaphoreSyncRoot.Release();
+ }
+ }
+ }
}
} \ No newline at end of file
diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
index 1aaa4a4f..e2733442 100644
--- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
+++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs
@@ -15,6 +15,7 @@
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
+using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace slskd.Authentication
@@ -24,7 +25,7 @@ namespace slskd.Authentication
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
- using Microsoft.Extensions.Logging;
+ using Serilog;
/// <summary>
/// API key authentication.
@@ -51,7 +52,7 @@ namespace slskd.Authentication
/// <param name="urlEncoder">A url encoder.</param>
public ApiKeyAuthenticationHandler(
IOptionsMonitor<ApiKeyAuthenticationOptions> apiKeyOptionsMonitor,
- ISecurityService securityService,
+ SecurityService securityService,
ILoggerFactory logger,
UrlEncoder urlEncoder)
: base(apiKeyOptionsMonitor, logger, urlEncoder)
@@ -59,7 +60,8 @@ namespace slskd.Authentication
Security = securityService;
}
- private ISecurityService Security { get; }
+ private ILogger Log { get; } = Serilog.Log.ForContext<ApiKeyAuthenticationHandler>();
+ private SecurityService Security { get; }
/// <summary>
/// Authenticates via API key.
@@ -86,6 +88,7 @@ namespace slskd.Authentication
}
catch (Exception ex)
{
+ Log.Warning("Unauthorized request from IP address {IP}: {Message}", Request.HttpContext.Connection.RemoteIpAddress, ex.Message);
return AuthenticateResult.Fail(ex);
}
}
diff --git a/src/slskd/Common/Logging/Checkpointer.cs b/src/slskd/Common/Logging/Checkpointer.cs
new file mode 100644
index 00000000..08a6f2d9
--- /dev/null
+++ b/src/slskd/Common/Logging/Checkpointer.cs
@@ -0,0 +1,94 @@
+// <copyright file="Checkpointer.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd;
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using Serilog;
+
+public static class CheckpointerExtensions
+{
+ public static Checkpointer Checkpointer(this ILogger logger, string context = null, [CallerMemberName] string memberName = "")
+ {
+ return new Checkpointer(context, memberName, logger);
+ }
+}
+
+public sealed class Checkpointer : IDisposable
+{
+ public Checkpointer(
+ string context = null,
+ [CallerMemberName] string memberName = "",
+ ILogger logger = null)
+ {
+ Stopwatch = Stopwatch.StartNew();
+ Context = $"{context ?? memberName}";
+ Logger = logger ?? Log.ForContext<Checkpointer>().ForContext("CheckpointerContext", Context);
+ Checkpoints = new List<(string, long)>();
+ LastCheckpointMs = 0;
+
+ Logger.Debug("[{Context}] Started", Context);
+ }
+
+ private Stopwatch Stopwatch { get; }
+ private string Context { get; }
+ private ILogger Logger { get; }
+ private List<(string Name, long ElapsedMs)> Checkpoints { get; }
+ private long LastCheckpointMs { get; set; }
+
+ public void Capture(
+ string name,
+ [CallerLineNumber] int lineNumber = 0)
+ {
+ var currentMs = Stopwatch.ElapsedMilliseconds;
+ var deltaMs = currentMs - LastCheckpointMs;
+
+ Checkpoints.Add((name, currentMs));
+
+ Logger.Warning(
+ "📌[{Context}] [+{Delta}ms] {Checkpoint} ({Total}ms)",
+ Context,
+ currentMs.ToString().PadLeft(5),
+ name,
+ deltaMs);
+
+ LastCheckpointMs = currentMs;
+ }
+
+ public void Summary()
+ {
+ Stopwatch.Stop();
+ var totalMs = Stopwatch.ElapsedMilliseconds;
+
+ Logger.Information(
+ "[{Context}] Completed in {Total}ms with {Count} checkpoints",
+ Context,
+ totalMs,
+ Checkpoints.Count);
+ }
+
+ public void Dispose()
+ {
+ if (Stopwatch.IsRunning)
+ {
+ Summary();
+ }
+ }
+} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/IPAddressAttribute.cs b/src/slskd/Common/Validation/IPAddressAttribute.cs
index 6e53df57..b9075808 100644
--- a/src/slskd/Common/Validation/IPAddressAttribute.cs
+++ b/src/slskd/Common/Validation/IPAddressAttribute.cs
@@ -18,6 +18,7 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
+ using System.Linq;
using System.Net;
/// <summary>
@@ -25,6 +26,13 @@ namespace slskd.Validation
/// </summary>
public class IPAddressAttribute : ValidationAttribute
{
+ public IPAddressAttribute(bool allowCommaSeparatedValues = false)
+ {
+ AllowCommaSeparatedValues = allowCommaSeparatedValues;
+ }
+
+ private bool AllowCommaSeparatedValues { get; set; }
+
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
@@ -36,9 +44,29 @@ namespace slskd.Validation
return fail;
}
- if (!IPAddress.TryParse(valueAsString, out _))
+ if (!valueAsString.Contains(','))
{
- return fail;
+ if (!IPAddress.TryParse(valueAsString, out _))
+ {
+ return fail;
+ }
+ }
+ else
+ {
+ if (!AllowCommaSeparatedValues)
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field accepts a single value only (a comma separated list was specified)");
+ }
+
+ var values = valueAsString.Split(',').Select(v => v.Trim());
+
+ foreach (var currentValue in values)
+ {
+ if (!IPAddress.TryParse(currentValue, out _))
+ {
+ return new ValidationResult($"The {validationContext.DisplayName} field contains one or more invalid IPv4 or IPv6 IP addresses.");
+ }
+ }
}
}
diff --git a/src/slskd/Core/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs
index 861fd468..cfcb3f23 100644
--- a/src/slskd/Core/API/Controllers/SessionController.cs
+++ b/src/slskd/Core/API/Controllers/SessionController.cs
@@ -36,7 +36,7 @@ namespace slskd.Core.API
public class SessionController : ControllerBase
{
public SessionController(
- ISecurityService securityService,
+ SecurityService securityService,
IOptionsSnapshot<Options> optionsSnapshot,
OptionsAtStartup optionsAtStartup)
{
@@ -47,7 +47,7 @@ namespace slskd.Core.API
private IOptionsSnapshot<Options> OptionsSnapshot { get; set; }
private OptionsAtStartup OptionsAtStartup { get; set; }
- private ISecurityService Security { get; }
+ private SecurityService Security { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<SessionController>();
/// <summary>
diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs
new file mode 100644
index 00000000..2deffeb3
--- /dev/null
+++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs
@@ -0,0 +1,93 @@
+// <copyright file="Z12282025_AdditionalTransferIndexesMigration.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Migrations;
+
+using System;
+using System.Linq;
+using Microsoft.Data.Sqlite;
+using Serilog;
+
+/// <summary>
+/// Adds additional indexes to the Transfers table for Removed, Username/Filename, and user upload statistics.
+/// </summary>
+public class Z12282025_AdditionalTransferIndexesMigration : IMigration
+{
+ public Z12282025_AdditionalTransferIndexesMigration(ConnectionStringDictionary connectionStrings)
+ {
+ ConnectionString = connectionStrings[Database.Transfers];
+ }
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<Z12282025_AdditionalTransferIndexesMigration>();
+ private string ConnectionString { get; }
+
+ public bool NeedsToBeApplied()
+ {
+ // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply
+ var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString);
+ var txfers = idxes["Transfers"];
+
+ var removedExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Removed", StringComparison.OrdinalIgnoreCase));
+ var usernameFilenameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_UsernameFilename", StringComparison.OrdinalIgnoreCase));
+ var statsExist = txfers.Any(c => c.Name.Equals("IDX_Transfers_UserUploadStatistics", StringComparison.OrdinalIgnoreCase));
+
+ if (removedExists && usernameFilenameExists && statsExist)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ public void Apply()
+ {
+ if (!NeedsToBeApplied())
+ {
+ Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z12282025_AdditionalTransferIndexesMigration));
+ return;
+ }
+
+ using var connection = new SqliteConnection(ConnectionString);
+ connection.Open();
+
+ using var transaction = connection.BeginTransaction();
+
+ try
+ {
+ void Exec(string sql)
+ {
+ using var command = new SqliteCommand(sql, connection, transaction);
+ command.ExecuteNonQuery();
+ }
+
+ Log.Information("> Adding missing index(es) on the Transfers table...");
+
+ Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed)");
+ Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UsernameFilename ON Transfers (Username, Filename)");
+ Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size)");
+
+ Log.Information("> Index(es) created");
+ transaction.Commit();
+ Log.Information("> Done!");
+ }
+ catch (Exception)
+ {
+ transaction.Rollback();
+ throw;
+ }
+ }
+}
diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs
index b8a7ce10..5561de4b 100644
--- a/src/slskd/Core/Data/Migrator.cs
+++ b/src/slskd/Core/Data/Migrator.cs
@@ -43,6 +43,7 @@ public class Migrator
{ nameof(Z04012025_TransferStateMigration), new Z04012025_TransferStateMigration(connectionStrings: Databases) },
{ nameof(Z07062025_TransferIndexesMigration), new Z07062025_TransferIndexesMigration(connectionStrings: Databases) },
{ nameof(Z07262025_PrivateMessageWasReplayedMigration), new Z07262025_PrivateMessageWasReplayedMigration(connectionStrings: Databases) },
+ { nameof(Z12282025_AdditionalTransferIndexesMigration), new Z12282025_AdditionalTransferIndexesMigration(connectionStrings: Databases) },
};
}
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 76dcd45c..a1d9953c 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -115,7 +115,7 @@ namespace slskd
/// <summary>
/// Gets a value indicating whether to display a list of configuration environment variables.
/// </summary>
- [Argument('e', "envars")]
+ [Argument(default, "envars")]
[Description("display environment variables")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
@@ -125,7 +125,7 @@ namespace slskd
/// <summary>
/// Gets a value indicating whether to generate an X509 certificate and password.
/// </summary>
- [Argument('g', "generate-cert")]
+ [Argument(default, "generate-cert")]
[Description("generate X509 certificate and password for HTTPS")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
@@ -135,7 +135,7 @@ namespace slskd
/// <summary>
/// Gets a value indicating whether to generate a random secret.
/// </summary>
- [Argument('k', "generate-secret")]
+ [Argument(default, "generate-secret")]
[Description("generate random secret of the specified length")]
[Obsolete("Used only for documentation; see Program for actual implementation")]
[JsonIgnore]
@@ -1423,6 +1423,12 @@ namespace slskd
/// </summary>
[Range(5, maximum: int.MaxValue)]
public int? Cancelled { get; init; } = null;
+
+ /// <summary>
+ /// Gets the time to retain unsuccessful (including errored and cancelled) transfers, in minutes.
+ /// </summary>
+ [Range(5, maximum: int.MaxValue)]
+ public int? Failed { get; init; } = null;
}
}
@@ -1839,6 +1845,16 @@ namespace slskd
public int Port { get; init; } = 5030;
/// <summary>
+ /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTP requests.
+ /// </summary>
+ [Argument(default, "http-ip-address")]
+ [EnvironmentVariable("HTTP_IP_ADDRESS")]
+ [Description("IP addresses on which to listen for HTTP requests")]
+ [IPAddress(allowCommaSeparatedValues: true)]
+ [RequiresRestart]
+ public string IpAddress { get; init; }
+
+ /// <summary>
/// Gets the HTTP listen unix domain socket (UDS) path.
/// </summary>
[Argument(default, "http-socket")]
@@ -1893,7 +1909,7 @@ namespace slskd
/// <summary>
/// Authentication options.
/// </summary>
- public class WebAuthenticationOptions
+ public class WebAuthenticationOptions : IValidatableObject
{
/// <summary>
/// Gets a value indicating whether authentication should be disabled.
@@ -1931,11 +1947,89 @@ namespace slskd
public JwtOptions Jwt { get; init; } = new JwtOptions();
/// <summary>
+ /// Gets the primary API key. Defaults to 'Administrator' role and CIDR '0.0.0.0/0,::/0'.
+ /// role and CIDR can be supplied by prefixing the key with 'role=[role];cidr=[cidrs];[key]'.
+ /// </summary>
+ [Argument('k', "api-key")]
+ [EnvironmentVariable("API_KEY")]
+ [Description("primary API key value")]
+ [Secret]
+ [RequiresRestart]
+ public string ApiKey { get; init; }
+
+ /// <summary>
/// Gets API keys.
/// </summary>
[Validate]
public Dictionary<string, ApiKeyOptions> ApiKeys { get; init; } = new Dictionary<string, ApiKeyOptions>();
+ public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
+ {
+ var results = new List<ValidationResult>();
+
+ if (string.IsNullOrWhiteSpace(ApiKey))
+ {
+ return results;
+ }
+
+ var tuples = ApiKey.Split(';');
+
+ // if only one tuple is supplied, it's just the key, no role or list of CIDRs
+ if (tuples.Length == 1)
+ {
+ var key = tuples.FirstOrDefault();
+
+ if (key?.Length < 16 || key?.Length > 255)
+ {
+ results.Add(new ValidationResult("API key must be between 16 and 255 characters"));
+ }
+
+ return results;
+ }
+
+ /*
+ if multiple tuples are supplied, verify that:
+
+ * if a tuple starts with 'role=', it's defining a role and it must match one of the Role enum values
+ * if a tuple starts with 'cidr=', it's defining a list of CIDRs which need to be valid
+ * if a tuple doesn't start with a prefix, it's the API key itself and it must be between 16 and 255 characters
+ */
+ foreach (var tuple in tuples)
+ {
+ if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase))
+ {
+ var role = tuple.Split('=').LastOrDefault();
+
+ if (!Enum.TryParse(typeof(Role), value: role, ignoreCase: true, out _))
+ {
+ results.Add(new ValidationResult($"API key role must be one of: {string.Join(", ", Enum.GetNames(typeof(Role)))}"));
+ }
+ }
+ else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase))
+ {
+ var cidrs = tuple.Split('=').LastOrDefault();
+
+ foreach (var cidr in cidrs.Split(','))
+ {
+ try
+ {
+ _ = IPAddressRange.Parse(cidr);
+ }
+ catch (Exception ex)
+ {
+ results.Add(new ValidationResult($"API key CIDR {cidr} is invalid: {ex.Message}"));
+ }
+ }
+ }
+ else if (tuple?.Length < 16 || tuple?.Length > 255)
+ {
+ results.Add(new ValidationResult("API key must be between 16 and 255 characters"));
+ }
+ }
+
+ return results;
+ }
+
/// <summary>
/// JWT options.
/// </summary>
@@ -2040,6 +2134,16 @@ namespace slskd
public int Port { get; init; } = 5031;
/// <summary>
+ /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTPS requests.
+ /// </summary>
+ [Argument(default, "https-ip-address")]
+ [EnvironmentVariable("HTTPS_IP_ADDRESS")]
+ [Description("IP addresses on which to listen for HTTPS requests")]
+ [IPAddress(allowCommaSeparatedValues: true)]
+ [RequiresRestart]
+ public string IpAddress { get; init; }
+
+ /// <summary>
/// Gets a value indicating whether HTTP requests should be redirected to HTTPS.
/// </summary>
[Argument('f', "force-https")]
diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs
index 6da88571..254b3081 100644
--- a/src/slskd/Core/Security/SecurityService.cs
+++ b/src/slskd/Core/Security/SecurityService.cs
@@ -17,84 +17,133 @@
using Microsoft.Extensions.Options;
-namespace slskd
+namespace slskd;
+
+using System;
+using System.Collections.Generic;
+using System.IdentityModel.Tokens.Jwt;
+using System.Linq;
+using System.Net;
+using System.Security.Claims;
+using Microsoft.IdentityModel.Tokens;
+using NetTools;
+using slskd.Authentication;
+
+public class SecurityService
{
- using System;
- using System.Collections.Generic;
- using System.IdentityModel.Tokens.Jwt;
- using System.Linq;
- using System.Net;
- using System.Security.Claims;
- using Microsoft.IdentityModel.Tokens;
- using NetTools;
- using slskd.Authentication;
-
- public interface ISecurityService
+ public SecurityService(
+ SymmetricSecurityKey jwtSigningKey,
+ OptionsAtStartup optionsAtStartup,
+ IOptionsMonitor<Options> optionsMonitor)
{
- JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null);
- (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress);
- }
+ JwtSigningKey = jwtSigningKey;
+ OptionsAtStartup = optionsAtStartup;
+ OptionsMonitor = optionsMonitor;
- public class SecurityService : ISecurityService
- {
- public SecurityService(
- SymmetricSecurityKey jwtSigningKey,
- OptionsAtStartup optionsAtStartup,
- IOptionsMonitor<Options> optionsMonitor)
+ // parse the configured string into an instance of ApiKeyOptions and assign it to
+ // PrimaryApiKey, if a string is provided.
+ // this is kind of expensive in terms of allocations, so do it once at instantiation
+ // and mark the option with [RequiresRestart]
+ var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey;
+
+ if (!string.IsNullOrWhiteSpace(adminApiKeyString))
{
- JwtSigningKey = jwtSigningKey;
- OptionsAtStartup = optionsAtStartup;
- OptionsMonitor = optionsMonitor;
- }
+ if (!adminApiKeyString.Contains(';'))
+ {
+ PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions
+ {
+ Key = adminApiKeyString,
+ };
+ }
- private SymmetricSecurityKey JwtSigningKey { get; }
- private OptionsAtStartup OptionsAtStartup { get; }
- private IOptionsMonitor<Options> OptionsMonitor { get; }
+ var tuples = adminApiKeyString.Split(';');
- public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress)
- {
- var record = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys
- .FirstOrDefault(k => k.Value.Key == key);
+ string key = null;
+ string role = null;
+ string cidr = null;
- if (record.Key == null)
+ foreach (var tuple in tuples)
{
- throw new NotFoundException($"The provided API key does not match an existing key");
+ if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase))
+ {
+ role = tuple.Split('=').LastOrDefault();
+ }
+ else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase))
+ {
+ cidr = tuple.Split('=').LastOrDefault();
+ }
+ else
+ {
+ key = tuple;
+ }
}
- if (!record.Value.Cidr.Split(',')
- .Select(cidr => IPAddressRange.Parse(cidr))
- .Any(range => range.Contains(callerIpAddress)))
+ if (!string.IsNullOrEmpty(key))
{
- throw new OutOfRangeException("The remote IP address is not within the range specified for the key");
+ PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions
+ {
+ Key = key,
+ Role = string.IsNullOrWhiteSpace(role) ? Role.Administrator.ToString() : role,
+ Cidr = string.IsNullOrWhiteSpace(cidr) ? "0.0.0.0/0,::/0" : cidr,
+ };
}
+ }
+ }
+
+ private SymmetricSecurityKey JwtSigningKey { get; }
+ private OptionsAtStartup OptionsAtStartup { get; }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions PrimaryApiKey { get; } = null;
+
+ public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress)
+ {
+ var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable();
- return (record.Key, record.Value.Role.ToEnum<Role>());
+ if (PrimaryApiKey is not null)
+ {
+ keys = keys.Prepend(new KeyValuePair<string, Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions>(nameof(PrimaryApiKey), PrimaryApiKey));
}
- public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null)
+ var record = keys.FirstOrDefault(k => k.Value.Key == key);
+
+ if (record.Key == null)
{
- var issuedUtc = DateTime.UtcNow;
- var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl);
+ throw new NotFoundException($"Unknown API key beginning with: {key.Substring(0, 4)}");
+ }
- var claims = new List<Claim>()
- {
- new Claim(ClaimTypes.Name, username),
- new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
- new Claim(ClaimTypes.Role, role.ToString()),
- new Claim("name", username),
- new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()),
- };
-
- var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256);
-
- var token = new JwtSecurityToken(
- issuer: Program.AppName,
- claims: claims,
- notBefore: issuedUtc,
- expires: expiresUtc,
- signingCredentials: credentials);
-
- return token;
+ if (!record.Value.Cidr.Split(',')
+ .Select(cidr => IPAddressRange.Parse(cidr))
+ .Any(range => range.Contains(callerIpAddress)))
+ {
+ throw new OutOfRangeException($"IP address {callerIpAddress} not included in CIDR range(s) for API key {record.Key}; allowed: {record.Value.Cidr}");
}
+
+ return (record.Key, record.Value.Role.ToEnum<Role>());
+ }
+
+ public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null)
+ {
+ var issuedUtc = DateTime.UtcNow;
+ var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl);
+
+ var claims = new List<Claim>()
+ {
+ new Claim(ClaimTypes.Name, username),
+ new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
+ new Claim(ClaimTypes.Role, role.ToString()),
+ new Claim("name", username),
+ new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()),
+ };
+
+ var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256);
+
+ var token = new JwtSecurityToken(
+ issuer: Program.AppName,
+ claims: claims,
+ notBefore: issuedUtc,
+ expires: expiresUtc,
+ signingCredentials: credentials);
+
+ return token;
}
}
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index b9ca4d36..d6873dc0 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -40,6 +40,7 @@ namespace slskd
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
+ using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
@@ -241,7 +242,7 @@ namespace slskd
private static IConfigurationRoot Configuration { get; set; }
private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup();
private static ILogger Log { get; set; } = new ConsoleWriteLineLogger();
- private static Mutex Mutex { get; } = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName));
+ private static Mutex Mutex { get; set; }
private static IDisposable DotNetRuntimeStats { get; set; }
[Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")]
@@ -339,9 +340,29 @@ namespace slskd
// the application isn't being run in command mode. check the mutex to ensure
// only one long-running instance.
- if (!Mutex.WaitOne(millisecondsTimeout: 0, exitContext: false))
+ try
+ {
+ Mutex = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName), out bool created);
+
+ if (!created)
+ {
+ Log.Fatal($"An instance of {AppName} is already running");
+ return;
+ }
+ }
+ catch (IOException ex)
+ {
+ Log.Fatal($"I/O exception attempting to acquire the application singleton mutex; this can happen when running in a restricted environment (such as a read-only filesystem or container). Exception: {ex.Message}");
+ return;
+ }
+ catch (UnauthorizedAccessException ex)
{
- Log.Fatal($"An instance of {AppName} is already running");
+ Log.Fatal($"Unauthorized access attempting to acquire the application singleton mutex; this can happen when running with insuffucent permissions. Exception: {ex.Message}");
+ return;
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal($"Failed to acquire the application singleton mutex: {ex.Message}");
return;
}
@@ -478,19 +499,39 @@ namespace slskd
.UseUrls()
.UseKestrel(options =>
{
- Log.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/");
- options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port);
+ // configure HTTP, either by listening at any IP or by each of the IPs provided in the
+ // config (note: they've already been validated at this point!)
+ if (string.IsNullOrWhiteSpace(OptionsAtStartup.Web.IpAddress))
+ {
+ Log.Information("Listening for HTTP requests at http://{IP}:{Port}/", IPAddress.IPv6Any, OptionsAtStartup.Web.Port);
+ options.Listen(IPAddress.IPv6Any, OptionsAtStartup.Web.Port); // [::]; any IPv4 or IPv6 address
+ }
+ else
+ {
+ var httpIps = OptionsAtStartup.Web.IpAddress
+ .Split(',')
+ .Select(ip => ip.Trim())
+ .Select(ip => IPAddress.Parse(ip));
+
+ foreach (var ip in httpIps)
+ {
+ Log.Information("Listening for HTTP requests at http://{IP}:{Port}/", ip, OptionsAtStartup.Web.Port);
+ options.Listen(ip, OptionsAtStartup.Web.Port);
+ }
+ }
+ // configure UDS, if supplied
if (OptionsAtStartup.Web.Socket != null)
{
Log.Information($"Listening for HTTP requests on unix domain socket (UDS) {OptionsAtStartup.Web.Socket}");
options.ListenUnixSocket(OptionsAtStartup.Web.Socket);
}
- if (!OptionsAtStartup.Web.Https.Disabled)
+ // configure HTTPS, again listening on any IP or on a list of supplied IPs
+ // use a local function because Microsoft can't get enough of the obtuse builder pattern
+ static void ListenHttps(KestrelServerOptions o, IPAddress ip)
{
- Log.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/");
- options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions =>
+ o.Listen(ip, OptionsAtStartup.Web.Https.Port, listenOptions =>
{
var cert = OptionsAtStartup.Web.Https.Certificate;
@@ -506,6 +547,28 @@ namespace slskd
}
});
}
+
+ if (!OptionsAtStartup.Web.Https.Disabled)
+ {
+ if (string.IsNullOrWhiteSpace(OptionsAtStartup.Web.Https.IpAddress))
+ {
+ Log.Information("Listening for HTTPS requests at https://{IP}:{Port}/", IPAddress.IPv6Any, OptionsAtStartup.Web.Https.Port);
+ ListenHttps(options, IPAddress.IPv6Any);
+ }
+ else
+ {
+ var httpsIps = OptionsAtStartup.Web.Https.IpAddress
+ .Split(',')
+ .Select(ip => ip.Trim())
+ .Select(ip => IPAddress.Parse(ip));
+
+ foreach (var ip in httpsIps)
+ {
+ Log.Information("Listening for HTTPS requests at https://{IP}:{Port}/", ip, OptionsAtStartup.Web.Https.Port);
+ ListenHttps(options, ip);
+ }
+ }
+ }
});
builder.Services
@@ -544,6 +607,15 @@ namespace slskd
}
finally
{
+ try
+ {
+ Mutex?.Dispose();
+ }
+ catch (Exception)
+ {
+ // Ignore disposal errors to prevent masking other exceptions
+ }
+
Serilog.Log.CloseAndFlush();
}
}
@@ -725,7 +797,7 @@ namespace slskd
var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key));
services.AddSingleton(jwtSigningKey);
- services.AddSingleton<ISecurityService, SecurityService>();
+ services.AddSingleton<SecurityService>();
if (!OptionsAtStartup.Web.Authentication.Disabled)
{
@@ -792,7 +864,7 @@ namespace slskd
try
{
// check to see if the provided value is a valid API key
- var service = services.BuildServiceProvider().GetRequiredService<ISecurityService>();
+ var service = services.BuildServiceProvider().GetRequiredService<SecurityService>();
var (name, role) = service.AuthenticateWithApiKey(token, callerIpAddress: context.HttpContext.Connection.RemoteIpAddress);
// the API key is valid. create a new, short lived jwt for the key name and role
@@ -1224,9 +1296,12 @@ namespace slskd
options.UseSqlite(connectionString);
options.AddInterceptors(new SqliteConnectionOpenedInterceptor());
- if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL)
+ if (OptionsAtStartup.Flags.LogSQL)
{
- options.LogTo(Log.Debug, LogLevel.Information);
+ options
+ .EnableSensitiveDataLogging()
+ .EnableDetailedErrors()
+ .LogTo(OptionsAtStartup.Debug ? Log.Debug : Log.Information, LogLevel.Information);
}
});
diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index 711bb21e..cb0c331a 100644
--- a/src/slskd/Shares/SqliteShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -177,6 +177,10 @@ namespace slskd.Shares
conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS files " +
"(maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, " +
"extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL);");
+
+ conn.ExecuteNonQuery("CREATE INDEX IF NOT EXISTS idx_files_timestamp ON files(timestamp)");
+ conn.ExecuteNonQuery("CREATE INDEX IF NOT EXISTS idx_directories_timestamp ON directories(timestamp)");
+ conn.ExecuteNonQuery("CREATE INDEX IF NOT EXISTS idx_scans_timestamp ON scans(timestamp DESC)");
}
/// <summary>
diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs
index 7bc6fd25..33550577 100644
--- a/src/slskd/Telemetry/Metrics.cs
+++ b/src/slskd/Telemetry/Metrics.cs
@@ -83,7 +83,7 @@ public static class Metrics
"The time taken to resolve a response to an incoming browse request, in milliseconds",
new HistogramConfiguration
{
- Buckets = Histogram.ExponentialBuckets(1, 2, 10),
+ Buckets = Histogram.ExponentialBuckets(start: 1, factor: 2, count: 10),
});
/// <summary>
@@ -105,6 +105,72 @@ public static class Metrics
}
/// <summary>
+ /// Metrics related to incoming enqueue requests and responses.
+ /// </summary>
+ public static class Enqueue
+ {
+ /// <summary>
+ /// Gets a histogram representing the time taken to evaluate an incoming request to enqueue a file against configured limits, in milliseconds.
+ /// </summary>
+ public static Histogram DecisionLatency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_enqueue_decision_latency",
+ "The time taken to evaluate an incoming request to enqueue a file against configured limits, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(start: 1, factor: 2, count: 16), // up to ~2 seconds
+ });
+
+ /// <summary>
+ /// Gets an EMA representing the average time taken to evaluate an incoming request to enqueue a file against configured limits, in milliseconds.
+ /// </summary>
+ public static ExponentialMovingAverage CurrentDecisionLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentDecisionLatencyGauge.Set(value));
+
+ /// <summary>
+ /// Gets a histogram representing the total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds.
+ /// </summary>
+ public static Histogram Latency { get; } = Prometheus.Metrics.CreateHistogram(
+ "slskd_enqueue_latency",
+ "The total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds",
+ new HistogramConfiguration
+ {
+ Buckets = Histogram.ExponentialBuckets(start: 1, factor: 2, count: 16), // up to ~2 seconds
+ });
+
+ /// <summary>
+ /// Gets an EMA representing the average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds.
+ /// </summary>
+ public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentLatencyGauge.Set(value));
+
+ /// <summary>
+ /// Gets a counter representing the total number of incoming enqueue requests received.
+ /// </summary>
+ public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_received", "Total number of incoming enqueue requests received");
+
+ /// <summary>
+ /// Gets a counter representing the total number of incoming enqueue requests dropped due to processing pressure.
+ /// </summary>
+ public static Counter RequestsDropped { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_dropped", "Total number of incoming enqueue requests dropped due to processing pressure");
+
+ /// <summary>
+ /// Gets a counter representing the total number of incoming enqueue requests rejected.
+ /// </summary>
+ public static Counter RequestsRejected { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_rejected", "Total number of incoming enqueue requests rejected");
+
+ /// <summary>
+ /// Gets a counter representing the total number of incoming enqueue requests accepted.
+ /// </summary>
+ public static Counter RequestsAccepted { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_accepted", "Total number of incoming enqueue requests accepted");
+
+ /// <summary>
+ /// Gets a gauge representing the number of incoming enqueue requests waiting to be processed.
+ /// </summary>
+ public static Gauge CurrentQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_queue_depth_current", "The number of incoming enqueue requests waiting to be processed");
+
+ private static Gauge CurrentDecisionLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_decision_latency_current", "The average time taken to evaluate an incoming request to enqueue a file against configured limits, in milliseconds");
+ private static Gauge CurrentLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_latency_current", "The average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds");
+ }
+
+ /// <summary>
/// Metrics related to the distributed network.
/// </summary>
public static class DistributedNetwork
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index 068d1174..443a1b44 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -115,14 +115,16 @@ namespace slskd.Transfers.API
return Forbid();
}
- var transfers = Transfers.Downloads.List(t => t.State.HasFlag(Soulseek.TransferStates.Completed));
-
- foreach (var id in transfers.Select(t => t.Id))
+ try
{
- Transfers.Downloads.Remove(id);
+ Transfers.Downloads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains(t.State));
+ return NoContent();
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to remove completed downloads: {Message}", ex.Message);
+ return StatusCode(500, ex.Message);
}
-
- return NoContent();
}
/// <summary>
@@ -182,16 +184,16 @@ namespace slskd.Transfers.API
return Forbid();
}
- // get all the transfers that aren't removed
- var transfers = Transfers.Uploads
- .List(t => t.State.HasFlag(Soulseek.TransferStates.Completed), includeRemoved: false);
-
- foreach (var id in transfers.Select(t => t.Id))
+ try
{
- Transfers.Uploads.Remove(id);
+ Transfers.Uploads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains(t.State));
+ return NoContent();
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to remove completed uploads: {Message}", ex.Message);
+ return StatusCode(500, ex.Message);
}
-
- return NoContent();
}
/// <summary>
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index 9bc25373..beeab755 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -89,16 +89,25 @@ namespace slskd.Transfers.Downloads
/// Removes <see cref="TransferStates.Completed"/> downloads older than the specified <paramref name="age"/>.
/// </summary>
/// <param name="age">The age after which downloads are eligible for pruning, in hours.</param>
- /// <param name="stateHasFlag">An optional, additional state by which downloads are filtered for pruning.</param>
+ /// <param name="states">One or more states by which downloads are filtered for pruning.</param>
/// <returns>The number of pruned downloads.</returns>
- int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed);
+ int Prune(int age, params TransferStates[] states);
/// <summary>
- /// Removes the download matching the specified <paramref name="id"/>.
+ /// Removes the completed download matching the specified <paramref name="id"/>.
/// </summary>
/// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
/// <param name="id">The unique identifier of the download.</param>
- void Remove(Guid id);
+ /// <returns>A value indicating whether the record was removed.</returns>
+ bool Remove(Guid id);
+
+ /// <summary>
+ /// Removes all completed downloads matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="expression">The expression used to match downloads.</param>
+ /// <returns>The number of records removed.</returns>
+ int Remove(Expression<Func<Transfer, bool>> expression);
/// <summary>
/// Cancels the download matching the specified <paramref name="id"/>, if it is in progress.
@@ -307,17 +316,22 @@ namespace slskd.Transfers.Downloads
using var context = ContextFactory.CreateDbContext();
/*
- get all past downloads from this user. this list will remain stable throughout this process because
+ get existing downloads from this user. this list will remain stable throughout this process because
we have exclusive access for this user. we'll be adding new records, but we've already deduplicated
them so we don't have to worry about duplicate records being created in the critical section
+
+ we are looking for:
+ 1. anything that's not yet complete (we need to disallow the enqueue)
+ 2. anything complete, but not yet removed from the UI (we need to supersede it)
*/
- var existingRecords = context.Transfers
+ var existingRecordsNotYetRemoved = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
.Where(t => t.Username == username)
+ .Where(t => !t.Removed || !TransferStateCategories.Completed.Contains(t.State))
.AsNoTracking()
.ToList();
- var existingInProgressRecords = existingRecords
+ var existingInProgressRecords = existingRecordsNotYetRemoved
.Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed))
.ToDictionary(t => t.Filename, t => t);
@@ -401,7 +415,7 @@ namespace slskd.Transfers.Downloads
Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id);
- foreach (var record in existingRecords.Where(t => t.Filename == file.Filename && !t.Removed))
+ foreach (var record in existingRecordsNotYetRemoved.Where(t => t.Filename == file.Filename && !t.Removed))
{
record.Removed = true;
context.Update(record);
@@ -663,13 +677,15 @@ namespace slskd.Transfers.Downloads
/// Removes <see cref="TransferStates.Completed"/> downloads older than the specified <paramref name="age"/>.
/// </summary>
/// <param name="age">The age after which downloads are eligible for pruning, in hours.</param>
- /// <param name="stateHasFlag">An optional, additional state by which downloads are filtered for pruning.</param>
+ /// <param name="states">One or more states by which downloads are filtered for pruning.</param>
/// <returns>The number of pruned downloads.</returns>
- public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed)
+ public int Prune(int age, params TransferStates[] states)
{
- if (!stateHasFlag.HasFlag(TransferStates.Completed))
+ var statesSet = new HashSet<int>(states.Select(s => (int)s));
+
+ if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed)))
{
- throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag));
+ throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states));
}
try
@@ -678,23 +694,16 @@ namespace slskd.Transfers.Downloads
var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age);
- var expired = context.Transfers
+ var pruned = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
.Where(t => !t.Removed)
.Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime)
- .Where(t => t.State == stateHasFlag)
- .ToList();
-
- foreach (var tx in expired)
- {
- tx.Removed = true;
- }
-
- var pruned = context.SaveChanges();
+ .Where(t => statesSet.Contains((int)t.State))
+ .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
if (pruned > 0)
{
- Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, stateHasFlag);
+ Log.Debug("Pruned {Count} expired downloads with states {States}", pruned, statesSet);
}
return pruned;
@@ -707,38 +716,40 @@ namespace slskd.Transfers.Downloads
}
/// <summary>
- /// Removes the download matching the specified <paramref name="id"/>.
+ /// Removes the completed download matching the specified <paramref name="id"/>.
/// </summary>
/// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
/// <param name="id">The unique identifier of the download.</param>
- public void Remove(Guid id)
+ /// <returns>A value indicating whether the record was removed.</returns>
+ public bool Remove(Guid id)
+ {
+ return Remove(t => t.Id == id) > 0;
+ }
+
+ /// <summary>
+ /// Removes all completed downloads matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="expression">The expression used to match downloads.</param>
+ /// <returns>The number of records removed.</returns>
+ public int Remove(Expression<Func<Transfer, bool>> expression)
{
try
{
using var context = ContextFactory.CreateDbContext();
- var transfer = context.Transfers
+ var count = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
- .Where(t => t.Id == id)
- .FirstOrDefault();
-
- if (transfer == default)
- {
- throw new NotFoundException($"No download matching id ${id}");
- }
-
- if (!transfer.State.HasFlag(TransferStates.Completed))
- {
- throw new InvalidOperationException($"Invalid attempt to remove a download before it is complete");
- }
-
- transfer.Removed = true;
+ .Where(t => TransferStateCategories.Completed.Contains(t.State))
+ .Where(expression)
+ .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
- context.SaveChanges();
+ Log.Debug("Removed {Count} downloads by expression", count);
+ return count;
}
catch (Exception ex)
{
- Log.Error(ex, "Failed to remove download {Id}: {Message}", id, ex.Message);
+ Log.Error(ex, "Failed to remove downloads by expression: {Message}", ex.Message);
throw;
}
}
diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs
index eac4935b..422595e9 100644
--- a/src/slskd/Transfers/TransfersDbContext.cs
+++ b/src/slskd/Transfers/TransfersDbContext.cs
@@ -70,6 +70,24 @@ namespace slskd.Transfers
.Entity<Transfer>()
.HasIndex(t => t.State)
.HasDatabaseName("IDX_Transfers_State");
+
+ modelBuilder
+ .Entity<Transfer>()
+ .HasIndex(t => t.Removed)
+ .HasDatabaseName("IDX_Transfers_Removed");
+
+ // covers the check for existing records when enqueueing uploads and downloads
+ modelBuilder
+ .Entity<Transfer>()
+ .HasIndex(t => new { t.Username, t.Filename })
+ .HasDatabaseName("IDX_Transfers_UsernameFilename");
+
+ // covers the GetUserStatistics method that backs limit checks
+ // check every so often with EXPLAIN to make sure it's being shown as a covering index
+ modelBuilder
+ .Entity<Transfer>()
+ .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size })
+ .HasDatabaseName("IDX_Transfers_UserUploadStatistics");
}
}
}
diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs
new file mode 100644
index 00000000..5ccbe572
--- /dev/null
+++ b/src/slskd/Transfers/Types/TransferStateCategories.cs
@@ -0,0 +1,116 @@
+// <copyright file="TransferStateCategories.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Transfers;
+
+using System.Collections.Generic;
+using Soulseek;
+
+/// <summary>
+/// A collection of transfer state integers, grouped into sets that represent common states.
+/// </summary>
+/// <remarks>
+/// SQLite can't take advantage of indexes when using bitwise operations, which is what Entity Framework
+/// turns HasFlag() expressions into. These hash sets allow us to use IN expressions instead of bitwise.
+/// </remarks>
+public static class TransferStateCategories
+{
+ /// <summary>
+ /// All states representing a successful transfer:
+ ///
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Succeeded"/> (16 | 32 = 48)</item>
+ /// </list>
+ /// </summary>
+ public static readonly HashSet<TransferStates> Successful = [
+ TransferStates.Completed | TransferStates.Succeeded // 16 | 32 = 48
+ ];
+
+ /// <summary>
+ /// All states representing a failed transfer:
+ ///
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Cancelled"/> (16 | 64 = 80)</item>
+ /// <item><see cref="TransferStates.TimedOut"/> (16 | 128 = 144)</item>
+ /// <item><see cref="TransferStates.Errored"/> (16 | 256 = 272)</item>
+ /// <item><see cref="TransferStates.Rejected"/> (16 | 512 = 528)</item>
+ /// <item><see cref="TransferStates.Aborted"/> (16 | 1024 = 1040)</item>
+ /// </list>
+ /// </summary>
+ public static readonly HashSet<TransferStates> Failed = [
+ TransferStates.Completed | TransferStates.Cancelled, // 16 | 64 = 80
+ TransferStates.Completed | TransferStates.TimedOut, // 16 | 128 = 144
+ TransferStates.Completed | TransferStates.Errored, // 16 | 256 = 272
+ TransferStates.Completed | TransferStates.Rejected, // 16 | 512 = 528
+ TransferStates.Completed | TransferStates.Aborted, // 16 | 1024 = 1040
+ ];
+
+ /// <summary>
+ /// All states containing the <see cref="TransferStates.Completed"/> flag.
+ ///
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Completed"/> (16)</item>
+ /// </list>
+ ///
+ /// Successful:
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Succeeded"/> (16 | 32 = 48)</item>
+ /// </list>
+ ///
+ /// Failed:
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Cancelled"/> (16 | 64 = 80)</item>
+ /// <item><see cref="TransferStates.TimedOut"/> (16 | 128 = 144)</item>
+ /// <item><see cref="TransferStates.Errored"/> (16 | 256 = 272)</item>
+ /// <item><see cref="TransferStates.Rejected"/> (16 | 512 = 528)</item>
+ /// <item><see cref="TransferStates.Aborted"/> (16 | 1024 = 1040)</item>
+ /// </list>
+ /// </summary>
+ public static readonly HashSet<TransferStates> Completed = [
+ TransferStates.Completed, // 16, in case of some sort of a malfunction or regression
+ .. Successful,
+ .. Failed
+ ];
+
+ /// <summary>
+ /// All states representing a queued transfer:
+ ///
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Queued"/> (2)</item>
+ /// <item><see cref="TransferStates.Locally"/> (2 | 2048 = 2050)</item>
+ /// <item><see cref="TransferStates.Remotely"/> (2 | 4096 = 4098)</item>
+ /// </list>
+ /// </summary>
+ public static readonly HashSet<TransferStates> Queued = [
+ TransferStates.Queued, // 2, in case of some sort of a malfunction or regression
+ TransferStates.Queued | TransferStates.Locally, // 2 | 2048 = 2050
+ TransferStates.Queued | TransferStates.Remotely, // 2 | 4096 = 4098
+ ];
+
+ /// <summary>
+ /// All states representing a transfer that is in progress:
+ ///
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Initializing"/> (4)</item>
+ /// <item><see cref="TransferStates.InProgress"/> (8)</item>
+ /// </list>
+ /// </summary>
+ public static readonly HashSet<TransferStates> InProgress = [
+ TransferStates.Initializing, // 4
+ TransferStates.InProgress, // 8
+ ];
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Types/UserUploadStatistics.cs b/src/slskd/Transfers/Types/UserUploadStatistics.cs
new file mode 100644
index 00000000..945964f5
--- /dev/null
+++ b/src/slskd/Transfers/Types/UserUploadStatistics.cs
@@ -0,0 +1,35 @@
+// <copyright file="UserUploadStatistics.cs" company="slskd Team">
+// Copyright (c) slskd Team. All rights reserved.
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published
+// by the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see https://www.gnu.org/licenses/.
+// </copyright>
+
+namespace slskd.Transfers;
+
+/// <summary>
+/// Upload statistics, for use when evaluating incoming enqueue requests against configured limits.
+/// </summary>
+public record UserUploadStatistics
+{
+ public int QueuedFiles { get; set; }
+ public long QueuedBytes { get; set; }
+
+ public int WeeklyFailedFiles { get; set; }
+ public int WeeklySucceededFiles { get; set; }
+ public long WeeklySucceededBytes { get; set; }
+
+ public int DailyFailedFiles { get; set; }
+ public int DailySucceededFiles { get; set; }
+ public long DailySucceededBytes { get; set; }
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index c96d1131..bcc1dd90 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -96,6 +96,14 @@ namespace slskd.Transfers.Uploads
(int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression);
/// <summary>
+ /// Gets upload statistics for the specified <paramref name="username"/>.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <param name="utcNow">An optional timestamp representing the current time in UTC.</param>
+ /// <returns>The gathered statistics.</returns>
+ UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null);
+
+ /// <summary>
/// Returns a list of all uploads matching the optional <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An optional expression used to match uploads.</param>
@@ -107,16 +115,25 @@ namespace slskd.Transfers.Uploads
/// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>.
/// </summary>
/// <param name="age">The age after which uploads are eligible for pruning, in minutes.</param>
- /// <param name="stateHasFlag">An optional, additional state by which uploads are filtered for pruning.</param>
+ /// <param name="states">One or more states by which uploads are filtered for pruning.</param>
/// <returns>The number of pruned uploads.</returns>
- int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed);
+ int Prune(int age, params TransferStates[] states);
/// <summary>
- /// Removes the upload matching the specified <paramref name="id"/>.
+ /// Removes the completed upload matching the specified <paramref name="id"/>.
/// </summary>
/// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
/// <param name="id">The unique identifier of the upload.</param>
- void Remove(Guid id);
+ /// <returns>A value indicating whether the record was removed.</returns>
+ bool Remove(Guid id);
+
+ /// <summary>
+ /// Removes all completed uploads matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="expression">The expression used to match uploads.</param>
+ /// <returns>The number of records removed.</returns>
+ int Remove(Expression<Func<Transfer, bool>> expression);
/// <summary>
/// Cancels the upload matching the specified <paramref name="id"/>, if it is in progress.
@@ -780,13 +797,15 @@ namespace slskd.Transfers.Uploads
/// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>.
/// </summary>
/// <param name="age">The age after which uploads are eligible for pruning, in minutes.</param>
- /// <param name="stateHasFlag">An optional, additional state by which uploads are filtered for pruning.</param>
+ /// <param name="states">One or more states by which uploads are filtered for pruning.</param>
/// <returns>The number of pruned uploads.</returns>
- public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed)
+ public int Prune(int age, params TransferStates[] states)
{
- if (!stateHasFlag.HasFlag(TransferStates.Completed))
+ var statesSet = new HashSet<int>(states.Select(s => (int)s));
+
+ if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed)))
{
- throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag));
+ throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states));
}
try
@@ -795,23 +814,16 @@ namespace slskd.Transfers.Uploads
var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age);
- var expired = context.Transfers
+ var pruned = context.Transfers
.Where(t => t.Direction == TransferDirection.Upload)
.Where(t => !t.Removed)
.Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime)
- .Where(t => t.State.HasFlag(stateHasFlag))
- .ToList();
-
- foreach (var tx in expired)
- {
- tx.Removed = true;
- }
-
- var pruned = context.SaveChanges();
+ .Where(t => statesSet.Contains((int)t.State))
+ .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
if (pruned > 0)
{
- Log.Debug("Pruned {Count} expired uploads with state {State}", pruned, stateHasFlag);
+ Log.Debug("Pruned {Count} expired uploads with states {States}", pruned, statesSet);
}
return pruned;
@@ -824,38 +836,40 @@ namespace slskd.Transfers.Uploads
}
/// <summary>
- /// Removes the upload matching the specified <paramref name="id"/>.
+ /// Removes the completed upload matching the specified <paramref name="id"/>.
/// </summary>
/// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
/// <param name="id">The unique identifier of the upload.</param>
- public void Remove(Guid id)
+ /// <returns>A value indicating whether the record was removed.</returns>
+ public bool Remove(Guid id)
+ {
+ return Remove(t => t.Id == id) > 0;
+ }
+
+ /// <summary>
+ /// Removes all completed uploads matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="expression">The expression used to match uploads.</param>
+ /// <returns>The number of records removed.</returns>
+ public int Remove(Expression<Func<Transfer, bool>> expression)
{
try
{
using var context = ContextFactory.CreateDbContext();
- var transfer = context.Transfers
+ var count = context.Transfers
.Where(t => t.Direction == TransferDirection.Upload)
- .Where(t => t.Id == id)
- .FirstOrDefault();
-
- if (transfer == default)
- {
- throw new NotFoundException($"No upload matching id ${id}");
- }
-
- if (!transfer.State.HasFlag(TransferStates.Completed))
- {
- throw new InvalidOperationException($"Invalid attempt to remove an upload before it is complete");
- }
-
- transfer.Removed = true;
+ .Where(t => TransferStateCategories.Completed.Contains(t.State))
+ .Where(expression)
+ .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
- context.SaveChanges();
+ Log.Debug("Removed {Count} uploads by expression", count);
+ return count;
}
catch (Exception ex)
{
- Log.Error(ex, "Failed to remove upload {Id}: {Message}", id, ex.Message);
+ Log.Error(ex, "Failed to remove uploads by expression: {Message}", ex.Message);
throw;
}
}
@@ -913,6 +927,54 @@ namespace slskd.Transfers.Uploads
context.SaveChanges();
}
+ /// <summary>
+ /// Gets upload statistics for the specified <paramref name="username"/>.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <param name="utcNow">An optional timestamp representing the current time in UTC.</param>
+ /// <returns>The gathered statistics.</returns>
+ public UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null)
+ {
+ utcNow ??= DateTime.UtcNow;
+ var dailyCutoff = utcNow.Value.AddDays(-1);
+ var weeklyCutoff = utcNow.Value.AddDays(-7);
+
+ using var context = ContextFactory.CreateDbContext();
+
+ var failedStates = TransferStateCategories.Failed.ToList();
+ var successState = TransferStates.Completed | TransferStates.Succeeded;
+
+ var stats = context.Transfers
+ .AsNoTracking()
+ .Where(t => t.Username == username)
+ .Where(t => t.Direction == TransferDirection.Upload)
+ .Where(t => t.EndedAt == null || t.StartedAt >= weeklyCutoff)
+ .GroupBy(t => 1) // aggregate everything into one row
+ .Select(g => new UserUploadStatistics
+ {
+ QueuedFiles = g.Count(t => t.EndedAt == null),
+ QueuedBytes = g.Where(t => t.EndedAt == null).Sum(t => (long?)t.Size) ?? 0,
+
+ // note: this generates some funky json_each() expression under the hood; it's an EF optimization
+ // that helps with optimization of query plans. i've tried expanding this out to force an IN
+ // and there's either no difference, or there's a slight improvement with the json_each method.
+ WeeklyFailedFiles = g.Count(t => t.StartedAt >= weeklyCutoff && failedStates.Contains(t.State)),
+
+ WeeklySucceededFiles = g.Count(t => t.StartedAt >= weeklyCutoff && t.State == successState),
+ WeeklySucceededBytes = g.Where(t => t.StartedAt >= weeklyCutoff && t.State == successState)
+ .Sum(t => (long?)t.Size) ?? 0,
+
+ DailyFailedFiles = g.Count(t => t.StartedAt >= dailyCutoff && failedStates.Contains(t.State)),
+
+ DailySucceededFiles = g.Count(t => t.StartedAt >= dailyCutoff && t.State == successState),
+ DailySucceededBytes = g.Where(t => t.StartedAt >= dailyCutoff && t.State == successState)
+ .Sum(t => (long?)t.Size) ?? 0,
+ })
+ .FirstOrDefault();
+
+ return stats ?? new UserUploadStatistics();
+ }
+
private bool TryFail(Guid id, string exception, TransferStates state)
{
var t = Find(t => t.Id == id);
diff --git a/src/web/package-lock.json b/src/web/package-lock.json
index 5d0ae3d2..88c9c5da 100644
--- a/src/web/package-lock.json
+++ b/src/web/package-lock.json
@@ -6544,6 +6544,23 @@
"node": ">= 0.4"
}
},
+ "node_modules/call-bound": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "get-intrinsic": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
@@ -10414,45 +10431,50 @@
}
},
"node_modules/express": {
- "version": "4.21.1",
- "resolved": "https://registry.npmjs.org/express/-/express-4.21.1.tgz",
- "integrity": "sha512-YSFlK1Ee0/GC8QaO91tHcDxJiE/X4FbpAyQWkxAvG6AXCuR65YzK8ua6D9hvi/TzUfZMpc+BwuM1IPw8fmQBiQ==",
+ "version": "4.22.1",
+ "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz",
+ "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==",
"dev": true,
+ "license": "MIT",
"dependencies": {
"accepts": "~1.3.8",
"array-flatten": "1.1.1",
- "body-parser": "1.20.3",
- "content-disposition": "0.5.4",
+ "body-parser": "~1.20.3",
+ "content-disposition": "~0.5.4",
"content-type": "~1.0.4",
- "cookie": "0.7.1",
- "cookie-signature": "1.0.6",
+ "cookie": "~0.7.1",
+ "cookie-signature": "~1.0.6",
"debug": "2.6.9",
"depd": "2.0.0",
"encodeurl": "~2.0.0",
"escape-html": "~1.0.3",
"etag": "~1.8.1",
- "finalhandler": "1.3.1",
- "fresh": "0.5.2",
- "http-errors": "2.0.0",
+ "finalhandler": "~1.3.1",
+ "fresh": "~0.5.2",
+ "http-errors": "~2.0.0",
"merge-descriptors": "1.0.3",
"methods": "~1.1.2",
- "on-finished": "2.4.1",
+ "on-finished": "~2.4.1",
"parseurl": "~1.3.3",
- "path-to-regexp": "0.1.10",
+ "path-to-regexp": "~0.1.12",
"proxy-addr": "~2.0.7",
- "qs": "6.13.0",
+ "qs": "~6.14.0",
"range-parser": "~1.2.1",
"safe-buffer": "5.2.1",
- "send": "0.19.0",
- "serve-static": "1.16.2",
+ "send": "~0.19.0",
+ "serve-static": "~1.16.2",
"setprototypeof": "1.2.0",
- "statuses": "2.0.1",
+ "statuses": "~2.0.1",
"type-is": "~1.6.18",
"utils-merge": "1.0.1",
"vary": "~1.1.2"
},
"engines": {
"node": ">= 0.10.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
}
},
"node_modules/express/node_modules/array-flatten": {
@@ -10477,10 +10499,27 @@
"dev": true
},
"node_modules/express/node_modules/path-to-regexp": {
- "version": "0.1.10",
- "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz",
- "integrity": "sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==",
- "dev": true
+ "version": "0.1.12",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz",
+ "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/express/node_modules/qs": {
+ "version": "6.14.1",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz",
+ "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "side-channel": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
},
"node_modules/extract-files": {
"version": "11.0.0",
@@ -15120,10 +15159,14 @@
}
},
"node_modules/object-inspect": {
- "version": "1.13.1",
- "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz",
- "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==",
+ "version": "1.13.4",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
@@ -18745,15 +18788,73 @@
}
},
"node_modules/side-channel": {
- "version": "1.0.6",
- "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz",
- "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==",
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz",
+ "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==",
"dev": true,
+ "license": "MIT",
"dependencies": {
- "call-bind": "^1.0.7",
"es-errors": "^1.3.0",
- "get-intrinsic": "^1.2.4",
- "object-inspect": "^1.13.1"
+ "object-inspect": "^1.13.3",
+ "side-channel-list": "^1.0.0",
+ "side-channel-map": "^1.0.1",
+ "side-channel-weakmap": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-list": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz",
+ "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-map": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-weakmap": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3",
+ "side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
diff --git a/src/web/src/components/System/Files/Explorer.jsx b/src/web/src/components/System/Files/Explorer.jsx
index e577b31c..ca0bdba1 100644
--- a/src/web/src/components/System/Files/Explorer.jsx
+++ b/src/web/src/components/System/Files/Explorer.jsx
@@ -126,6 +126,8 @@ const Explorer = ({ remoteFileManagement, root }) => {
const [directory, setDirectory] = useState({ directories: [], files: [] });
const [subdirectory, setSubdirectory] = useState([]);
const [loading, setLoading] = useState(false);
+ const [sortColumn, setSortColumn] = useState('name');
+ const [sortDirection, setSortDirection] = useState('ascending');
const fetch = async () => {
setLoading(true);
@@ -155,11 +157,45 @@ const Explorer = ({ remoteFileManagement, root }) => {
setSubdirectory(copy);
};
+ 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 <LoaderSegment />;
}
const total = directory?.directories?.length + directory?.files?.length ?? 0;
+ const sortedDirectories = sortItems(directory?.directories);
+ const sortedFiles = sortItems(directory?.files);
return (
<>
@@ -176,11 +212,37 @@ const Explorer = ({ remoteFileManagement, root }) => {
>
<Table.Header>
<Table.Row>
- <Table.HeaderCell className="explorer-list-name">
+ <Table.HeaderCell
+ className="explorer-list-name"
+ onClick={() => handleSort('name')}
+ style={{ cursor: 'pointer' }}
+ >
Name
+ {sortColumn === 'name' && (
+ <Icon
+ name={
+ sortDirection === 'ascending'
+ ? 'chevron up'
+ : 'chevron down'
+ }
+ />
+ )}
</Table.HeaderCell>
- <Table.HeaderCell className="explorer-list-date">
+ <Table.HeaderCell
+ className="explorer-list-date"
+ onClick={() => handleSort('date')}
+ style={{ cursor: 'pointer' }}
+ >
Date Modified
+ {sortColumn === 'date' && (
+ <Icon
+ name={
+ sortDirection === 'ascending'
+ ? 'chevron up'
+ : 'chevron down'
+ }
+ />
+ )}
</Table.HeaderCell>
<Table.HeaderCell className="explorer-list-size">
Size
@@ -215,7 +277,7 @@ const Explorer = ({ remoteFileManagement, root }) => {
subdirectory={subdirectory}
/>
)}
- {directory?.directories?.map((d) => (
+ {sortedDirectories?.map((d) => (
<DirectoryRow
key={d.name}
onClick={() => select({ path: d.name })}
@@ -225,7 +287,7 @@ const Explorer = ({ remoteFileManagement, root }) => {
{...d}
/>
))}
- {directory?.files?.map((f) => (
+ {sortedFiles?.map((f) => (
<FileRow
key={f.name}
remoteFileManagement={remoteFileManagement}
diff --git a/src/web/src/components/Transfers/TransferDetails.jsx b/src/web/src/components/Transfers/TransferDetails.jsx
new file mode 100644
index 00000000..256ddcac
--- /dev/null
+++ b/src/web/src/components/Transfers/TransferDetails.jsx
@@ -0,0 +1,107 @@
+import { formatBytes, formatDate } from '../../lib/util';
+import { Table } from 'semantic-ui-react';
+
+// Regex patterns for field name formatting
+const UPPERCASE_PATTERN = /([A-Z])/gu;
+const FIRST_CHAR_PATTERN = /^./u;
+const DURATION_PATTERN = /^\d{2}:\d{2}:\d{2}/u;
+
+// Convert camelCase to Title Case with spaces
+const formatFieldName = (fieldName) => {
+ return fieldName
+ .replaceAll(UPPERCASE_PATTERN, ' $1')
+ .replace(FIRST_CHAR_PATTERN, (string) => string.toUpperCase())
+ .trim();
+};
+
+// Format value based on field type
+const formatValue = (key, value) => {
+ if (value === null || value === undefined) {
+ return 'N/A';
+ }
+
+ const lowerKey = key.toLowerCase();
+
+ // Format datetime fields
+ if (
+ (lowerKey.includes('at') || lowerKey.includes('time')) &&
+ typeof value === 'string' &&
+ value.includes(':')
+ ) {
+ // Check if it's a duration (HH:MM:SS format)
+ if (DURATION_PATTERN.test(value)) {
+ return value;
+ }
+
+ // Otherwise it's a datetime
+ return formatDate(value);
+ }
+
+ // Format byte-related fields
+ if (lowerKey.includes('bytes') || key === 'size') {
+ return formatBytes(value);
+ }
+
+ // Format speed
+ if (lowerKey.includes('speed')) {
+ return `${formatBytes(value)}/s`;
+ }
+
+ // Format percentage
+ if (lowerKey.includes('percent')) {
+ if (typeof value === 'number') {
+ return `${value.toFixed(2)}%`;
+ }
+
+ return String(value);
+ }
+
+ return String(value);
+};
+
+const TransferDetails = ({ file }) => {
+ // Fields to display in the popup
+ const fields = [
+ 'id',
+ 'username',
+ 'direction',
+ 'filename',
+ 'size',
+ 'startOffset',
+ 'state',
+ 'requestedAt',
+ 'enqueuedAt',
+ 'startedAt',
+ 'endedAt',
+ 'bytesTransferred',
+ 'averageSpeed',
+ 'bytesRemaining',
+ 'elapsedTime',
+ 'percentComplete',
+ 'remainingTime',
+ ];
+
+ return (
+ <Table
+ basic="very"
+ compact
+ size="small"
+ >
+ <Table.Body>
+ {fields.map((field) => {
+ const value = file[field];
+ return (
+ <Table.Row key={field}>
+ <Table.Cell style={{ fontWeight: 'bold', paddingRight: '1em' }}>
+ {formatFieldName(field)}
+ </Table.Cell>
+ <Table.Cell>{formatValue(field, value)}</Table.Cell>
+ </Table.Row>
+ );
+ })}
+ </Table.Body>
+ </Table>
+ );
+};
+
+export default TransferDetails;
diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx
index b81049ec..4bd1e14e 100644
--- a/src/web/src/components/Transfers/TransferList.jsx
+++ b/src/web/src/components/Transfers/TransferList.jsx
@@ -1,4 +1,5 @@
import { formatBytes, formatBytesAsUnit, getFileName } from '../../lib/util';
+import TransferDetails from './TransferDetails';
import React, { Component } from 'react';
import {
Button,
@@ -6,6 +7,7 @@ import {
Header,
Icon,
List,
+ Popup,
Progress,
Table,
} from 'semantic-ui-react';
@@ -114,6 +116,12 @@ class TransferList extends Component {
<Table.HeaderCell className="transferlist-size">
Size
</Table.HeaderCell>
+ <Table.HeaderCell className="transferlist-detail">
+ <Icon
+ name="info circle"
+ size="small"
+ />
+ </Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
@@ -172,10 +180,37 @@ class TransferList extends Component {
)}
</Table.Cell>
<Table.Cell className="transferlist-size">
- {formatBytesTransferred({
- size: f.size,
- transferred: f.bytesTransferred,
- })}
+ <div
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ justifyContent: 'space-between',
+ }}
+ >
+ <span>
+ {formatBytesTransferred({
+ size: f.size,
+ transferred: f.bytesTransferred,
+ })}
+ </span>
+ </div>
+ </Table.Cell>
+ <Table.Cell className="transferlist-detail">
+ <Popup
+ content={<TransferDetails file={f} />}
+ on="click"
+ position="left center"
+ style={{ maxWidth: '600px' }}
+ trigger={
+ <Icon
+ color="grey"
+ link
+ name="info circle"
+ size="small"
+ />
+ }
+ wide="very"
+ />
</Table.Cell>
</Table.Row>
))}
diff --git a/src/web/src/components/Transfers/Transfers.css b/src/web/src/components/Transfers/Transfers.css
index 0b787f5f..2b16d32f 100644
--- a/src/web/src/components/Transfers/Transfers.css
+++ b/src/web/src/components/Transfers/Transfers.css
@@ -43,6 +43,11 @@
min-width: 150px;
}
+.transferlist-detail {
+ width: 5px;
+ min-width: 5px;
+}
+
.transferlist-filename {
word-wrap: break-word !important;
}