From 1378c0498a2206ebc0cc39045f6f1bc330a22ce6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 18 Dec 2025 08:47:03 -0600 Subject: emit enqueue metrics --- src/slskd/Application.cs | 42 ++++++++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 10 deletions(-) (limited to 'src/slskd/Application.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 1a18790f..97d3392c 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -40,7 +40,6 @@ namespace slskd using Serilog.Events; using slskd.Configuration; using slskd.Core.API; - using slskd.Events; using slskd.Files; using slskd.Integrations.Pushbullet; using slskd.Messaging; @@ -83,6 +82,12 @@ 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; +#pragma warning restore SA1306 // Field names should begin with lower-case letter + + public Application( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, @@ -537,20 +542,28 @@ 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)) + { + Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address); + throw new DownloadEnqueueException("File not shared."); + } + var stopwatch = new Stopwatch(); var decisionStopwatch = new Stopwatch(); + Interlocked.Increment(ref EnqueueRequestQueueDepth); + await EnqueueRequestRateLimiter.WaitAsync(); try { - stopwatch.Start(); + 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."); - } + Metrics.Enqueue.CurrentRequestQueueDepth.Set(EnqueueRequestQueueDepth); + + stopwatch.Start(); // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file // it helps, too, that this will tell us whether the file is even shared. @@ -747,12 +760,21 @@ namespace slskd } await Transfers.Uploads.EnqueueAsync(username, filename); - } - finally - { + + Metrics.Enqueue.RequestsAccepted.Inc(1); + decisionStopwatch.Stop(); + + Metrics.Enqueue.DecisionLatency.Observe(decisionStopwatch.ElapsedMilliseconds); + Metrics.Enqueue.CurrentDecisionLatency.Update(decisionStopwatch.ElapsedMilliseconds); + stopwatch.Stop(); + Metrics.Enqueue.ResponseLatency.Observe(stopwatch.ElapsedMilliseconds); + Metrics.Enqueue.CurrentResponseLatency.Update(stopwatch.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 d36b9703df5cbd498540ee941c1149b0ae851a8f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 25 Dec 2025 18:47:02 -0600 Subject: use categories for pruning --- src/slskd/Application.cs | 4 ++-- src/slskd/Transfers/Downloads/DownloadService.cs | 18 ++++++++++-------- src/slskd/Transfers/Uploads/UploadService.cs | 18 ++++++++++-------- 3 files changed, 22 insertions(+), 18 deletions(-) (limited to 'src/slskd/Application.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 97d3392c..31b99e3b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1178,7 +1178,7 @@ namespace slskd { if (age.HasValue) { - Transfers.Uploads.Prune(age.Value, TransferStates.Completed | state); + Transfers.Uploads.Prune(age.Value, (int)(TransferStates.Completed | state)); } } @@ -1186,7 +1186,7 @@ namespace slskd { if (age.HasValue) { - Transfers.Downloads.Prune(age.Value, TransferStates.Completed | state); + Transfers.Downloads.Prune(age.Value, (int)(TransferStates.Completed | state)); } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9bc25373..54fed035 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -89,9 +89,9 @@ namespace slskd.Transfers.Downloads /// Removes downloads older than the specified . /// /// The age after which downloads are eligible for pruning, in hours. - /// An optional, additional state by which downloads are filtered for pruning. + /// One or more states by which downloads are filtered for pruning. /// The number of pruned downloads. - int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed); + int Prune(int age, params int[] states); /// /// Removes the download matching the specified . @@ -663,13 +663,15 @@ namespace slskd.Transfers.Downloads /// Removes downloads older than the specified . /// /// The age after which downloads are eligible for pruning, in hours. - /// An optional, additional state by which downloads are filtered for pruning. + /// One or more states by which downloads are filtered for pruning. /// The number of pruned downloads. - public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) + public int Prune(int age, params int[] states) { - if (!stateHasFlag.HasFlag(TransferStates.Completed)) + var statesSet = new HashSet(states); + + if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed))) { - throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); + throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states)); } try @@ -682,7 +684,7 @@ namespace slskd.Transfers.Downloads .Where(t => t.Direction == TransferDirection.Download) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - .Where(t => t.State == stateHasFlag) + .Where(t => statesSet.Contains((int)t.State)) .ToList(); foreach (var tx in expired) @@ -694,7 +696,7 @@ namespace slskd.Transfers.Downloads if (pruned > 0) { - Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, stateHasFlag); + Log.Debug("Pruned {Count} expired downloads with states {States}", pruned, statesSet); } return pruned; diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index c96d1131..e6988ce0 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -107,9 +107,9 @@ namespace slskd.Transfers.Uploads /// Removes uploads older than the specified . /// /// The age after which uploads are eligible for pruning, in minutes. - /// An optional, additional state by which uploads are filtered for pruning. + /// One or more states by which uploads are filtered for pruning. /// The number of pruned uploads. - int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed); + int Prune(int age, params int[] states); /// /// Removes the upload matching the specified . @@ -780,13 +780,15 @@ namespace slskd.Transfers.Uploads /// Removes uploads older than the specified . /// /// The age after which uploads are eligible for pruning, in minutes. - /// An optional, additional state by which uploads are filtered for pruning. + /// One or more states by which uploads are filtered for pruning. /// The number of pruned uploads. - public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) + public int Prune(int age, params int[] states) { - if (!stateHasFlag.HasFlag(TransferStates.Completed)) + var statesSet = new HashSet(states); + + if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed))) { - throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); + throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states)); } try @@ -799,7 +801,7 @@ namespace slskd.Transfers.Uploads .Where(t => t.Direction == TransferDirection.Upload) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - .Where(t => t.State.HasFlag(stateHasFlag)) + .Where(t => statesSet.Contains((int)t.State)) .ToList(); foreach (var tx in expired) @@ -811,7 +813,7 @@ namespace slskd.Transfers.Uploads if (pruned > 0) { - Log.Debug("Pruned {Count} expired uploads with state {State}", pruned, stateHasFlag); + Log.Debug("Pruned {Count} expired uploads with states {States}", pruned, statesSet); } return pruned; -- cgit v1.2.3 From 35453533cfc25be782f0d1111af3fb67edff90ee Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 18:20:06 -0600 Subject: move cast down --- src/slskd/Application.cs | 5 ++--- src/slskd/Transfers/Downloads/DownloadService.cs | 6 +++--- src/slskd/Transfers/Uploads/UploadService.cs | 6 +++--- 3 files changed, 8 insertions(+), 9 deletions(-) (limited to 'src/slskd/Application.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 31b99e3b..6b66ec6e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -87,7 +87,6 @@ namespace slskd private static int EnqueueRequestQueueDepth = 0; #pragma warning restore SA1306 // Field names should begin with lower-case letter - public Application( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, @@ -1178,7 +1177,7 @@ namespace slskd { if (age.HasValue) { - Transfers.Uploads.Prune(age.Value, (int)(TransferStates.Completed | state)); + Transfers.Uploads.Prune(age.Value, TransferStates.Completed | state); } } @@ -1186,7 +1185,7 @@ namespace slskd { if (age.HasValue) { - Transfers.Downloads.Prune(age.Value, (int)(TransferStates.Completed | state)); + Transfers.Downloads.Prune(age.Value, TransferStates.Completed | state); } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 289bcb40..f62af711 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -91,7 +91,7 @@ namespace slskd.Transfers.Downloads /// The age after which downloads are eligible for pruning, in hours. /// One or more states by which downloads are filtered for pruning. /// The number of pruned downloads. - int Prune(int age, params int[] states); + int Prune(int age, params TransferStates[] states); /// /// Removes the download matching the specified . @@ -679,9 +679,9 @@ namespace slskd.Transfers.Downloads /// The age after which downloads are eligible for pruning, in hours. /// One or more states by which downloads are filtered for pruning. /// The number of pruned downloads. - public int Prune(int age, params int[] states) + public int Prune(int age, params TransferStates[] states) { - var statesSet = new HashSet(states); + var statesSet = new HashSet(states.Select(s => (int)s)); if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed))) { diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 87899d78..a30bb87f 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -109,7 +109,7 @@ namespace slskd.Transfers.Uploads /// The age after which uploads are eligible for pruning, in minutes. /// One or more states by which uploads are filtered for pruning. /// The number of pruned uploads. - int Prune(int age, params int[] states); + int Prune(int age, params TransferStates[] states); /// /// Removes the upload matching the specified . @@ -791,9 +791,9 @@ namespace slskd.Transfers.Uploads /// The age after which uploads are eligible for pruning, in minutes. /// One or more states by which uploads are filtered for pruning. /// The number of pruned uploads. - public int Prune(int age, params int[] states) + public int Prune(int age, params TransferStates[] states) { - var statesSet = new HashSet(states); + var statesSet = new HashSet(states.Select(s => (int)s)); if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed))) { -- 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(-) (limited to 'src/slskd/Application.cs') 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 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(-) (limited to 'src/slskd/Application.cs') 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(-) (limited to 'src/slskd/Application.cs') 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 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(-) (limited to 'src/slskd/Application.cs') 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 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(-) (limited to 'src/slskd/Application.cs') 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(-) (limited to 'src/slskd/Application.cs') 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(-) (limited to 'src/slskd/Application.cs') 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(-) (limited to 'src/slskd/Application.cs') 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(+) (limited to 'src/slskd/Application.cs') 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(+) (limited to 'src/slskd/Application.cs') 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(-) (limited to 'src/slskd/Application.cs') 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 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(-) (limited to 'src/slskd/Application.cs') 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