aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-01-02 18:51:07 -0600
committerGitHub <noreply@github.com>2026-01-02 18:51:07 -0600
commitb7f74ae0b21054cc57142c79b2514f5a94dce7f3 (patch)
tree2bc6d2c9a4dfad623d521a954f3a2b5c524d1dca /src
parent6a9c127062b8408e3cad19d4dd283577de6de045 (diff)
parentc00e667d6e0bded62599363a7766aeba877cca54 (diff)
downloadslskd-b7f74ae0b21054cc57142c79b2514f5a94dce7f3.tar.gz
Merge pull request #1591 from slskd/indexes
Optimize handling of file requests
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs245
-rw-r--r--src/slskd/Common/Logging/Checkpointer.cs94
-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/Program.cs7
-rw-r--r--src/slskd/Telemetry/Metrics.cs20
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs4
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs4
-rw-r--r--src/slskd/Transfers/TransfersDbContext.cs18
-rw-r--r--src/slskd/Transfers/Types/TransferStateCategories.cs73
-rw-r--r--src/slskd/Transfers/Types/UserUploadStatistics.cs35
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs58
12 files changed, 530 insertions, 122 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 6b66ec6e..52ca4f86 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -83,8 +83,8 @@ 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 EnqueueRequestQueueDepth = 0;
+ private static int EnqueueQueueDepth = 0;
+ private static double CurrentEnqueueLatency = 0;
#pragma warning restore SA1306 // Field names should begin with lower-case letter
public Application(
@@ -224,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; }
@@ -316,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)
{
@@ -327,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)
{
@@ -538,29 +540,82 @@ 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);
- if (Users.IsBlacklisted(username, endpoint.Address))
+ /*
+ 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)
{
- Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address);
- throw new DownloadEnqueueException("File not shared.");
+ Metrics.Enqueue.RequestsDropped.Inc(1);
+ throw new DownloadEnqueueException("Overwhelmed with requests; try again later.");
}
var stopwatch = new Stopwatch();
var decisionStopwatch = new Stopwatch();
- Interlocked.Increment(ref EnqueueRequestQueueDepth);
+ SemaphoreSlim userSemaphore = null;
+ Task userSemaphoreWaitTask;
+ bool userSemaphoreAcquired = false;
- await EnqueueRequestRateLimiter.WaitAsync();
+ bool enqueueRequestsSemaphoreAcquired = false;
try
{
- Interlocked.Decrement(ref EnqueueRequestQueueDepth);
+ 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
- Metrics.Enqueue.CurrentRequestQueueDepth.Set(EnqueueRequestQueueDepth);
+ 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();
@@ -623,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)
{
@@ -680,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)
{
@@ -721,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)
{
@@ -758,25 +786,47 @@ namespace slskd
}
}
- await Transfers.Uploads.EnqueueAsync(username, filename);
-
- Metrics.Enqueue.RequestsAccepted.Inc(1);
-
decisionStopwatch.Stop();
- Metrics.Enqueue.DecisionLatency.Observe(decisionStopwatch.ElapsedMilliseconds);
- Metrics.Enqueue.CurrentDecisionLatency.Update(decisionStopwatch.ElapsedMilliseconds);
+ await Transfers.Uploads.EnqueueAsync(username, filename);
stopwatch.Stop();
- Metrics.Enqueue.ResponseLatency.Observe(stopwatch.ElapsedMilliseconds);
- Metrics.Enqueue.CurrentResponseLatency.Update(stopwatch.ElapsedMilliseconds);
+ // 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
{
- EnqueueRequestRateLimiter.Release();
+ if (decisionStopwatch.IsRunning)
+ {
+ decisionStopwatch.Stop();
+ }
+
+ // 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);
+
+ if (userSemaphoreAcquired)
+ {
+ userSemaphore.Release();
+ }
- Log.Debug("EnqueueDownload for {Username}/{Filename} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", username, filename, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds);
+ if (enqueueRequestsSemaphoreAcquired)
+ {
+ GlobalEnqueueSemaphore.Release();
+ }
}
}
@@ -1061,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)
@@ -1771,5 +1824,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/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/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/Program.cs b/src/slskd/Program.cs
index 770c6746..2b2d2840 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -1293,9 +1293,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/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs
index 33d2bc40..33550577 100644
--- a/src/slskd/Telemetry/Metrics.cs
+++ b/src/slskd/Telemetry/Metrics.cs
@@ -128,8 +128,8 @@ public static class Metrics
/// <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 ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram(
- "slskd_enqueue_response_latency",
+ 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
{
@@ -139,7 +139,7 @@ public static class Metrics
/// <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 CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value));
+ 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.
@@ -147,6 +147,16 @@ public static class Metrics
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");
@@ -154,10 +164,10 @@ public static class Metrics
/// <summary>
/// Gets a gauge representing the number of incoming enqueue requests waiting to be processed.
/// </summary>
- public static Gauge CurrentRequestQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_request_queue_depth_current", "The number of incoming enqueue requests waiting to be processed");
+ 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 CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_response_latency_current", "The average total time taken to resolve a response to an incoming request to enqueue a file, 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>
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index 3e380000..5d2fc274 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -117,7 +117,7 @@ namespace slskd.Transfers.API
try
{
- Transfers.Downloads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains((int)t.State));
+ Transfers.Downloads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains(t.State));
return NoContent();
}
catch (Exception ex)
@@ -186,7 +186,7 @@ namespace slskd.Transfers.API
try
{
- Transfers.Uploads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains((int)t.State));
+ Transfers.Uploads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains(t.State));
return NoContent();
}
catch (Exception ex)
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index f1f39fba..beeab755 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -327,7 +327,7 @@ namespace slskd.Transfers.Downloads
var existingRecordsNotYetRemoved = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
.Where(t => t.Username == username)
- .Where(t => !t.Removed || !TransferStateCategories.Completed.Contains((int)t.State))
+ .Where(t => !t.Removed || !TransferStateCategories.Completed.Contains(t.State))
.AsNoTracking()
.ToList();
@@ -740,7 +740,7 @@ namespace slskd.Transfers.Downloads
var count = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
- .Where(t => TransferStateCategories.Completed.Contains((int)t.State))
+ .Where(t => TransferStateCategories.Completed.Contains(t.State))
.Where(expression)
.ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
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
index 02065714..5ccbe572 100644
--- a/src/slskd/Transfers/Types/TransferStateCategories.cs
+++ b/src/slskd/Transfers/Types/TransferStateCategories.cs
@@ -33,37 +33,55 @@ public static class TransferStateCategories
/// All states representing a successful transfer:
///
/// <list type="bullet">
- /// <item><see cref="TransferStates.Succeeded"/></item>
+ /// <item><see cref="TransferStates.Succeeded"/> (16 | 32 = 48)</item>
/// </list>
/// </summary>
- public static readonly HashSet<int> Successful = [
- (int)(TransferStates.Completed | TransferStates.Succeeded)
+ 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"/></item>
- /// <item><see cref="TransferStates.TimedOut"/></item>
- /// <item><see cref="TransferStates.Errored"/></item>
- /// <item><see cref="TransferStates.Rejected"/></item>
- /// <item><see cref="TransferStates.Aborted"/></item>
+ /// <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<int> Failed = [
- (int)(TransferStates.Completed | TransferStates.Cancelled),
- (int)(TransferStates.Completed | TransferStates.TimedOut),
- (int)(TransferStates.Completed | TransferStates.Errored),
- (int)(TransferStates.Completed | TransferStates.Rejected),
- (int)(TransferStates.Completed | TransferStates.Aborted),
+ 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<int> Completed = [
- (int)TransferStates.Completed, // in case some sort of a malfunction or regression
+ public static readonly HashSet<TransferStates> Completed = [
+ TransferStates.Completed, // 16, in case of some sort of a malfunction or regression
.. Successful,
.. Failed
];
@@ -72,26 +90,27 @@ public static class TransferStateCategories
/// All states representing a queued transfer:
///
/// <list type="bullet">
- /// <item><see cref="TransferStates.Locally"/></item>
- /// <item><see cref="TransferStates.Remotely"/></item>
+ /// <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<int> Queued = [
- (int)TransferStates.Queued,
- (int)(TransferStates.Queued | TransferStates.Locally),
- (int)(TransferStates.Queued | TransferStates.Remotely),
+ 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"/></item>
- /// <item><see cref="TransferStates.InProgress"/></item>
+ /// <item><see cref="TransferStates.Initializing"/> (4)</item>
+ /// <item><see cref="TransferStates.InProgress"/> (8)</item>
/// </list>
/// </summary>
- public static readonly HashSet<int> InProgress = [
- (int)TransferStates.Initializing,
- (int)TransferStates.InProgress,
+ 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 d75ccea3..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>
@@ -852,7 +860,7 @@ namespace slskd.Transfers.Uploads
var count = context.Transfers
.Where(t => t.Direction == TransferDirection.Upload)
- .Where(t => TransferStateCategories.Completed.Contains((int)t.State))
+ .Where(t => TransferStateCategories.Completed.Contains(t.State))
.Where(expression)
.ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
@@ -919,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);