aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Application.cs
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-01-18 13:25:32 -0600
committerJP Dillingham <jp@dillingham.me>2026-01-18 13:25:32 -0600
commit959269b2ba70d795b344f53a082be35250de1e2f (patch)
treedfcd03414280daf165832409e686c1bf977640a3 /src/slskd/Application.cs
parent572aa0502b325fc9657eef774f034a43a7078e1a (diff)
downloadslskd-959269b2ba70d795b344f53a082be35250de1e2f.tar.gz
add semaphore and queue depth
Diffstat (limited to 'src/slskd/Application.cs')
-rw-r--r--src/slskd/Application.cs163
1 files changed, 102 insertions, 61 deletions
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<Guid> ActiveDownloadIdsAtPreviousShutdown { get; set; } = [];
private Options.FlagsOptions Flags { get; set; }
private IReadOnlyList<string> 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();
}
}