diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-01-19 12:53:17 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-01-19 12:53:17 -0600 |
| commit | 6fdc317978fd91fbfd5828ee72c7e7f19c316b13 (patch) | |
| tree | 0370a03f1fadda7e6d4979cb4ee46c4d75880e8d | |
| parent | 9c1c726f2de69dd3fd38740f5bdb7f1f76e97fcf (diff) | |
| parent | 5b302ae5f2e0c01cb111a37680d63df3d47b114d (diff) | |
| download | slskd-6fdc317978fd91fbfd5828ee72c7e7f19c316b13.tar.gz | |
Merge pull request #1608 from slskd/search-metrics
Add throttling for incoming search requests, add additional prometheus metrics covering search responses
| -rw-r--r-- | config/slskd.example.yml | 6 | ||||
| -rw-r--r-- | docs/config.md | 33 | ||||
| -rw-r--r-- | src/slskd/Application.cs | 184 | ||||
| -rw-r--r-- | src/slskd/Core/Clock.cs | 10 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 61 | ||||
| -rw-r--r-- | src/slskd/Core/State.cs | 18 | ||||
| -rw-r--r-- | src/slskd/Shares/IShareRepository.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Shares/IShareService.cs | 3 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareService.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Shares/SqliteShareRepository.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Telemetry/Metrics.cs | 131 |
11 files changed, 376 insertions, 83 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml index b8723f4d..b5e3b321 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -179,6 +179,12 @@ # complete: 20160 # 2 weeks, in minutes # incomplete: 43200 # 30 days, in minutes # logs: 180 # days +# throttling: +# search: +# 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/docs/config.md b/docs/config.md index 2f8bdb1e..9836a063 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 | @@ -979,6 +979,35 @@ retention: logs: 180 # days ``` +# Throttling + +> [!WARNING] +> **Application Stability Risk**: The options in this section control the behavior of the application at the limits of the hosting environment's performance. Increasing values can result in unintended behavior and crashes. Support for users that increase these values will be limited. + +slskd is a multi-threaded application and the logic is highly concurrent, but is mostly bound by disk and network I/O rather than CPU. + +The `concurrency` option controls how many threads (.NET `Task`s to be specific) can perform work at the same time, limiting I/O contention. Raising the number _can_ improve throughput on capable machines but defaults are generally set in such a way that improvements will be negligible. Lowering the number will reduce throughput but alleviate I/O contention and improve stability on lower-spec hardware. + +Lower values of `concurrency` or slow processing of individual messages may cause the application to process messages at a slower rate than they are received, causing messages to be 'backed up' in internal queues. The `circuit_breaker` option controls the number of messages that can be enqueued. Once the circuit breaker is hit, the application will drop or discard messages without processing them. + +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_THROTTLING_SEARCH_INCOMING_CONCURRENCY` | The limit for the number of concurrent search response operations | +| `--throttling-search-incoming-circuit-breaker` | `SLSKD_THROTTLING_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_THROTTLING_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: + 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 +``` + # Integrations ## User-Defined diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a93afafe..bed8aab2 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 IncomingSearchRequestQueueDepth = 0; #pragma warning restore SA1306 // Field names should begin with lower-case letter public Application( @@ -129,6 +130,10 @@ namespace slskd OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options)); + IncomingSearchRequestSemaphore = new SemaphoreSlim( + initialCount: OptionsAtStartup.Throttling.Search.Incoming.Concurrency, + maxCount: OptionsAtStartup.Throttling.Search.Incoming.Concurrency); + PreviousOptions = OptionsMonitor.CurrentValue; Flags = Program.Flags; @@ -200,6 +205,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; @@ -243,6 +249,7 @@ namespace slskd private IReadOnlyList<Guid> ActiveDownloadIdsAtPreviousShutdown { get; set; } = []; private Options.FlagsOptions Flags { get; set; } private IReadOnlyList<string> ExcludedSearchPhrases { get; set; } = []; + private SemaphoreSlim IncomingSearchRequestSemaphore { get; set; } public void CollectGarbage() { @@ -1116,6 +1123,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()); @@ -1549,24 +1575,39 @@ namespace slskd /// <returns>A Task resolving a SearchResponse, or null.</returns> private async Task<SearchResponse> 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 + 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 CircuitBreaker, 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 (IncomingSearchRequestQueueDepth > OptionsMonitor.CurrentValue.Throttling.Search.Incoming.CircuitBreaker) { + Metrics.Search.Incoming.RequestsDropped.Inc(1); + Metrics.Search.Incoming.CurrentRequestDropRate.CountUp(1); + return null; } - if (CompiledSearchRequestFilters.Any(filter => filter.IsMatch(query.SearchText))) + Interlocked.Increment(ref IncomingSearchRequestQueueDepth); + + try { - return null; + await IncomingSearchRequestSemaphore.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 IncomingSearchRequestQueueDepth); + Metrics.Search.Incoming.CurrentRequestQueueDepth.Set(IncomingSearchRequestQueueDepth); } try @@ -1574,60 +1615,105 @@ namespace slskd 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()); + if (Users.IsBlacklisted(username)) + { + return null; + } - var results = await Shares.SearchAsync(queryWithExclusionsApplied); + if (CompiledSearchRequestFilters.Any(filter => filter.IsMatch(query.SearchText))) + { + return null; + } - sw.Stop(); + // 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; + } - Metrics.Search.ResponseLatency.Observe(sw.ElapsedMilliseconds); - Metrics.Search.CurrentResponseLatency.Update(sw.ElapsedMilliseconds); + var filterLatency = sw.ElapsedMilliseconds; + Metrics.Search.Incoming.Filter.Latency.Observe(filterLatency); + Metrics.Search.Incoming.Filter.CurrentLatency.Update(filterLatency); - if (results.Any()) + 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, limit: OptionsMonitor.CurrentValue.Throttling.Search.Incoming.ResponseFileLimit); + + var queryLatency = sw.ElapsedMilliseconds - filterLatency; + Metrics.Search.Incoming.Query.Latency.Observe(queryLatency); + Metrics.Search.Incoming.Query.CurrentLatency.Update(queryLatency); + + SearchResponse response = null; - if (Users.IsBlacklisted(username, endpoint.Address)) + 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. + try + { + 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; + } + } + catch (Soulseek.UserOfflineException) + { + 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); - return 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); + } - // 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; + sw.Stop(); + + Metrics.Search.Incoming.ResponseLatency.Observe(sw.ElapsedMilliseconds); + Metrics.Search.Incoming.CurrentResponseLatency.Update(sw.ElapsedMilliseconds); + + if (response is not null) + { + 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 + // response will be sent to the requestor. + return response; + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to resolve search response: {Message}", ex.Message); + throw; + } } - catch (Exception ex) + finally { - Log.Warning(ex, "Failed to resolve search response: {Message}", ex.Message); - throw; + IncomingSearchRequestSemaphore.Release(); } } 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); @@ -50,6 +51,11 @@ namespace slskd public static event EventHandler<ClockEventArgs> EveryMinute; /// <summary> + /// Fires every 30 seconds. + /// </summary> + public static event EventHandler<ClockEventArgs> EveryThirtySeconds; + + /// <summary> /// Fires every 30 minutes. /// </summary> public static event EventHandler<ClockEventArgs> EveryThirtyMinutes; @@ -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); /// <summary> @@ -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(); diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 68fa4d92..200b0ee8 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -283,6 +283,12 @@ namespace slskd public RetentionOptions Retention { get; init; } = new RetentionOptions(); /// <summary> + /// Gets throttling options. + /// </summary> + [Validate] + public ThrottlingOptions Throttling { get; init; } = new ThrottlingOptions(); + + /// <summary> /// Gets logger options. /// </summary> [Validate] @@ -1462,6 +1468,61 @@ namespace slskd } /// <summary> + /// Throttling options. + /// </summary> + public class ThrottlingOptions + { + /// <summary> + /// Gets search throttling options. + /// </summary> + [Validate] + public SearchThrottlingOptions Search { get; init; } = new SearchThrottlingOptions(); + + /// <summary> + /// Search throttling options. + /// </summary> + public class SearchThrottlingOptions + { + /// <summary> + /// Gets incoming search throttling options. + /// </summary> + [Validate] + public IncomingSearchThrottlingOptions Incoming { get; init; } = new IncomingSearchThrottlingOptions(); + + /// <summary> + /// Search response throttling options. + /// </summary> + public class IncomingSearchThrottlingOptions + { + /// <summary> + /// Gets the limit for the number of concurrent search response operations. + /// </summary> + [Argument(default, "throttling-search-incoming-concurrency")] + [EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CONCURRENCY")] + [Range(1, 100)] + [RequiresRestart] + public int Concurrency { get; init; } = 10; + + /// <summary> + /// Gets the limit for the number of queued search response operations, after which requests will be discarded. + /// </summary> + [Argument(default, "throttling-search-incoming-circuit-breaker")] + [EnvironmentVariable("THROTTLING_SEARCH_INCOMING_CIRCUIT_BREAKER")] + [Range(100, 10000)] + public int CircuitBreaker { get; init; } = 500; + + /// <summary> + /// Gets the limit for the number of files that can be returned in a single search request. + /// </summary> + [Argument(default, "throttling-search-incoming-response-file-limit")] + [EnvironmentVariable("THROTTLING_SEARCH_INCOMING_RESPONSE_FILE_LIMIT")] + [Range(100, 5000)] + public int ResponseFileLimit { get; init; } = 500; + } + } + } + + /// <summary> /// Metrics options. /// </summary> public class MetricsOptions 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<User>(); } + 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; 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 <paramref name="query"/>. /// </summary> /// <param name="query">The search query.</param> + /// <param name="limit">An optional row limit.</param> /// <returns>The list of matching files.</returns> - IEnumerable<File> Search(SearchQuery query); + IEnumerable<File> Search(SearchQuery query, int? limit = null); /// <summary> /// 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 <paramref name="query"/> and returns the matching files. /// </summary> /// <param name="query">The query for which to search.</param> + /// <param name="limit">An optional row limit.</param> /// <returns>The matching files.</returns> - Task<IEnumerable<File>> SearchAsync(SearchQuery query); + Task<IEnumerable<File>> SearchAsync(SearchQuery query, int? limit = null); /// <summary> /// 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..9cd79a6c 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -343,10 +343,11 @@ namespace slskd.Shares /// Searches the cache for the specified <paramref name="query"/> and returns the matching files. /// </summary> /// <param name="query">The query for which to search.</param> + /// <param name="limit">An optional row limit.</param> /// <returns>The matching files.</returns> - public Task<IEnumerable<File>> SearchAsync(SearchQuery query) + public Task<IEnumerable<File>> 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); } 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 <paramref name="query"/>. /// </summary> /// <param name="query">The search query.</param> + /// <param name="limit">An optional row limit.</param> /// <returns>The list of matching files.</returns> - public IEnumerable<Soulseek.File> Search(SearchQuery query) + public IEnumerable<Soulseek.File> 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<Soulseek.File>(); diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 33550577..520d77a2 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -36,38 +36,117 @@ public static class Metrics public static class Search { /// <summary> - /// Gets a histogram representing the time taken to resolve a response to an incoming search request, in milliseconds. + /// Metrics related to incoming search requests and responses. /// </summary> - 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", - new HistogramConfiguration - { - Buckets = Histogram.ExponentialBuckets(0.1, 2, 11), - }); + public static class Incoming + { + /// <summary> + /// Gets a counter representing the total number of search requests received. + /// </summary> + public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_incoming_requests_received", "Total number of search requests received"); - /// <summary> - /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds. - /// </summary> - public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); + /// <summary> + /// Gets an automatically resetting counter of the number of search requests received per minute. + /// </summary> + public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count)); - /// <summary> - /// Gets an automatically resetting counter of the number of search requests received. - /// </summary> - public static TimedCounter CurrentRequestReceiveRate { get; } = new TimedCounter(TimeSpan.FromSeconds(1), onElapsed: count => CurrentRequestReceiveRateGauge.Set(count)); + /// <summary> + /// Gets a counter representing the total number of search requests dropped due to processing pressure. + /// </summary> + public static Counter RequestsDropped { get; } = Prometheus.Metrics.CreateCounter("slskd_search_incoming_requests_dropped", "Total number of search requests dropped due to processing pressure"); - /// <summary> - /// Gets a counter representing the total number of search requests received. - /// </summary> - public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_search_requests_received", "Total number of search requests received"); + /// <summary> + /// Gets an automatically resetting counter of the number of search requests dropped due to processing pressure per minute. + /// </summary> + public static TimedCounter CurrentRequestDropRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentRequestDropRateGauge.Set(count)); - /// <summary> - /// Gets a counter representing the total number of search responses sent. - /// </summary> - public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_responses_sent", "Total number of search responses sent"); + /// <summary> + /// Gets a counter representing the total number of search responses sent. + /// </summary> + public static Counter ResponsesSent { get; } = Prometheus.Metrics.CreateCounter("slskd_search_incoming_responses_sent", "Total number of search responses sent"); + + /// <summary> + /// Gets an automatically resetting counter of the number of search responses sent per minute. + /// </summary> + public static TimedCounter CurrentResponseSendRate { get; } = new TimedCounter(TimeSpan.FromMinutes(1), onElapsed: count => CurrentResponseSendRateGauge.Set(count)); + + /// <summary> + /// Gets a histogram representing the time taken to resolve and return a response to an incoming search request, in milliseconds. + /// </summary> + 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), + }); + + /// <summary> + /// Gets an EMA representing the average time taken to resolve a response to an incoming search request, in milliseconds. + /// </summary> + public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); + + /// <summary> + /// Gets a gauge representing the number of incoming search requests waiting to be processed. + /// </summary> + 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"); + + /// <summary> + /// Metrics related to the filtering of incoming search requests. + /// </summary> + public static class Filter + { + /// <summary> + /// Gets a histogram representing the time taken to apply filters to an incoming search request, in milliseconds. + /// </summary> + 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), + }); + + /// <summary> + /// Gets an EMA representing the average time taken to apply filters to an incoming search request, in milliseconds. + /// </summary> + 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"); + } + + /// <summary> + /// Metrics related to the querying of shares for search results. + /// </summary> + public static class Query + { + /// <summary> + /// Gets a histogram representing the time taken to query share database(s) for results, in milliseconds. + /// </summary> + 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), + }); - 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"); + /// <summary> + /// Gets an EMA representing the average time taken to query share database(s) for results, in milliseconds. + /// </summary> + 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"); + } + } } /// <summary> |
