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 /src | |
| 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
Diffstat (limited to 'src')
| -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 |
9 files changed, 339 insertions, 81 deletions
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> |
