From b471a8619ed6ef631794ef7ef9db05f00d1c2f26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 27 Dec 2025 17:28:42 -0600 Subject: document numeric values --- .../Transfers/Types/TransferStateCategories.cs | 63 ++++++++++++++-------- 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index 02065714..bd3c83de 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: /// /// - /// + /// (16 | 32 = 48) /// /// public static readonly HashSet Successful = [ - (int)(TransferStates.Completed | TransferStates.Succeeded) + (int)(TransferStates.Completed | TransferStates.Succeeded) // 16 | 32 = 48 ]; /// /// All states representing a failed transfer: /// /// - /// - /// - /// - /// - /// + /// (16 | 64 = 80) + /// (16 | 128 = 144) + /// (16 | 256 = 272) + /// (16 | 512 = 528) + /// (16 | 1024 = 1040) /// /// public static readonly HashSet 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), + (int)(TransferStates.Completed | TransferStates.Cancelled), // 16 | 64 = 80 + (int)(TransferStates.Completed | TransferStates.TimedOut), // 16 | 128 = 144 + (int)(TransferStates.Completed | TransferStates.Errored), // 16 | 256 = 272 + (int)(TransferStates.Completed | TransferStates.Rejected), // 16 | 512 = 528 + (int)(TransferStates.Completed | TransferStates.Aborted), // 16 | 1024 = 1040 ]; /// /// All states containing the flag. + /// + /// + /// (16) + /// + /// + /// Successful: + /// + /// (16 | 32 = 48) + /// + /// + /// Failed: + /// + /// (16 | 64 = 80) + /// (16 | 128 = 144) + /// (16 | 256 = 272) + /// (16 | 512 = 528) + /// (16 | 1024 = 1040) + /// /// public static readonly HashSet Completed = [ - (int)TransferStates.Completed, // in case some sort of a malfunction or regression + (int)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: /// /// - /// - /// + /// (2) + /// (2 | 2048 = 2050) + /// (2 | 4096 = 4098) /// /// public static readonly HashSet Queued = [ - (int)TransferStates.Queued, - (int)(TransferStates.Queued | TransferStates.Locally), - (int)(TransferStates.Queued | TransferStates.Remotely), + (int)TransferStates.Queued, // 2, in case of some sort of a malfunction or regression + (int)(TransferStates.Queued | TransferStates.Locally), // 2 | 2048 = 2050 + (int)(TransferStates.Queued | TransferStates.Remotely), // 2 | 4096 = 4098 ]; /// /// All states representing a transfer that is in progress: /// /// - /// - /// + /// (4) + /// (8) /// /// public static readonly HashSet InProgress = [ - (int)TransferStates.Initializing, - (int)TransferStates.InProgress, + (int)TransferStates.Initializing, // 4 + (int)TransferStates.InProgress, // 8 ]; } \ No newline at end of file -- cgit v1.2.3 From 37fd4e0a28de6249abd4e4dec15e22e10cf44936 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 16:38:52 -0600 Subject: use enums with categories instead of ints to avoid SQLite casting --- src/slskd/Application.cs | 4 +-- .../API/Controllers/TransfersController.cs | 4 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- .../Transfers/Types/TransferStateCategories.cs | 34 +++++++++++----------- src/slskd/Transfers/Uploads/UploadService.cs | 2 +- 5 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 6b66ec6e..c740bbad 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -316,7 +316,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 +327,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) { 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/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index bd3c83de..f894b963 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -36,8 +36,8 @@ public static class TransferStateCategories /// (16 | 32 = 48) /// /// - public static readonly HashSet Successful = [ - (int)(TransferStates.Completed | TransferStates.Succeeded) // 16 | 32 = 48 + public static readonly HashSet Successful = [ + TransferStates.Completed | TransferStates.Succeeded // 16 | 32 = 48 ]; /// @@ -51,12 +51,12 @@ public static class TransferStateCategories /// (16 | 1024 = 1040) /// /// - public static readonly HashSet Failed = [ - (int)(TransferStates.Completed | TransferStates.Cancelled), // 16 | 64 = 80 - (int)(TransferStates.Completed | TransferStates.TimedOut), // 16 | 128 = 144 - (int)(TransferStates.Completed | TransferStates.Errored), // 16 | 256 = 272 - (int)(TransferStates.Completed | TransferStates.Rejected), // 16 | 512 = 528 - (int)(TransferStates.Completed | TransferStates.Aborted), // 16 | 1024 = 1040 + public static readonly HashSet 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 ]; /// @@ -80,8 +80,8 @@ public static class TransferStateCategories /// (16 | 1024 = 1040) /// /// - public static readonly HashSet Completed = [ - (int)TransferStates.Completed, // 16, in case of some sort of a malfunction or regression + public static readonly HashSet Completed = [ + TransferStates.Completed, // 16, in case of some sort of a malfunction or regression .. Successful, .. Failed ]; @@ -95,10 +95,10 @@ public static class TransferStateCategories /// (2 | 4096 = 4098) /// /// - public static readonly HashSet Queued = [ - (int)TransferStates.Queued, // 2, in case of some sort of a malfunction or regression - (int)(TransferStates.Queued | TransferStates.Locally), // 2 | 2048 = 2050 - (int)(TransferStates.Queued | TransferStates.Remotely), // 2 | 4096 = 4098 + public static readonly HashSet 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 ]; /// @@ -109,8 +109,8 @@ public static class TransferStateCategories /// (8) /// /// - public static readonly HashSet InProgress = [ - (int)TransferStates.Initializing, // 4 - (int)TransferStates.InProgress, // 8 + public static readonly HashSet InProgress = [ + TransferStates.Initializing, // 4 + TransferStates.InProgress, // 8 ]; } \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index d75ccea3..67f71647 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -852,7 +852,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)); -- cgit v1.2.3 From 7b2deffc16b632b084750cd0be535a509ff3d253 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 16:39:13 -0600 Subject: log parameters and detailed errors when logging SQL --- src/slskd/Program.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 770c6746..9203dd37 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1295,7 +1295,10 @@ namespace slskd if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL) { - options.LogTo(Log.Debug, LogLevel.Information); + options + .EnableSensitiveDataLogging() + .EnableDetailedErrors() + .LogTo(Log.Debug, LogLevel.Information); } }); -- cgit v1.2.3 From 130449908748762449b41b93af45b884b5265255 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 16:39:39 -0600 Subject: add UserUploadStatistics and method to derive --- src/slskd/Transfers/Types/UserUploadStatistics.cs | 35 ++++++++++++++++ src/slskd/Transfers/Uploads/UploadService.cs | 51 +++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/slskd/Transfers/Types/UserUploadStatistics.cs 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 (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/. +// + +namespace slskd.Transfers; + +/// +/// Upload statistics, for use when evaluating incoming enqueue requests against configured limits. +/// +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 67f71647..fe2621c8 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -95,6 +95,14 @@ namespace slskd.Transfers.Uploads /// (int Files, long Bytes) Summarize(Expression> expression); + /// + /// Gets upload statistics for the specified . + /// + /// The username of the user. + /// An optional timestamp representing the current time in UTC. + /// The gathered statistics. + UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null); + /// /// Returns a list of all uploads matching the optional . /// @@ -919,6 +927,49 @@ namespace slskd.Transfers.Uploads context.SaveChanges(); } + /// + /// Gets upload statistics for the specified . + /// + /// The username of the user. + /// An optional timestamp representing the current time in UTC. + /// The gathered statistics. + public UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null) + { + utcNow ??= DateTime.UtcNow; + var dailyCutoff = utcNow.Value.AddDays(-1); + var weeklyCutoff = utcNow.Value.AddDays(-7); + + var failedStateIds = TransferStateCategories.Failed.ToList(); + var successState = TransferStates.Completed | TransferStates.Succeeded; + + using var context = ContextFactory.CreateDbContext(); + + 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, + + WeeklyFailedFiles = g.Count(t => t.StartedAt >= weeklyCutoff && failedStateIds.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 && failedStateIds.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); -- cgit v1.2.3 From f857168bdeb8a5607c2374f2aea47b506524a4c8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:31:25 -0600 Subject: final tweaks of GetUserStatistics --- src/slskd/Transfers/Uploads/UploadService.cs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index fe2621c8..bcc1dd90 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -939,11 +939,11 @@ namespace slskd.Transfers.Uploads var dailyCutoff = utcNow.Value.AddDays(-1); var weeklyCutoff = utcNow.Value.AddDays(-7); - var failedStateIds = TransferStateCategories.Failed.ToList(); - var successState = TransferStates.Completed | TransferStates.Succeeded; - 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) @@ -955,15 +955,20 @@ namespace slskd.Transfers.Uploads QueuedFiles = g.Count(t => t.EndedAt == null), QueuedBytes = g.Where(t => t.EndedAt == null).Sum(t => (long?)t.Size) ?? 0, - WeeklyFailedFiles = g.Count(t => t.StartedAt >= weeklyCutoff && failedStateIds.Contains(t.State)), + // 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, + 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 && failedStateIds.Contains(t.State)), + 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, + DailySucceededBytes = g.Where(t => t.StartedAt >= dailyCutoff && t.State == successState) + .Sum(t => (long?)t.Size) ?? 0, }) .FirstOrDefault(); -- cgit v1.2.3 From c807ee96e997b904419a95089365cb17ac372f9d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:34:41 -0600 Subject: add new indexes --- src/slskd/Transfers/TransfersDbContext.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index eac4935b..8c0b0eb5 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -70,6 +70,21 @@ namespace slskd.Transfers .Entity() .HasIndex(t => t.State) .HasDatabaseName("IDX_Transfers_State"); + + modelBuilder + .Entity() + .HasIndex(t => t.Username) + .HasDatabaseName("IDX_Transfers_Username"); + + modelBuilder + .Entity() + .HasIndex(t => t.Removed) + .HasDatabaseName("IDX_Transfers_Removed"); + + modelBuilder + .Entity() + .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size }) + .HasDatabaseName("IDX_Transfers_UserUploadStatistics"); } } } -- cgit v1.2.3 From 1144e602347277cc2abca3a4301dda5fb95a3346 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:34:56 -0600 Subject: tweak sql logging so debug isn't required --- src/slskd/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 9203dd37..2b2d2840 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1293,12 +1293,12 @@ namespace slskd options.UseSqlite(connectionString); options.AddInterceptors(new SqliteConnectionOpenedInterceptor()); - if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL) + if (OptionsAtStartup.Flags.LogSQL) { options .EnableSensitiveDataLogging() .EnableDetailedErrors() - .LogTo(Log.Debug, LogLevel.Information); + .LogTo(OptionsAtStartup.Debug ? Log.Debug : Log.Information, LogLevel.Information); } }); -- cgit v1.2.3 From 2e4411eb00e8192f41e92d57f500b56ced4dcc3f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:35:39 -0600 Subject: reduce enqueue semaphore to 10 (from 20) --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c740bbad..0ac92e31 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -224,7 +224,7 @@ namespace slskd private OptionsAtStartup OptionsAtStartup { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1); - private SemaphoreSlim EnqueueRequestRateLimiter { get; } = new SemaphoreSlim(20, 20); + private SemaphoreSlim EnqueueRequestRateLimiter { get; } = new SemaphoreSlim(10, 10); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } private DateTime SharesRefreshStarted { get; set; } -- cgit v1.2.3 From b082e89226234d00b73dcd753b301a70e2ac58bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:40:42 -0600 Subject: use stats query --- src/slskd/Application.cs | 101 +++++++++++++++++------------------------------ 1 file changed, 36 insertions(+), 65 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 0ac92e31..c462ca45 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -538,7 +538,6 @@ 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); @@ -623,45 +622,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 +682,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 +708,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,17 +730,16 @@ 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.RequestsAccepted.Inc(1); Metrics.Enqueue.ResponseLatency.Observe(stopwatch.ElapsedMilliseconds); Metrics.Enqueue.CurrentResponseLatency.Update(stopwatch.ElapsedMilliseconds); } -- cgit v1.2.3 From d29e74c2eafa0f97d12c33be1e22e444a7618bd4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:44:56 -0600 Subject: stub migration for new indexes --- ...Z12282025_AdditionalTransferIndexesMigration.cs | 98 ++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs 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..6beec9d3 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs @@ -0,0 +1,98 @@ +// +// 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/. +// + +namespace slskd.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Updates the Transfers table to add indexes on the Direction and State columns. +/// +public class Z12282025_AdditionalTransferIndexesMigration : IMigration +{ + public Z12282025_AdditionalTransferIndexesMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + 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 usernameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Username", StringComparison.OrdinalIgnoreCase)); + var removedExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Removed", StringComparison.OrdinalIgnoreCase)); + var statsExist = txfers.Any(c => c.Name.Equals("IDX_Transfers_UserUploadStatistics", StringComparison.OrdinalIgnoreCase)); + + if (usernameExists && removedExists && 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 + { + Log.Information("> Adding missing index(es) on the Transfers table..."); + + var usernameCommand = new SqliteCommand(@" + CREATE INDEX IF NOT EXISTS IDX_Transfers_Username ON Transfers (Username) + ", connection, transaction); + usernameCommand.ExecuteNonQuery(); + + var removedCommand = new SqliteCommand(@" + CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed) + ", connection, transaction); + removedCommand.ExecuteNonQuery(); + + var statsCommand = new SqliteCommand(@" + CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size) + ", connection, transaction); + statsCommand.ExecuteNonQuery(); + + Log.Information("> Index(es) created"); + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} -- cgit v1.2.3 From 05714b25d7f802e9d495bf179af2e19fb7750797 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Dec 2025 18:29:33 -0600 Subject: tweak logging --- src/slskd/Application.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c462ca45..ae6b7c0b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -742,12 +742,12 @@ namespace slskd Metrics.Enqueue.RequestsAccepted.Inc(1); Metrics.Enqueue.ResponseLatency.Observe(stopwatch.ElapsedMilliseconds); Metrics.Enqueue.CurrentResponseLatency.Update(stopwatch.ElapsedMilliseconds); + + Log.Information("Enqueue of {Filename} to {Username} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", filename, username, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds); } finally { EnqueueRequestRateLimiter.Release(); - - Log.Debug("EnqueueDownload for {Username}/{Filename} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", username, filename, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds); } } -- cgit v1.2.3 From 4af4974dbc5add4e3e66e9b9d7744f5d2bebec20 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Dec 2025 18:29:47 -0600 Subject: add username, filename index --- src/slskd/Transfers/TransfersDbContext.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 8c0b0eb5..f89530df 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -81,6 +81,14 @@ namespace slskd.Transfers .HasIndex(t => t.Removed) .HasDatabaseName("IDX_Transfers_Removed"); + // covers the ckeck for existing records when enqueueing uploads and downloads + modelBuilder + .Entity() + .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() .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size }) -- cgit v1.2.3 From 97a5ee6aa304ce645f0bf97a26c07cb35c873431 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Dec 2025 18:43:59 -0600 Subject: add new index --- ...Z12282025_AdditionalTransferIndexesMigration.cs | 27 ++++++++++------------ 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs index 6beec9d3..0c8d8b0c 100644 --- a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs @@ -43,9 +43,10 @@ public class Z12282025_AdditionalTransferIndexesMigration : IMigration var usernameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Username", StringComparison.OrdinalIgnoreCase)); 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 (usernameExists && removedExists && statsExist) + if (usernameExists && removedExists && usernameFilenameExists && statsExist) { return false; } @@ -68,22 +69,18 @@ public class Z12282025_AdditionalTransferIndexesMigration : IMigration try { - Log.Information("> Adding missing index(es) on the Transfers table..."); - - var usernameCommand = new SqliteCommand(@" - CREATE INDEX IF NOT EXISTS IDX_Transfers_Username ON Transfers (Username) - ", connection, transaction); - usernameCommand.ExecuteNonQuery(); + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } - var removedCommand = new SqliteCommand(@" - CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed) - ", connection, transaction); - removedCommand.ExecuteNonQuery(); + Log.Information("> Adding missing index(es) on the Transfers table..."); - var statsCommand = new SqliteCommand(@" - CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size) - ", connection, transaction); - statsCommand.ExecuteNonQuery(); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Username ON Transfers (Username)"); + 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(); -- cgit v1.2.3 From 9d868062e86f761f16d36a48a7a5f4951149114a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Dec 2025 18:48:15 -0600 Subject: wire up new migration --- src/slskd/Core/Data/Migrator.cs | 1 + 1 file changed, 1 insertion(+) 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) }, }; } -- cgit v1.2.3 From 3e04ab2c3c81ebee11178c1767d70476bfa3575f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:10:40 -0600 Subject: add counters for dropped and rejected requests, rename latency --- src/slskd/Telemetry/Metrics.cs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 33d2bc40..610ab9c6 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -128,8 +128,8 @@ public static class Metrics /// /// Gets a histogram representing the total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds. /// - 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,13 +139,23 @@ public static class Metrics /// /// Gets an EMA representing the average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds. /// - 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 => CurrentResponseLatencyGauge.Set(value)); /// /// Gets a counter representing the total number of incoming enqueue requests received. /// public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_received", "Total number of incoming enqueue requests received"); + /// + /// Gets a counter representing the total number of incoming enqueue requests dropped due to processing pressure. + /// + public static Counter RequestsDropped { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_dropped", "Total number of incoming enqueue requests dropped due to processing pressure"); + + /// + /// Gets a counter representing the total number of incoming enqueue requests rejected. + /// + public static Counter RequestsRejected { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_rejected", "Total number of incoming enqueue requests rejected"); + /// /// Gets a counter representing the total number of incoming enqueue requests accepted. /// @@ -154,10 +164,10 @@ public static class Metrics /// /// Gets a gauge representing the number of incoming enqueue requests waiting to be processed. /// - 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"); } /// -- cgit v1.2.3 From 870324657b842412a9af8268c65fac3ff56aa278 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:26:07 -0600 Subject: oops --- src/slskd/Telemetry/Metrics.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 610ab9c6..33550577 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -139,7 +139,7 @@ public static class Metrics /// /// Gets an EMA representing the average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds. /// - public static ExponentialMovingAverage CurrentLatency { 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)); /// /// Gets a counter representing the total number of incoming enqueue requests received. -- cgit v1.2.3 From 1adae6abf5035ac6271b124b106c6b386a3aaa83 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:26:28 -0600 Subject: toss checkpointer in --- src/slskd/Common/Logging/Checkpointer.cs | 94 ++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/slskd/Common/Logging/Checkpointer.cs 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 (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/. +// + +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().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 -- cgit v1.2.3 From d4bdc5be05c68288955ebc96bfd50d06ac8ca0d3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:26:50 -0600 Subject: remove redundant username --- .../Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs index 0c8d8b0c..1e85ee60 100644 --- a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs @@ -41,12 +41,11 @@ public class Z12282025_AdditionalTransferIndexesMigration : IMigration var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); var txfers = idxes["Transfers"]; - var usernameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Username", StringComparison.OrdinalIgnoreCase)); 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 (usernameExists && removedExists && usernameFilenameExists && statsExist) + if (removedExists && usernameFilenameExists && statsExist) { return false; } @@ -77,7 +76,6 @@ public class Z12282025_AdditionalTransferIndexesMigration : IMigration Log.Information("> Adding missing index(es) on the Transfers table..."); - Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Username ON Transfers (Username)"); 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)"); -- cgit v1.2.3 From 42d1647f0ec495ee8afa986d9061603c70be7374 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:31:10 -0600 Subject: add latency field --- src/slskd/Application.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index ae6b7c0b..d2bb1f3e 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( -- cgit v1.2.3 From 8b4a4d1d4c000192e068e5c78f3f9c18eb24d492 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:31:57 -0600 Subject: add semaphores --- src/slskd/Application.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index d2bb1f3e..c5b6450c 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -224,7 +224,9 @@ namespace slskd private OptionsAtStartup OptionsAtStartup { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1); - private SemaphoreSlim EnqueueRequestRateLimiter { get; } = new SemaphoreSlim(10, 10); + private SemaphoreSlim EnqueueSemaphore { get; } = new SemaphoreSlim(10, 10); + private SemaphoreSlim tUserEnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(1, 1); + private ConcurrentDictionary UserEnqueueSemaphores { get; } = new ConcurrentDictionary(); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } private DateTime SharesRefreshStarted { get; set; } -- cgit v1.2.3 From 1bb14575e70e5fd61091d8f1b94cec8de68c4461 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:38:24 -0600 Subject: acquire semaphores --- src/slskd/Application.cs | 101 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 92 insertions(+), 9 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c5b6450c..a08822da 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -224,8 +224,8 @@ namespace slskd private OptionsAtStartup OptionsAtStartup { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1); - private SemaphoreSlim EnqueueSemaphore { get; } = new SemaphoreSlim(10, 10); - private SemaphoreSlim tUserEnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(1, 1); + private SemaphoreSlim GlobalEnqueueSemaphore { get; } = new SemaphoreSlim(10, 10); + private SemaphoreSlim UserEnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(1, 1); private ConcurrentDictionary UserEnqueueSemaphores { get; } = new ConcurrentDictionary(); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } @@ -544,24 +544,78 @@ namespace slskd { 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 + + 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; - Metrics.Enqueue.CurrentRequestQueueDepth.Set(EnqueueRequestQueueDepth); + await GlobalEnqueueSemaphore.WaitAsync(); + enqueueRequestsSemaphoreAcquired = true; + } + finally + { + Interlocked.Decrement(ref EnqueueQueueDepth); + Metrics.Enqueue.CurrentQueueDepth.Set(EnqueueQueueDepth); + } stopwatch.Start(); @@ -1034,6 +1088,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) @@ -1744,5 +1801,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 -- cgit v1.2.3 From 2100d773a653bf2bd49e5cb53d649744fc44c387 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:39:12 -0600 Subject: release semaphores if they were acquired --- src/slskd/Application.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a08822da..f5a15be1 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -803,7 +803,15 @@ namespace slskd } finally { - EnqueueRequestRateLimiter.Release(); + if (userSemaphoreAcquired) + { + userSemaphore.Release(); + } + + if (enqueueRequestsSemaphoreAcquired) + { + GlobalEnqueueSemaphore.Release(); + } } } -- cgit v1.2.3 From be5bd15dad2fb849b8c7358a87ed04f86b861730 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:39:30 -0600 Subject: report decision stats in finally --- src/slskd/Application.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index f5a15be1..df01206f 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -803,6 +803,16 @@ namespace slskd } finally { + 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(); -- cgit v1.2.3 From 9609f2555ad62ffa18590bd4a59dce49de991cb7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:39:47 -0600 Subject: report rejected metric in catch --- src/slskd/Application.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index df01206f..61a72b4e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -801,6 +801,11 @@ namespace slskd 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 { if (decisionStopwatch.IsRunning) -- cgit v1.2.3 From 048e15393491fb2514c83c098c150e4527f97df7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:40:16 -0600 Subject: update full metrics --- src/slskd/Application.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 61a72b4e..52ca4f86 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -788,16 +788,16 @@ namespace slskd decisionStopwatch.Stop(); - Metrics.Enqueue.DecisionLatency.Observe(decisionStopwatch.ElapsedMilliseconds); - Metrics.Enqueue.CurrentDecisionLatency.Update(decisionStopwatch.ElapsedMilliseconds); - 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.ResponseLatency.Observe(stopwatch.ElapsedMilliseconds); - Metrics.Enqueue.CurrentResponseLatency.Update(stopwatch.ElapsedMilliseconds); + 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); } -- cgit v1.2.3 From 9e7744c2507ef46d897741621f65e4f7b7de77f1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Jan 2026 18:24:54 -0600 Subject: remove Username index --- src/slskd/Transfers/TransfersDbContext.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index f89530df..b67bd47a 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -71,11 +71,6 @@ namespace slskd.Transfers .HasIndex(t => t.State) .HasDatabaseName("IDX_Transfers_State"); - modelBuilder - .Entity() - .HasIndex(t => t.Username) - .HasDatabaseName("IDX_Transfers_Username"); - modelBuilder .Entity() .HasIndex(t => t.Removed) -- cgit v1.2.3 From a3605e662815002085a5ab2c51ea459508d2c77f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Jan 2026 18:44:03 -0600 Subject: Update src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs index 1e85ee60..2deffeb3 100644 --- a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs @@ -23,7 +23,7 @@ using Microsoft.Data.Sqlite; using Serilog; /// -/// Updates the Transfers table to add indexes on the Direction and State columns. +/// Adds additional indexes to the Transfers table for Removed, Username/Filename, and user upload statistics. /// public class Z12282025_AdditionalTransferIndexesMigration : IMigration { -- cgit v1.2.3 From 52d5509119d8c83bc96adc0205ecc7c1692cbb56 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Jan 2026 18:45:23 -0600 Subject: Update src/slskd/Transfers/TransfersDbContext.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Transfers/TransfersDbContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index b67bd47a..422595e9 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -76,7 +76,7 @@ namespace slskd.Transfers .HasIndex(t => t.Removed) .HasDatabaseName("IDX_Transfers_Removed"); - // covers the ckeck for existing records when enqueueing uploads and downloads + // covers the check for existing records when enqueueing uploads and downloads modelBuilder .Entity() .HasIndex(t => new { t.Username, t.Filename }) -- cgit v1.2.3 From e340124d58d08785d8ef046b9374ca1413b73d3b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Jan 2026 18:45:36 -0600 Subject: Update src/slskd/Transfers/Types/TransferStateCategories.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Transfers/Types/TransferStateCategories.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index f894b963..5ccbe572 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -92,7 +92,7 @@ public static class TransferStateCategories /// /// (2) /// (2 | 2048 = 2050) - /// (2 | 4096 = 4098) + /// (2 | 4096 = 4098) /// /// public static readonly HashSet Queued = [ -- cgit v1.2.3 From 07d33d57d6af59699d5ef322b7710d214f69d3cc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 13:21:52 -0600 Subject: add security policy --- SECURITY.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..f186b0db --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +Please report security vulnerabilities via email to security@slskd.org. \ No newline at end of file -- cgit v1.2.3 From f2d6e478a443e813ff2b31a199b93e44e71a0cd7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 13:40:06 -0600 Subject: update CONTRIBUTING --- CONTRIBUTING.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1c65af07..9ffedd08 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,26 +1,28 @@ # Contributing -When contributing to this repository, please first discuss the change you wish to make via issue, -email, or any other method with the owners of this repository before making a change. +All contributions must first have been discussed within an Issue or Discussion. -We don't maintain a Contributor License Agreement (CLA) but we do require that anyone that wishes to contribute agrees to the following: +Pull Requests opened without an accompanying Issue are considered to be unsolicited, and unsolicited Pull Requests may be rejected without review or converted into an Issue. -* You have the right to assign the copyright of your contribution. -* By making your contribution, you are giving up copyright of your contribution. +## Copyright -This application is released under the [AGPL 3.0](https://github.com/slskd/slskd/blob/master/LICENSE) license, and no single individual or entity owns -or will ever own the copyright. +By submitting a contribution to this project, you agree to the following: + +* You have the legal right to make this contribution and to assign its copyright. +* You irrevocably assign all copyright and related rights in your contribution to the project maintainer(s). +* You grant the project maintainer(s) the right to use, modify, distribute, and relicense your contribution under any license of their choosing. + +This application is currently released under the [AGPL 3.0](https://github.com/slskd/slskd/blob/master/LICENSE) license. ## Contribution Workflow -1. Assign yourself to the issue that you'll be working on. If you'd like to contribute something for which there is no - existing issue, consider creating one before you start so we can discuss. -1. Clone the repository and `git checkout master` to ensure you are on the master branch. +1. Comment on the Issue you'll be working on so others know you're working on it. You may also ask a maintainer to assign it to you. +1. Fork the repository, then clone it and run `git checkout master` to ensure you are on the master branch. 1. Create a new branch for your change with `git checkout -b ` be descriptive, but terse. 1. Make your changes. When finished, push your branch with `git push origin --set-upstream `. -1. Create a pull request to merge `` into `master`. -1. A maintainer will review your pull request and may make comments, ask questions, or request changes. When all - feedback has been addressed the pull request will be approved, and after all checks have passed it will be merged by +1. Create a Pull Request in the source repository to merge `` into `master`. +1. A maintainer will review your Pull Request and may make comments, ask questions, or request changes. When all + feedback has been addressed the Pull Request will be approved, and after all checks have passed it will be merged by a maintainer, or you may merge it yourself if you have the necessary access. 1. Delete your branch, unless you plan to submit additional pull request from it. -- cgit v1.2.3 From 91eb4a950965c95adeeb98b60d31ad32164adc4c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 13:51:21 -0600 Subject: add AI clause --- .github/ISSUE_TEMPLATE/bug_report.yml | 54 ++++++++++++++++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 5 +++ .github/ISSUE_TEMPLATE/feature_request.yml | 24 +++++++++++++ CONTRIBUTING.md | 14 ++++++-- 4 files changed, 94 insertions(+), 3 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 00000000..e857f7ca --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,54 @@ +name: Bug Report +description: Something is broken or doesn't work as expected +labels: ['needs triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + options: + - label: I have searched for existing issues (both open and closed) + required: true +- type: textarea + attributes: + label: Describe the Bug + description: A concise description of what you're experiencing. + validations: + required: true +- type: textarea + attributes: + label: Steps To Reproduce + description: Steps to reproduce the behavior. + placeholder: | + 1. In this environment... + 2. With this config... + 3. Run '...' + 4. See error... + validations: + required: false +- type: textarea + attributes: + label: Environment + description: | + examples: + - **OS**: Ubuntu 22.04 + - **slskd**: 0.24.0 + - **Docker Install?**: Yes + - **Filesystem**: ext4 + - **Hardware**: Raspberry Pi 5 4gb + value: | + - OS: + - slskd: + - Docker Install?: + - Filesystem: + - Hardware: + render: markdown + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? Screenshots? References? Anything that will give us more context about the issue you are encountering! + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..8bec6cd6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Support via Discord + url: https://discord.gg/GjDW5r8u + about: Chat with users and devs on support and setup related topics. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 00000000..f01bcb25 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,24 @@ +name: Feature Request +description: Suggest a feature for slskd +labels: ['needs triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + options: + - label: I have searched for existing issues (both open and closed) + required: true +- type: textarea + attributes: + label: Describe the Feature + description: A concise description of the feature you'd like to be added. + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? Screenshots? References? Anything that will give us more context about the feature you are suggesting! + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9ffedd08..73ebce45 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,6 @@ # Contributing -All contributions must first have been discussed within an Issue or Discussion. - -Pull Requests opened without an accompanying Issue are considered to be unsolicited, and unsolicited Pull Requests may be rejected without review or converted into an Issue. +All contributions must have first been discussed within an Issue or Discussion. Pull Requests opened without an accompanying Issue are considered to be unsolicited, and unsolicited Pull Requests may be rejected without review and/or converted into an Issue. ## Copyright @@ -14,6 +12,16 @@ By submitting a contribution to this project, you agree to the following: This application is currently released under the [AGPL 3.0](https://github.com/slskd/slskd/blob/master/LICENSE) license. +## Use of AI in Contributions + +If you used AI tools (such as ChatGPT, Copilot, Claude, etc.) to assist with your contribution, you must clearly disclose this in your Pull Request, including: + +* Which AI tool(s) you used +* How you used them (e.g., code generation, refactoring suggestions, documentation help) +* Which parts of your contribution were AI-assisted + +Contributors are expected to fully understand and take responsibility for all code they submit, regardless of how it was produced. Contributions made entirely by AI are not welcome and will be rejected. + ## Contribution Workflow 1. Comment on the Issue you'll be working on so others know you're working on it. You may also ask a maintainer to assign it to you. -- cgit v1.2.3 From 8d27bf1c9b4498b8808159c5525f603ab7faa38d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 13:58:43 -0600 Subject: add coc --- CODE_OF_CONDUCT.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..2c7b7aa6 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,5 @@ +# Code of Conduct + +[Be excellent to each other](https://www.youtube.com/watch?v=rph_1DODXDU), and especially to maintainers. + +The definition of excellence is at the sole discretion of the maintainers. \ No newline at end of file -- cgit v1.2.3 From a1ca1bb0b2e0635999739aed6b1fcd2329c28b2a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 14:12:40 -0600 Subject: add PR template --- .github/PULL_REQUEST_TEMPLATE.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..a46d48d6 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,29 @@ + \ No newline at end of file -- cgit v1.2.3 From 02df53f215a57c58d78df20a03497f03cce12185 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 14:13:51 -0600 Subject: remove disclaimer --- README.md | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/README.md b/README.md index 2d9897c1..e23bea3f 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,3 @@ -> [!WARNING] -> This is the only official repository for slskd. -> -> Official releases are published via: -> * Build artifacts from the [GitHub Actions](github.com/slskd/slskd/actions) of this repository -> * Platform-specific archives located in [Releases](https://github.com/slskd/slskd/releases/) -> * Docker images published to [Docker Hub](https://hub.docker.com/r/slskd/slskd) and [GitHub Container Registry](https://github.com/slskd/slskd/pkgs/container/slskd) -> -> The name associated with official releases is `slskd`. Any change to this will be clearly communicated here. -> -> If you encounter binaries with different names claiming to be slskd or an alternative, they are not affiliated with this project. -> -> Be cautious of unaffiliated forks that automatically mirror this repository and re-release binaries under different names. These forks are not reviewed, endorsed, or supported by the slskd maintainers, and may introduce changes that compromise security, privacy, or network integrity. -> As with any software, verify the source of binaries before running them. Supply chain attacks via unofficial forks are a real risk—if you didn't get it from this repository, you can't be certain what you're running. - # slskd [![Build](https://img.shields.io/github/actions/workflow/status/slskd/slskd/ci.yml?branch=master&logo=github)](https://github.com/slskd/slskd/actions/workflows/ci.yml) -- cgit v1.2.3 From 4f28547419971338afe679e129da87fbd39aa35a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 9 Jan 2026 08:40:41 -0600 Subject: add Failed retention setting, add more states to errored cleanup --- config/slskd.example.yml | 2 ++ src/slskd/Application.cs | 14 ++++++++------ src/slskd/Core/Options.cs | 6 ++++++ 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 66379626..b8723f4d 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -169,10 +169,12 @@ # succeeded: 1440 # 1 day, in minutes # errored: 30 # cancelled: 5 +# failed: 180 # any unsuccessful transfer, including errored and cancelled # download: # succeeded: 1440 # 1 day, in minutes # errored: 20160 # 2 weeks, in minutes # cancelled: 5 +# failed: 180 # any unsuccessful transfer, including errored and cancelled # files: # complete: 20160 # 2 weeks, in minutes # incomplete: 43200 # 30 days, in minutes diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 52ca4f86..a93afafe 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1226,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)]); } } @@ -1246,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 { diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 20b53f6c..a1d9953c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1423,6 +1423,12 @@ namespace slskd /// [Range(5, maximum: int.MaxValue)] public int? Cancelled { get; init; } = null; + + /// + /// Gets the time to retain unsuccessful (including errored and cancelled) transfers, in minutes. + /// + [Range(5, maximum: int.MaxValue)] + public int? Failed { get; init; } = null; } } -- cgit v1.2.3 From cb31a68a6e7f6d195281a7a480af539ddd945688 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 9 Jan 2026 08:43:38 -0600 Subject: update retention docs --- docs/config.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/config.md b/docs/config.md index 3efe2e8a..c47235af 100644 --- a/docs/config.md +++ b/docs/config.md @@ -950,7 +950,7 @@ By default, most things created by the application are retained indefinitely; th Completed searches can be configured to be removed from the UI and 'hard' deleted from the database. It's a good idea to set this to something relatively short, as old searches have diminishing value as they age and the records contain a lot of data. -Transfers can be configured to be removed from the UI after they are complete by specifying retention periods for uploads and downloads separately, and by transfer state; succeeded, errored, and cancelled. +Transfers can be configured to be removed from the UI after they are complete by specifying retention periods for uploads and downloads separately, and by transfer state; succeeded, errored, and cancelled. The 'failed' setting can be used instead of 'errored' and 'cancelled' to clean up all transfers that were not successful, regardless of reason. Files (on disk) can be configured to be deleted after the age of their last access time exceeds the configured time. Completed and incomplete files can be configured separately. @@ -967,10 +967,12 @@ retention: succeeded: 1440 # 1 day errored: 30 cancelled: 5 + failed: 180 download: succeeded: 1440 # 1 day errored: 20160 # 2 weeks cancelled: 5 + failed: 180 files: complete: 20160 # 2 weeks incomplete: 43200 # 30 days -- cgit v1.2.3