From 52a6cb47b7dd5944a9f0f5048f93eaf4d822a57c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Jan 2026 16:30:41 -0600 Subject: reorganize search metrics, add a few --- src/slskd/Telemetry/Metrics.cs | 76 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 66 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 33550577..76b6c7e0 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -35,6 +35,26 @@ public static class Metrics /// public static class Search { + /// + /// Gets a counter representing the total number of search requests received. + /// + public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_received", "Total number of search requests received"); + + /// + /// Gets an automatically resetting counter of the number of search requests received. + /// + public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count)); + + /// + /// Gets a counter representing the total number of search responses sent. + /// + public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_responses_sent", "Total number of search responses sent"); + + /// + /// Gets an automatically resetting counter of the number of search responses sent. + /// + public static TimedCounter CurrentResponseSendRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentResponseSendRateGauge.Set(count)); + /// /// Gets a histogram representing the time taken to resolve a response to an incoming search request, in milliseconds. /// @@ -51,23 +71,59 @@ public static class Metrics /// public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); - /// - /// Gets an automatically resetting counter of the number of search requests received. - /// - public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count)); + private static Gauge CurrentResponseLatencyGauge { get; } = + Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve and send a response to an incoming search request, in milliseconds"); + private static Gauge CurrentRequestReceiveRateGauge { get; } = + Prometheus.Metrics.CreateGauge("slskd_search_request_receive_rate_current", "Number of search requests received in the last minute"); + private static Gauge CurrentResponseSendRateGauge { get; } = + Prometheus.Metrics.CreateGauge("slskd_search_response_send_rate_current", "Number of search responses sent in the last minute"); /// - /// Gets a counter representing the total number of search requests received. + /// Metrics related to the filtering of incoming search requests. /// - public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_received", "Total number of search requests received"); + public static class Filter + { + /// + /// Gets a histogram representing the time taken to apply filters to an incoming search request, in milliseconds. + /// + public static Histogram Latency { get; } = Prometheus.Metrics.CreateHistogram( + "slskd_search_filter_latency", + "The time taken to apply filters to an incoming search request, in milliseconds", + new HistogramConfiguration + { + Buckets = Histogram.ExponentialBuckets(0.1, 2, 11), + }); + + /// + /// Gets an EMA representing the average time taken to apply filters to an incoming search request, in milliseconds. + /// + public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentLatencyGauge.Set(value)); + + private static Gauge CurrentLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_filter_latency_current", "The average time taken to apply filters to an incoming search request, in milliseconds"); + } /// - /// Gets a counter representing the total number of search responses sent. + /// Metrics related to the querying of shares for search results. /// - public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_responses_sent", "Total number of search responses sent"); + public static class Query + { + /// + /// Gets a histogram representing the time taken to perform a share search, in milliseconds. + /// + public static Histogram Latency { get; } = Prometheus.Metrics.CreateHistogram( + "slskd_search_query_latency", + "The time taken to query share database(s) for results, in milliseconds", + new HistogramConfiguration + { + Buckets = Histogram.ExponentialBuckets(0.1, 2, 11), + }); - private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve a response to an incoming search request, in milliseconds"); - private static Gauge CurrentRequestReceiveRateGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_request_receive_rate_current", "Number of search requests received in the last second"); + /// + /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds. + /// + public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentLatencyGauge.Set(value)); + private static Gauge CurrentLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_query_latency_current", "The average time taken to query share database(s) for results, in milliseconds"); + } } /// -- cgit v1.2.3 From ae99e0b92a092e74590c4ea0143cfb5584c36fe1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Jan 2026 16:30:57 -0600 Subject: instrument search responses --- src/slskd/Application.cs | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a93afafe..ba9755c0 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1552,6 +1552,9 @@ namespace slskd Metrics.Search.RequestsReceived.Inc(1); Metrics.Search.CurrentRequestReceiveRate.CountUp(1); + var sw = new Stopwatch(); + sw.Start(); + if (Users.IsBlacklisted(username)) { return null; @@ -1569,21 +1572,23 @@ namespace slskd return null; } + var filterLatency = sw.ElapsedMilliseconds; + Metrics.Search.Filter.Latency.Observe(filterLatency); + Metrics.Search.Filter.CurrentLatency.Update(filterLatency); + try { - var sw = new Stopwatch(); - sw.Start(); - // append the list of excluded search phrases supplied by the server // see https://github.com/jpdillingham/Soulseek.NET/issues/803 var queryWithExclusionsApplied = new SearchQuery(terms: query.Terms, exclusions: query.Exclusions.Concat(ExcludedSearchPhrases).Distinct()); var results = await Shares.SearchAsync(queryWithExclusionsApplied); - sw.Stop(); + var queryLatency = sw.ElapsedMilliseconds - filterLatency; + Metrics.Search.Query.Latency.Observe(queryLatency); + Metrics.Search.Query.CurrentLatency.Update(queryLatency); - Metrics.Search.ResponseLatency.Observe(sw.ElapsedMilliseconds); - Metrics.Search.CurrentResponseLatency.Update(sw.ElapsedMilliseconds); + SearchResponse response = null; if (results.Any()) { @@ -1611,7 +1616,7 @@ namespace slskd Metrics.Search.ResponsesSent.Inc(1); - return new SearchResponse( + response = new SearchResponse( Client.Username, token, uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed, @@ -1620,9 +1625,20 @@ namespace slskd fileList: results); } + sw.Stop(); + + Metrics.Search.ResponseLatency.Observe(sw.ElapsedMilliseconds); + Metrics.Search.CurrentResponseLatency.Update(sw.ElapsedMilliseconds); + + if (response is not null) + { + Metrics.Search.ResponsesSent.Inc(1); + Metrics.Search.CurrentResponseSendRate.CountUp(1); + } + // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no // response will be sent to the requestor. - return null; + return response; } catch (Exception ex) { -- cgit v1.2.3 From 84141d4d30390613d7a0266bc10d4a0b1c3d0384 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 17 Jan 2026 18:38:46 -0600 Subject: add metrics to track dropped searches --- src/slskd/Telemetry/Metrics.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 76b6c7e0..2d5b40e5 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -45,6 +45,16 @@ public static class Metrics /// public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count)); + /// + /// Gets a counter representing the total number of search requests dropped due to processing pressure. + /// + public static Counter RequestsDropped { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_dropped", "Total number of search requests dropped due to processing pressure"); + + /// + /// Gets an automatically resetting counter of the number of search requests dropped due to processing pressure. + /// + public static TimedCounter CurrentRequestDropRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestDropRateGauge.Set(count)); + /// /// Gets a counter representing the total number of search responses sent. /// @@ -75,6 +85,8 @@ public static class Metrics Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve and send a response to an incoming search request, in milliseconds"); private static Gauge CurrentRequestReceiveRateGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_request_receive_rate_current", "Number of search requests received in the last minute"); + private static Gauge CurrentRequestDropRateGauge { get; } = + Prometheus.Metrics.CreateGauge("slskd_search_request_drop_rate_current", "Number of search requests dropped in the last minute"); private static Gauge CurrentResponseSendRateGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_response_send_rate_current", "Number of search responses sent in the last minute"); -- cgit v1.2.3 From c87476175285a84196075ebc8a9b388169d8c34a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 11:47:28 -0600 Subject: tweak descriptions --- src/slskd/Telemetry/Metrics.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 2d5b40e5..d0592a68 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -66,11 +66,11 @@ public static class Metrics public static TimedCounter CurrentResponseSendRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentResponseSendRateGauge.Set(count)); /// - /// Gets a histogram representing the time taken to resolve a response to an incoming search request, in milliseconds. + /// Gets a histogram representing the time taken to resolve and return a response to an incoming search request, in milliseconds. /// public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram( "slskd_search_response_latency", - "The time taken to resolve a response to an incoming search request, in milliseconds", + "The time taken to resolve and return a response to an incoming search request, in milliseconds", new HistogramConfiguration { Buckets = Histogram.ExponentialBuckets(0.1, 2, 11), @@ -82,7 +82,7 @@ public static class Metrics public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); private static Gauge CurrentResponseLatencyGauge { get; } = - Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve and send a response to an incoming search request, in milliseconds"); + Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve and return a response to an incoming search request, in milliseconds"); private static Gauge CurrentRequestReceiveRateGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_request_receive_rate_current", "Number of search requests received in the last minute"); private static Gauge CurrentRequestDropRateGauge { get; } = @@ -120,7 +120,7 @@ public static class Metrics public static class Query { /// - /// Gets a histogram representing the time taken to perform a share search, in milliseconds. + /// Gets a histogram representing the time taken to query share database(s) for results, in milliseconds. /// public static Histogram Latency { get; } = Prometheus.Metrics.CreateHistogram( "slskd_search_query_latency", @@ -131,7 +131,7 @@ public static class Metrics }); /// - /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds. + /// Gets an EMA representing the average time taken to query share database(s) for results, in milliseconds. /// public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentLatencyGauge.Set(value)); private static Gauge CurrentLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_query_latency_current", "The average time taken to query share database(s) for results, in milliseconds"); -- cgit v1.2.3 From 572aa0502b325fc9657eef774f034a43a7078e1a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 13:23:44 -0600 Subject: add throttling options --- src/slskd/Core/Options.cs | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 68fa4d92..53c94303 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -282,6 +282,12 @@ namespace slskd [Validate] public RetentionOptions Retention { get; init; } = new RetentionOptions(); + /// + /// Gets throttling options. + /// + [Validate] + public ThrottlingOptions Throttling { get; init; } = new ThrottlingOptions(); + /// /// Gets logger options. /// @@ -1461,6 +1467,52 @@ namespace slskd } } + /// + /// Throttling options. + /// + public class ThrottlingOptions + { + /// + /// Gets search throttling options. + /// + [Validate] + public SearchThrottlingOptions Search { get; init; } = new SearchThrottlingOptions(); + + /// + /// Search throttling options. + /// + public class SearchThrottlingOptions + { + /// + /// Gets search response throttling options. + /// + [Validate] + public SearchResponseThrottlingOptions Response { get; init; } = new SearchResponseThrottlingOptions(); + + /// + /// Search response throttling options. + /// + public class SearchResponseThrottlingOptions + { + /// + /// Gets the limit for the number of concurrent search response operations. + /// + [EnvironmentVariable("THROTTLING_SEARCH_RESPONSE_CONCURRENCY")] + [Range(1, 100)] + [RequiresRestart] + public int Concurrency { get; init; } = 10; + + /// + /// Gets the limit for the number of queued search response operations, after which requests will be discarded. + /// + [EnvironmentVariable("THROTTLING_SEARCH_RESPONSE_CIRCUIT_BREAKER")] + [Range(100, 10000)] + [RequiresRestart] + public int CircuitBreaker { get; init; } = 500; + } + } + } + /// /// Metrics options. /// -- cgit v1.2.3 From 959269b2ba70d795b344f53a082be35250de1e2f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 13:25:32 -0600 Subject: add semaphore and queue depth --- src/slskd/Application.cs | 163 +++++++++++++++++++++++++++++------------------ 1 file changed, 102 insertions(+), 61 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index ba9755c0..7afd78d5 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -85,6 +85,7 @@ namespace slskd #pragma warning disable SA1306 // Field names should begin with lower-case letter private static int EnqueueQueueDepth = 0; private static double CurrentEnqueueLatency = 0; + private static int SearchResponseQueueDepth = 0; #pragma warning restore SA1306 // Field names should begin with lower-case letter public Application( @@ -129,6 +130,8 @@ namespace slskd OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); + SearchResponseSemaphore = new SemaphoreSlim(initialCount: OptionsAtStartup.Throttling.Search.Response.Concurrency, maxCount: OptionsAtStartup.Throttling.Search.Response.Concurrency); + PreviousOptions = OptionsMonitor.CurrentValue; Flags = Program.Flags; @@ -243,6 +246,7 @@ namespace slskd private IReadOnlyList ActiveDownloadIdsAtPreviousShutdown { get; set; } = []; private Options.FlagsOptions Flags { get; set; } private IReadOnlyList ExcludedSearchPhrases { get; set; } = []; + private SemaphoreSlim SearchResponseSemaphore { get; set; } public void CollectGarbage() { @@ -1552,98 +1556,135 @@ namespace slskd Metrics.Search.RequestsReceived.Inc(1); Metrics.Search.CurrentRequestReceiveRate.CountUp(1); - var sw = new Stopwatch(); - sw.Start(); + /* + if the host is struggling to process incoming search results in a timely manner, requests will back up + behind the SearchResponseSemaphore, potentially infinitely until the application runs out of memory and + crashes. + + to prevent this from happening we must count the number of waiting requests in SearchResponseQueueDepth, + and if that count exceeds the configured CicruitBreaker, we drop the search request and don't attempt + to resolve a response. - if (Users.IsBlacklisted(username)) + search requests arrive very consistently at a rate of about 30 per second, so we have about ~33 milliseconds + to process each request on average before we get into trouble. + */ + if (SearchResponseQueueDepth > OptionsAtStartup.Throttling.Search.Response.CircuitBreaker) { + Metrics.Search.RequestsDropped.Inc(1); + Metrics.Search.CurrentRequestDropRate.CountUp(1); + return null; } - if (CompiledSearchRequestFilters.Any(filter => filter.IsMatch(query.SearchText))) + Interlocked.Increment(ref SearchResponseQueueDepth); + + try { - return null; + await SearchResponseSemaphore.WaitAsync(); } - - // sometimes clients send search queries consisting only of exclusions; drop them. - // no other clients send search results for these, even though it is technically possible. - if (query.Terms.Count == 0) + finally { - return null; + Interlocked.Decrement(ref SearchResponseQueueDepth); + Metrics.Search.CurrentRequestQueueDepth.Set(SearchResponseQueueDepth); } - var filterLatency = sw.ElapsedMilliseconds; - Metrics.Search.Filter.Latency.Observe(filterLatency); - Metrics.Search.Filter.CurrentLatency.Update(filterLatency); - try { - // append the list of excluded search phrases supplied by the server - // see https://github.com/jpdillingham/Soulseek.NET/issues/803 - var queryWithExclusionsApplied = new SearchQuery(terms: query.Terms, exclusions: query.Exclusions.Concat(ExcludedSearchPhrases).Distinct()); + var sw = new Stopwatch(); + sw.Start(); - var results = await Shares.SearchAsync(queryWithExclusionsApplied); + if (Users.IsBlacklisted(username)) + { + return null; + } - var queryLatency = sw.ElapsedMilliseconds - filterLatency; - Metrics.Search.Query.Latency.Observe(queryLatency); - Metrics.Search.Query.CurrentLatency.Update(queryLatency); + if (CompiledSearchRequestFilters.Any(filter => filter.IsMatch(query.SearchText))) + { + return null; + } - SearchResponse response = null; + // sometimes clients send search queries consisting only of exclusions; drop them. + // no other clients send search results for these, even though it is technically possible. + if (query.Terms.Count == 0) + { + return null; + } - if (results.Any()) + var filterLatency = sw.ElapsedMilliseconds; + Metrics.Search.Filter.Latency.Observe(filterLatency); + Metrics.Search.Filter.CurrentLatency.Update(filterLatency); + + try { - // fetch the user's IP address so that we can check whether it's blacklisted. - // it's unfortunate that we have to do this to get the IP, but we have to do it - // anyway to send the results, and the information is cached. whether we do it here - // or Soulseek.NET does it under the hood doesn't really matter. - var endpoint = await Client.GetUserEndPointAsync(username); + // append the list of excluded search phrases supplied by the server + // see https://github.com/jpdillingham/Soulseek.NET/issues/803 + var queryWithExclusionsApplied = new SearchQuery(terms: query.Terms, exclusions: query.Exclusions.Concat(ExcludedSearchPhrases).Distinct()); + + var results = await Shares.SearchAsync(queryWithExclusionsApplied); - if (Users.IsBlacklisted(username, endpoint.Address)) + var queryLatency = sw.ElapsedMilliseconds - filterLatency; + Metrics.Search.Query.Latency.Observe(queryLatency); + Metrics.Search.Query.CurrentLatency.Update(queryLatency); + + SearchResponse response = null; + + if (results.Any()) { - return null; - } + // fetch the user's IP address so that we can check whether it's blacklisted. + // it's unfortunate that we have to do this to get the IP, but we have to do it + // anyway to send the results, and the information is cached. whether we do it here + // or Soulseek.NET does it under the hood doesn't really matter. + var endpoint = await Client.GetUserEndPointAsync(username); - // make sure our average speed (as reported by the server) is reasonably up to date - // we do this because we send the information along with the search response - await RefreshUserStatistics(); + if (Users.IsBlacklisted(username, endpoint.Address)) + { + return null; + } - // note: the following uses cached user data to determine group, so if the user's data - // isn't cached they may get a forecast based on the wrong group. this is a hot path though, - // and we don't want to incur the massive penalties that would caching data for each request. - var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); + // make sure our average speed (as reported by the server) is reasonably up to date + // we do this because we send the information along with the search response + await RefreshUserStatistics(); - Log.Debug("Sending search response with {Count} files to {Username} for query '{Query}'", results.Count(), username, query.SearchText); + // note: the following uses cached user data to determine group, so if the user's data + // isn't cached they may get a forecast based on the wrong group. this is a hot path though, + // and we don't want to incur the massive penalties that would caching data for each request. + var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); - Metrics.Search.ResponsesSent.Inc(1); + Log.Debug("Sending search response with {Count} files to {Username} for query '{Query}'", results.Count(), username, query.SearchText); - response = new SearchResponse( - Client.Username, - token, - uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed, - hasFreeUploadSlot: forecastedPosition == 0, - queueLength: forecastedPosition, - fileList: results); - } + response = new SearchResponse( + Client.Username, + token, + uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed, + hasFreeUploadSlot: forecastedPosition == 0, + queueLength: forecastedPosition, + fileList: results); + } - sw.Stop(); + sw.Stop(); - Metrics.Search.ResponseLatency.Observe(sw.ElapsedMilliseconds); - Metrics.Search.CurrentResponseLatency.Update(sw.ElapsedMilliseconds); + Metrics.Search.ResponseLatency.Observe(sw.ElapsedMilliseconds); + Metrics.Search.CurrentResponseLatency.Update(sw.ElapsedMilliseconds); - if (response is not null) + if (response is not null) + { + Metrics.Search.ResponsesSent.Inc(1); + Metrics.Search.CurrentResponseSendRate.CountUp(1); + } + + // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no + // response will be sent to the requestor. + return response; + } + catch (Exception ex) { - Metrics.Search.ResponsesSent.Inc(1); - Metrics.Search.CurrentResponseSendRate.CountUp(1); + Log.Warning(ex, "Failed to resolve search response: {Message}", ex.Message); + throw; } - - // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no - // response will be sent to the requestor. - return response; } - catch (Exception ex) + finally { - Log.Warning(ex, "Failed to resolve search response: {Message}", ex.Message); - throw; + SearchResponseSemaphore.Release(); } } -- cgit v1.2.3 From 8e991da03aa6da4e3ef1b429a7c3e09ee5cfed46 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 13:25:42 -0600 Subject: add queue depth metric --- src/slskd/Telemetry/Metrics.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index d0592a68..a2368392 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -81,6 +81,11 @@ public static class Metrics /// public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); + /// + /// Gets a gauge representing the number of incoming search requests waiting to be processed. + /// + public static Gauge CurrentRequestQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_search_response_queue_depth_current", "The number of incoming search requests waiting to be processed"); + private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve and return a response to an incoming search request, in milliseconds"); private static Gauge CurrentRequestReceiveRateGauge { get; } = -- cgit v1.2.3 From faffec9bbf67a92e10bb2cd297e61b21f0478aaf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 15:42:27 -0600 Subject: add a 30 second timer --- src/slskd/Core/Clock.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Clock.cs b/src/slskd/Core/Clock.cs index 1563a895..a111f40d 100644 --- a/src/slskd/Core/Clock.cs +++ b/src/slskd/Core/Clock.cs @@ -29,6 +29,7 @@ namespace slskd static Clock() { EveryMinuteTimer.Elapsed += (_, _) => Fire(EveryMinute); + EveryThirtySecondsTimer.Elapsed += (_, _) => Fire(EveryThirtySeconds); EveryFiveMinutesTimer.Elapsed += (_, _) => Fire(EveryFiveMinutes); EveryThirtyMinutesTimer.Elapsed += (_, _) => Fire(EveryThirtyMinutes); EveryHourTimer.Elapsed += (_, _) => Fire(EveryHour); @@ -49,6 +50,11 @@ namespace slskd /// public static event EventHandler EveryMinute; + /// + /// Fires every 30 seconds. + /// + public static event EventHandler EveryThirtySeconds; + /// /// Fires every 30 minutes. /// @@ -57,6 +63,7 @@ namespace slskd private static Timer EveryFiveMinutesTimer { get; } = CreateTimer(interval: 1000 * 60 * 5); private static Timer EveryHourTimer { get; } = CreateTimer(interval: 1000 * 60 * 60); private static Timer EveryMinuteTimer { get; } = CreateTimer(interval: 1000 * 60); + private static Timer EveryThirtySecondsTimer { get; } = CreateTimer(interval: 1000 * 30); private static Timer EveryThirtyMinutesTimer { get; } = CreateTimer(interval: 1000 * 60 * 30); /// @@ -66,6 +73,7 @@ namespace slskd public static Task StartAsync() { EveryMinuteTimer.Enabled = true; + EveryThirtySecondsTimer.Enabled = true; EveryFiveMinutesTimer.Enabled = true; EveryThirtyMinutesTimer.Enabled = true; EveryHourTimer.Enabled = true; @@ -74,6 +82,7 @@ namespace slskd return Task.WhenAll( Task.Run(() => Fire(EveryMinute, firstRunArgs)), + Task.Run(() => Fire(EveryThirtySeconds, firstRunArgs)), Task.Run(() => Fire(EveryFiveMinutes, firstRunArgs)), Task.Run(() => Fire(EveryThirtyMinutes, firstRunArgs)), Task.Run(() => Fire(EveryHour, firstRunArgs))); @@ -85,6 +94,7 @@ namespace slskd public static void Stop() { EveryMinuteTimer.Stop(); + EveryThirtySecondsTimer.Stop(); EveryFiveMinutesTimer.Stop(); EveryThirtyMinutesTimer.Stop(); EveryHourTimer.Stop(); -- cgit v1.2.3 From 9ee08068bac7efc778085ee3c0da480c9b089652 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 15:42:34 -0600 Subject: move metrics around --- src/slskd/Telemetry/Metrics.cs | 168 +++++++++++++++++++++-------------------- 1 file changed, 87 insertions(+), 81 deletions(-) (limited to 'src') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index a2368392..9a654a08 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -36,110 +36,116 @@ public static class Metrics public static class Search { /// - /// Gets a counter representing the total number of search requests received. + /// Metrics related to incoming search requests and responses. /// - public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_received", "Total number of search requests received"); - - /// - /// Gets an automatically resetting counter of the number of search requests received. - /// - public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count)); - - /// - /// Gets a counter representing the total number of search requests dropped due to processing pressure. - /// - public static Counter RequestsDropped { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_dropped", "Total number of search requests dropped due to processing pressure"); - - /// - /// Gets an automatically resetting counter of the number of search requests dropped due to processing pressure. - /// - public static TimedCounter CurrentRequestDropRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestDropRateGauge.Set(count)); - - /// - /// Gets a counter representing the total number of search responses sent. - /// - public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_responses_sent", "Total number of search responses sent"); + public static class Incoming + { + /// + /// Gets a counter representing the total number of search requests received. + /// + public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_incoming_requests_received", "Total number of search requests received"); - /// - /// Gets an automatically resetting counter of the number of search responses sent. - /// - public static TimedCounter CurrentResponseSendRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentResponseSendRateGauge.Set(count)); + /// + /// Gets an automatically resetting counter of the number of search requests received. + /// + public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count)); - /// - /// Gets a histogram representing the time taken to resolve and return a response to an incoming search request, in milliseconds. - /// - public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram( - "slskd_search_response_latency", - "The time taken to resolve and return a response to an incoming search request, in milliseconds", - new HistogramConfiguration - { - Buckets = Histogram.ExponentialBuckets(0.1, 2, 11), - }); + /// + /// Gets a counter representing the total number of search requests dropped due to processing pressure. + /// + public static Counter RequestsDropped { get; } = Prometheus.Metrics.CreateCounter("slskd_search_incoming_requests_dropped", "Total number of search requests dropped due to processing pressure"); - /// - /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds. - /// - public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); + /// + /// Gets an automatically resetting counter of the number of search requests dropped due to processing pressure. + /// + public static TimedCounter CurrentRequestDropRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestDropRateGauge.Set(count)); - /// - /// Gets a gauge representing the number of incoming search requests waiting to be processed. - /// - public static Gauge CurrentRequestQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_search_response_queue_depth_current", "The number of incoming search requests waiting to be processed"); + /// + /// Gets a counter representing the total number of search responses sent. + /// + public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_incoming_responses_sent", "Total number of search responses sent"); - private static Gauge CurrentResponseLatencyGauge { get; } = - Prometheus.Metrics.CreateGauge("slskd_search_response_latency_current", "The average time taken to resolve and return a response to an incoming search request, in milliseconds"); - private static Gauge CurrentRequestReceiveRateGauge { get; } = - Prometheus.Metrics.CreateGauge("slskd_search_request_receive_rate_current", "Number of search requests received in the last minute"); - private static Gauge CurrentRequestDropRateGauge { get; } = - Prometheus.Metrics.CreateGauge("slskd_search_request_drop_rate_current", "Number of search requests dropped in the last minute"); - private static Gauge CurrentResponseSendRateGauge { get; } = - Prometheus.Metrics.CreateGauge("slskd_search_response_send_rate_current", "Number of search responses sent in the last minute"); + /// + /// Gets an automatically resetting counter of the number of search responses sent. + /// + public static TimedCounter CurrentResponseSendRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentResponseSendRateGauge.Set(count)); - /// - /// Metrics related to the filtering of incoming search requests. - /// - public static class Filter - { /// - /// Gets a histogram representing the time taken to apply filters to an incoming search request, in milliseconds. + /// Gets a histogram representing the time taken to resolve and return a response to an incoming search request, in milliseconds. /// - public static Histogram Latency { get; } = Prometheus.Metrics.CreateHistogram( - "slskd_search_filter_latency", - "The time taken to apply filters to an incoming search request, in milliseconds", + public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram( + "slskd_search_incoming_response_latency", + "The time taken to resolve and return a response to an incoming search request, in milliseconds", new HistogramConfiguration { Buckets = Histogram.ExponentialBuckets(0.1, 2, 11), }); /// - /// Gets an EMA representing the average time taken to apply filters to an incoming search request, in milliseconds. + /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds. /// - public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentLatencyGauge.Set(value)); + public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); - private static Gauge CurrentLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_filter_latency_current", "The average time taken to apply filters to an incoming search request, in milliseconds"); - } + /// + /// Gets a gauge representing the number of incoming search requests waiting to be processed. + /// + public static Gauge CurrentRequestQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_search_incoming_request_queue_depth_current", "The number of incoming search requests waiting to be processed"); + + private static Gauge CurrentResponseLatencyGauge { get; } = + Prometheus.Metrics.CreateGauge("slskd_search_incoming_response_latency_current", "The average time taken to resolve and return a response to an incoming search request, in milliseconds"); + private static Gauge CurrentRequestReceiveRateGauge { get; } = + Prometheus.Metrics.CreateGauge("slskd_search_incoming_request_receive_rate_current", "Number of search requests received in the last minute"); + private static Gauge CurrentRequestDropRateGauge { get; } = + Prometheus.Metrics.CreateGauge("slskd_search_incoming_request_drop_rate_current", "Number of search requests dropped in the last minute"); + private static Gauge CurrentResponseSendRateGauge { get; } = + Prometheus.Metrics.CreateGauge("slskd_search_incoming_response_send_rate_current", "Number of search responses sent in the last minute"); - /// - /// Metrics related to the querying of shares for search results. - /// - public static class Query - { /// - /// Gets a histogram representing the time taken to query share database(s) for results, in milliseconds. + /// Metrics related to the filtering of incoming search requests. /// - public static Histogram Latency { get; } = Prometheus.Metrics.CreateHistogram( - "slskd_search_query_latency", - "The time taken to query share database(s) for results, in milliseconds", - new HistogramConfiguration - { - Buckets = Histogram.ExponentialBuckets(0.1, 2, 11), - }); + public static class Filter + { + /// + /// Gets a histogram representing the time taken to apply filters to an incoming search request, in milliseconds. + /// + public static Histogram Latency { get; } = Prometheus.Metrics.CreateHistogram( + "slskd_search_incoming_filter_latency", + "The time taken to apply filters to an incoming search request, in milliseconds", + new HistogramConfiguration + { + Buckets = Histogram.ExponentialBuckets(0.1, 2, 11), + }); + + /// + /// Gets an EMA representing the average time taken to apply filters to an incoming search request, in milliseconds. + /// + public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentLatencyGauge.Set(value)); + + private static Gauge CurrentLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_incoming_filter_latency_current", "The average time taken to apply filters to an incoming search request, in milliseconds"); + } /// - /// Gets an EMA representing the average time taken to query share database(s) for results, in milliseconds. + /// Metrics related to the querying of shares for search results. /// - public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentLatencyGauge.Set(value)); - private static Gauge CurrentLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_query_latency_current", "The average time taken to query share database(s) for results, in milliseconds"); + public static class Query + { + /// + /// Gets a histogram representing the time taken to query share database(s) for results, in milliseconds. + /// + public static Histogram Latency { get; } = Prometheus.Metrics.CreateHistogram( + "slskd_search_incoming_query_latency", + "The time taken to query share database(s) for results, in milliseconds", + new HistogramConfiguration + { + Buckets = Histogram.ExponentialBuckets(0.1, 2, 11), + }); + + /// + /// Gets an EMA representing the average time taken to query share database(s) for results, in milliseconds. + /// + public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentLatencyGauge.Set(value)); + private static Gauge CurrentLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_search_incoming_query_latency_current", "The average time taken to query share database(s) for results, in milliseconds"); + } } } -- cgit v1.2.3 From 55cc20f7e6357d27552d5bc2f79ce379b3085358 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 15:42:42 -0600 Subject: add health to state --- src/slskd/Core/State.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index 86b628b5..4f7876de 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -37,6 +37,7 @@ namespace slskd public ServerState Server { get; init; } = new ServerState(); public ServerConnectionWatchdogState ConnectionWatchdog { get; init; } = new ServerConnectionWatchdogState(); public RelayState Relay { get; init; } = new RelayState(); + public HealthState Health { get; init; } = new HealthState(); public UserState User { get; init; } = new UserState(); public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); public ShareState Shares { get; init; } = new ShareState(); @@ -44,6 +45,23 @@ namespace slskd public User[] Users { get; init; } = Array.Empty(); } + public record HealthState + { + public SearchHealthState Search { get; init; } = new(); + + public record SearchHealthState + { + public IncomingSearchHealthState Incoming { get; init; } = new(); + + public record IncomingSearchHealthState + { + public double Latency { get; init; } + public int QueueDepth { get; init; } + public double DropRate { get; init; } + } + } + } + public record VersionState { public string Full { get; init; } = Program.FullVersion; -- cgit v1.2.3 From deef26c4a219b4197ca988515d886643c2ff81e8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 15:42:58 -0600 Subject: populate health --- src/slskd/Application.cs | 54 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 7afd78d5..d3bfdadf 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -85,7 +85,7 @@ namespace slskd #pragma warning disable SA1306 // Field names should begin with lower-case letter private static int EnqueueQueueDepth = 0; private static double CurrentEnqueueLatency = 0; - private static int SearchResponseQueueDepth = 0; + private static int IncomingSearchRequestQueueDepth = 0; #pragma warning restore SA1306 // Field names should begin with lower-case letter public Application( @@ -203,6 +203,7 @@ namespace slskd ConnectionWatchdog = connectionWatchdog; Clock.EveryMinute += Clock_EveryMinute; + Clock.EveryThirtySeconds += Clock_EveryThirtySeconds; Clock.EveryFiveMinutes += Clock_EveryFiveMinutes; Clock.EveryThirtyMinutes += Clock_EveryThirtyMinutes; Clock.EveryHour += Clock_EveryHour; @@ -1120,6 +1121,25 @@ namespace slskd .ContinueWith(task => Log.Error(task.Exception, "Failed to clean up user enqueue semaphore(s): {Message}", task.Exception?.Message), TaskContinuationOptions.OnlyOnFaulted); } + private void Clock_EveryThirtySeconds(object sender, ClockEventArgs e) + { + State.SetValue(state => state with + { + Health = state.Health with + { + Search = state.Health.Search with + { + Incoming = state.Health.Search.Incoming with + { + Latency = Metrics.Search.Incoming.CurrentResponseLatency.Value, + QueueDepth = IncomingSearchRequestQueueDepth, + DropRate = Metrics.Search.Incoming.CurrentRequestDropRate.Count, + }, + }, + }, + }); + } + private void Clock_EveryFiveMinutes(object sender, ClockEventArgs e) { _ = Task.Run(() => PruneSearches()); @@ -1553,8 +1573,8 @@ namespace slskd /// A Task resolving a SearchResponse, or null. private async Task SearchResponseResolver(string username, int token, SearchQuery query) { - Metrics.Search.RequestsReceived.Inc(1); - Metrics.Search.CurrentRequestReceiveRate.CountUp(1); + Metrics.Search.Incoming.RequestsReceived.Inc(1); + Metrics.Search.Incoming.CurrentRequestReceiveRate.CountUp(1); /* if the host is struggling to process incoming search results in a timely manner, requests will back up @@ -1568,15 +1588,15 @@ namespace slskd search requests arrive very consistently at a rate of about 30 per second, so we have about ~33 milliseconds to process each request on average before we get into trouble. */ - if (SearchResponseQueueDepth > OptionsAtStartup.Throttling.Search.Response.CircuitBreaker) + if (IncomingSearchRequestQueueDepth > OptionsAtStartup.Throttling.Search.Response.CircuitBreaker) { - Metrics.Search.RequestsDropped.Inc(1); - Metrics.Search.CurrentRequestDropRate.CountUp(1); + Metrics.Search.Incoming.RequestsDropped.Inc(1); + Metrics.Search.Incoming.CurrentRequestDropRate.CountUp(1); return null; } - Interlocked.Increment(ref SearchResponseQueueDepth); + Interlocked.Increment(ref IncomingSearchRequestQueueDepth); try { @@ -1584,8 +1604,8 @@ namespace slskd } finally { - Interlocked.Decrement(ref SearchResponseQueueDepth); - Metrics.Search.CurrentRequestQueueDepth.Set(SearchResponseQueueDepth); + Interlocked.Decrement(ref IncomingSearchRequestQueueDepth); + Metrics.Search.Incoming.CurrentRequestQueueDepth.Set(IncomingSearchRequestQueueDepth); } try @@ -1611,8 +1631,8 @@ namespace slskd } var filterLatency = sw.ElapsedMilliseconds; - Metrics.Search.Filter.Latency.Observe(filterLatency); - Metrics.Search.Filter.CurrentLatency.Update(filterLatency); + Metrics.Search.Incoming.Filter.Latency.Observe(filterLatency); + Metrics.Search.Incoming.Filter.CurrentLatency.Update(filterLatency); try { @@ -1623,8 +1643,8 @@ namespace slskd var results = await Shares.SearchAsync(queryWithExclusionsApplied); var queryLatency = sw.ElapsedMilliseconds - filterLatency; - Metrics.Search.Query.Latency.Observe(queryLatency); - Metrics.Search.Query.CurrentLatency.Update(queryLatency); + Metrics.Search.Incoming.Query.Latency.Observe(queryLatency); + Metrics.Search.Incoming.Query.CurrentLatency.Update(queryLatency); SearchResponse response = null; @@ -1663,13 +1683,13 @@ namespace slskd sw.Stop(); - Metrics.Search.ResponseLatency.Observe(sw.ElapsedMilliseconds); - Metrics.Search.CurrentResponseLatency.Update(sw.ElapsedMilliseconds); + Metrics.Search.Incoming.ResponseLatency.Observe(sw.ElapsedMilliseconds); + Metrics.Search.Incoming.CurrentResponseLatency.Update(sw.ElapsedMilliseconds); if (response is not null) { - Metrics.Search.ResponsesSent.Inc(1); - Metrics.Search.CurrentResponseSendRate.CountUp(1); + Metrics.Search.Incoming.ResponsesSent.Inc(1); + Metrics.Search.Incoming.CurrentResponseSendRate.CountUp(1); } // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no -- cgit v1.2.3 From 14827ae832d04e8df0058bb4a580de2ec84cb2bd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 16:43:52 -0600 Subject: add the ability to pass a limit to share search --- src/slskd/Shares/IShareRepository.cs | 3 ++- src/slskd/Shares/IShareService.cs | 3 ++- src/slskd/Shares/ShareService.cs | 3 ++- src/slskd/Shares/SqliteShareRepository.cs | 5 +++-- 4 files changed, 9 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/IShareRepository.cs b/src/slskd/Shares/IShareRepository.cs index 1ccfeb22..cb6830d6 100644 --- a/src/slskd/Shares/IShareRepository.cs +++ b/src/slskd/Shares/IShareRepository.cs @@ -167,8 +167,9 @@ namespace slskd.Shares /// Searches the database for files matching the specified . /// /// The search query. + /// An optional row limit. /// The list of matching files. - IEnumerable Search(SearchQuery query); + IEnumerable Search(SearchQuery query, int? limit = null); /// /// Attempts to validate the backing database. diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 7db9671b..3b379c98 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -109,8 +109,9 @@ namespace slskd.Shares /// Searches the cache for the specified and returns the matching files. /// /// The query for which to search. + /// An optional row limit. /// The matching files. - Task> SearchAsync(SearchQuery query); + Task> SearchAsync(SearchQuery query, int? limit = null); /// /// Cancels the currently running scan on the local host, if one is running. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 6068a744..ee63f1bc 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -343,8 +343,9 @@ namespace slskd.Shares /// Searches the cache for the specified and returns the matching files. /// /// The query for which to search. + /// An optional row limit. /// The matching files. - public Task> SearchAsync(SearchQuery query) + public Task> SearchAsync(SearchQuery query, int? limit = null) { var results = AllRepositories.SelectMany(r => r.Search(query)); diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index cb0c331a..1d4e6783 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -517,8 +517,9 @@ namespace slskd.Shares /// Searches the database for files matching the specified . /// /// The search query. + /// An optional row limit. /// The list of matching files. - public IEnumerable Search(SearchQuery query) + public IEnumerable Search(SearchQuery query, int? limit = null) { string Clean(string str) => str.Replace("/", " ") .Replace("\\", " ") @@ -532,7 +533,7 @@ namespace slskd.Shares var sql = $"SELECT files.maskedFilename, files.code, files.size, files.extension, files.attributeJson FROM filenames " + "INNER JOIN files ON filenames.maskedFilename = files.maskedFilename " + $"WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}' " + - "ORDER BY filenames.maskedFilename ASC;"; + $"ORDER BY filenames.maskedFilename ASC {(limit.HasValue ? $"LIMIT {limit.Value}" : string.Empty)};"; var results = new List(); -- cgit v1.2.3 From bff2f9fa511061b1a24e30643c5f065ef159ffb0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 16:47:00 -0600 Subject: tweak range --- src/slskd/Core/Options.cs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 53c94303..e37a9446 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1484,20 +1484,20 @@ namespace slskd public class SearchThrottlingOptions { /// - /// Gets search response throttling options. + /// Gets incoming search throttling options. /// [Validate] - public SearchResponseThrottlingOptions Response { get; init; } = new SearchResponseThrottlingOptions(); + public IncomingSearchThrottlingOptions Incoming { get; init; } = new IncomingSearchThrottlingOptions(); /// /// Search response throttling options. /// - public class SearchResponseThrottlingOptions + public class IncomingSearchThrottlingOptions { /// /// Gets the limit for the number of concurrent search response operations. /// - [EnvironmentVariable("THROTTLING_SEARCH_RESPONSE_CONCURRENCY")] + [EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CONCURRENCY")] [Range(1, 100)] [RequiresRestart] public int Concurrency { get; init; } = 10; @@ -1505,10 +1505,17 @@ namespace slskd /// /// Gets the limit for the number of queued search response operations, after which requests will be discarded. /// - [EnvironmentVariable("THROTTLING_SEARCH_RESPONSE_CIRCUIT_BREAKER")] + [EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CIRCUIT_BREAKER")] [Range(100, 10000)] [RequiresRestart] public int CircuitBreaker { get; init; } = 500; + + /// + /// Gets the limit for the number of files that can be returned in a single search request. + /// + [EnvironmentVariable("THROTTLING_SEARCH_INCOMING_RESPONSE_FILE_LIMIT")] + [Range(100, 5000)] + public int ResponseFileLimit { get; init; } = 500; } } } -- cgit v1.2.3 From ce693af3352a0aa977b489b1423cc845e9b40894 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 16:47:32 -0600 Subject: tweak names --- config/slskd.example.yml | 3 ++- src/slskd/Application.cs | 14 ++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index d8c11226..b5e3b321 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -181,9 +181,10 @@ # logs: 180 # days # throttling: # search: -# response: +# incoming: # concurrency: 10 # number of search requests to process at the same time # circuit_breaker: 500 # maximum number of pending search requests +# response_file_limit: 500 # maximum number of files to return in a single search response # logger: # disk: false # no_color: false diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index d3bfdadf..df7d4f3f 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -130,7 +130,9 @@ namespace slskd OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); - SearchResponseSemaphore = new SemaphoreSlim(initialCount: OptionsAtStartup.Throttling.Search.Response.Concurrency, maxCount: OptionsAtStartup.Throttling.Search.Response.Concurrency); + IncomingSearchRequestSemaphore = new SemaphoreSlim( + initialCount: OptionsAtStartup.Throttling.Search.Incoming.Concurrency, + maxCount: OptionsAtStartup.Throttling.Search.Incoming.Concurrency); PreviousOptions = OptionsMonitor.CurrentValue; @@ -247,7 +249,7 @@ namespace slskd private IReadOnlyList ActiveDownloadIdsAtPreviousShutdown { get; set; } = []; private Options.FlagsOptions Flags { get; set; } private IReadOnlyList ExcludedSearchPhrases { get; set; } = []; - private SemaphoreSlim SearchResponseSemaphore { get; set; } + private SemaphoreSlim IncomingSearchRequestSemaphore { get; set; } public void CollectGarbage() { @@ -1588,7 +1590,7 @@ namespace slskd search requests arrive very consistently at a rate of about 30 per second, so we have about ~33 milliseconds to process each request on average before we get into trouble. */ - if (IncomingSearchRequestQueueDepth > OptionsAtStartup.Throttling.Search.Response.CircuitBreaker) + if (IncomingSearchRequestQueueDepth > OptionsAtStartup.Throttling.Search.Incoming.CircuitBreaker) { Metrics.Search.Incoming.RequestsDropped.Inc(1); Metrics.Search.Incoming.CurrentRequestDropRate.CountUp(1); @@ -1600,7 +1602,7 @@ namespace slskd try { - await SearchResponseSemaphore.WaitAsync(); + await IncomingSearchRequestSemaphore.WaitAsync(); } finally { @@ -1640,7 +1642,7 @@ namespace slskd // see https://github.com/jpdillingham/Soulseek.NET/issues/803 var queryWithExclusionsApplied = new SearchQuery(terms: query.Terms, exclusions: query.Exclusions.Concat(ExcludedSearchPhrases).Distinct()); - var results = await Shares.SearchAsync(queryWithExclusionsApplied); + var results = await Shares.SearchAsync(queryWithExclusionsApplied, limit: Options.Throttling.Search.Incoming.ResponseFileLimit); var queryLatency = sw.ElapsedMilliseconds - filterLatency; Metrics.Search.Incoming.Query.Latency.Observe(queryLatency); @@ -1704,7 +1706,7 @@ namespace slskd } finally { - SearchResponseSemaphore.Release(); + IncomingSearchRequestSemaphore.Release(); } } -- cgit v1.2.3 From fa39c123a67351e6d55d9fa04fd662a6b27f0481 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 17:17:42 -0600 Subject: add command line args --- docs/config.md | 13 ++++++++++--- src/slskd/Core/Options.cs | 3 +++ 2 files changed, 13 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/docs/config.md b/docs/config.md index 02f8abdb..f75a1335 100644 --- a/docs/config.md +++ b/docs/config.md @@ -471,7 +471,7 @@ Users added to the blacklist will be blocked from enqueueing any new files. Any A managed blacklist file may also be used to achieve the same effects. Read more about this in the [Managed Blacklist](#managed-blacklist) section below. -**YAML** +#### **YAML** ```yaml groups: blacklisted: @@ -640,7 +640,7 @@ Child connections should generally only be disabled on low spec systems or situa Depending on the current state, changing these values may require the server connection to be reset. | Command-Line | Environment Variable | Description | -| ------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--slsk-no-dnet` | `SLSKD_SLSK_NO_DNET` | Determines whether the distributed network is disabled. If disabled, the client will not obtain a parent or any child connections, and will not receive distributed search requests. | | `--slsk-dnet-no-children` | `SLSKD_SLSK_DNET_NO_CHILDREN` | Determines whether to disallow distributed children | | `--slsk-dnet-children` | `SLSKD_SLSK_DNET_CHILDREN` | The maximum number of distributed children to accept | @@ -992,13 +992,20 @@ Lower values of `concurrency` or slow processing of individual messages may caus The latency, queue depth and rate at which messages are being dropped can be monitored by reviewing the application state or Prometheus metrics. +| Command Line | Environment Variable | Description | +| -------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | +| `--throttling-search-incoming-concurrency` | `SLSKD_THROTTING_SEARCH_INCOMING_CONCURRENCY` | The limit for the number of concurrent search response operations | +| `--throttling-search-incoming-circuit-breaker` | `SLSKD_THROTTING_SEARCH_INCOMING_CIRCUIT_BREAKER` | The limit for the number of queued search response operations, after which requests will be discarded | +| `--throttling-search-incoming-response-file-limit` | `SLSKD_THROTTING_SEARCH_INCOMING_RESPONSE_FILE_LIMIT` | The limit for the number of files that can be returned in a single search request | + #### **YAML** ```yaml throttling: search: - response: + incoming: concurrency: 10 # number of search requests to process at the same time circuit_breaker: 500 # maximum number of pending search requests + file_limit: 500 # maximum number of files to return in a single search response ``` # Integrations diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e37a9446..7021f808 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1497,6 +1497,7 @@ namespace slskd /// /// Gets the limit for the number of concurrent search response operations. /// + [Argument(default, "throttling-search-incoming-concurrency")] [EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CONCURRENCY")] [Range(1, 100)] [RequiresRestart] @@ -1505,6 +1506,7 @@ namespace slskd /// /// Gets the limit for the number of queued search response operations, after which requests will be discarded. /// + [Argument(default, "throttling-search-incoming-circuit-breaker")] [EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CIRCUIT_BREAKER")] [Range(100, 10000)] [RequiresRestart] @@ -1513,6 +1515,7 @@ namespace slskd /// /// Gets the limit for the number of files that can be returned in a single search request. /// + [Argument(default, "throttling-search-incoming-response-file-limit")] [EnvironmentVariable("THROTTLING_SEARCH_INCOMING_RESPONSE_FILE_LIMIT")] [Range(100, 5000)] public int ResponseFileLimit { get; init; } = 500; -- cgit v1.2.3 From d4734424e1c39033c2c69086138a9bd9714a71a2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 17:27:33 -0600 Subject: pass limit to share --- src/slskd/Shares/ShareService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index ee63f1bc..9cd79a6c 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -347,7 +347,7 @@ namespace slskd.Shares /// The matching files. public Task> SearchAsync(SearchQuery query, int? limit = null) { - var results = AllRepositories.SelectMany(r => r.Search(query)); + var results = AllRepositories.SelectMany(r => r.Search(query, limit)); return Task.FromResult(results); } -- cgit v1.2.3 From eb194eed9f24ec84077360558c1804e3f31d7485 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 18 Jan 2026 17:29:14 -0600 Subject: ensure options can be changed at run time --- src/slskd/Application.cs | 4 ++-- src/slskd/Core/Options.cs | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index df7d4f3f..c68646da 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1590,7 +1590,7 @@ namespace slskd search requests arrive very consistently at a rate of about 30 per second, so we have about ~33 milliseconds to process each request on average before we get into trouble. */ - if (IncomingSearchRequestQueueDepth > OptionsAtStartup.Throttling.Search.Incoming.CircuitBreaker) + if (IncomingSearchRequestQueueDepth > OptionsMonitor.CurrentValue.Throttling.Search.Incoming.CircuitBreaker) { Metrics.Search.Incoming.RequestsDropped.Inc(1); Metrics.Search.Incoming.CurrentRequestDropRate.CountUp(1); @@ -1642,7 +1642,7 @@ namespace slskd // see https://github.com/jpdillingham/Soulseek.NET/issues/803 var queryWithExclusionsApplied = new SearchQuery(terms: query.Terms, exclusions: query.Exclusions.Concat(ExcludedSearchPhrases).Distinct()); - var results = await Shares.SearchAsync(queryWithExclusionsApplied, limit: Options.Throttling.Search.Incoming.ResponseFileLimit); + var results = await Shares.SearchAsync(queryWithExclusionsApplied, limit: OptionsMonitor.CurrentValue.Throttling.Search.Incoming.ResponseFileLimit); var queryLatency = sw.ElapsedMilliseconds - filterLatency; Metrics.Search.Incoming.Query.Latency.Observe(queryLatency); diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 7021f808..200b0ee8 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1509,7 +1509,6 @@ namespace slskd [Argument(default, "throttling-search-incoming-circuit-breaker")] [EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CIRCUIT_BREAKER")] [Range(100, 10000)] - [RequiresRestart] public int CircuitBreaker { get; init; } = 500; /// -- cgit v1.2.3 From 303fcb6752b0bfcc011fc79f3f9d64e943ead9ec Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 19 Jan 2026 12:13:22 -0600 Subject: Update src/slskd/Application.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c68646da..fdbddab9 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1584,7 +1584,7 @@ namespace slskd crashes. to prevent this from happening we must count the number of waiting requests in SearchResponseQueueDepth, - and if that count exceeds the configured CicruitBreaker, we drop the search request and don't attempt + and if that count exceeds the configured CircuitBreaker, we drop the search request and don't attempt to resolve a response. search requests arrive very consistently at a rate of about 30 per second, so we have about ~33 milliseconds -- cgit v1.2.3 From f9cf6063927da9d83a472df1ac90e7a35de40cc9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 19 Jan 2026 12:13:49 -0600 Subject: Update src/slskd/Telemetry/Metrics.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Telemetry/Metrics.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 9a654a08..85b13fa6 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -46,7 +46,9 @@ public static class Metrics public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_incoming_requests_received", "Total number of search requests received"); /// - /// Gets an automatically resetting counter of the number of search requests received. + /// Gets an automatically resetting counter of the number of search requests received per minute. + /// This metric previously represented a per-second rate; changing the period to one minute is a + /// breaking change for consumers that assumed requests per second. /// public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count)); -- cgit v1.2.3 From 5387effb11f58db572077a228882c9bd7eb7fd6d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 19 Jan 2026 12:24:52 -0600 Subject: ignore UserOfflineException --- src/slskd/Application.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index fdbddab9..bed8aab2 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1656,9 +1656,16 @@ namespace slskd // it's unfortunate that we have to do this to get the IP, but we have to do it // anyway to send the results, and the information is cached. whether we do it here // or Soulseek.NET does it under the hood doesn't really matter. - var endpoint = await Client.GetUserEndPointAsync(username); + try + { + var endpoint = await Client.GetUserEndPointAsync(username); - if (Users.IsBlacklisted(username, endpoint.Address)) + if (Users.IsBlacklisted(username, endpoint.Address)) + { + return null; + } + } + catch (Soulseek.UserOfflineException) { return null; } -- cgit v1.2.3 From 5b302ae5f2e0c01cb111a37680d63df3d47b114d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 19 Jan 2026 12:26:36 -0600 Subject: tweak docs --- src/slskd/Telemetry/Metrics.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 85b13fa6..520d77a2 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -47,8 +47,6 @@ public static class Metrics /// /// Gets an automatically resetting counter of the number of search requests received per minute. - /// This metric previously represented a per-second rate; changing the period to one minute is a - /// breaking change for consumers that assumed requests per second. /// public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count)); @@ -58,7 +56,7 @@ public static class Metrics public static Counter RequestsDropped { get; } = Prometheus.Metrics.CreateCounter("slskd_search_incoming_requests_dropped", "Total number of search requests dropped due to processing pressure"); /// - /// Gets an automatically resetting counter of the number of search requests dropped due to processing pressure. + /// Gets an automatically resetting counter of the number of search requests dropped due to processing pressure per minute. /// public static TimedCounter CurrentRequestDropRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestDropRateGauge.Set(count)); @@ -68,7 +66,7 @@ public static class Metrics public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_incoming_responses_sent", "Total number of search responses sent"); /// - /// Gets an automatically resetting counter of the number of search responses sent. + /// Gets an automatically resetting counter of the number of search responses sent per minute. /// public static TimedCounter CurrentResponseSendRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentResponseSendRateGauge.Set(count)); -- cgit v1.2.3