From b0a4c87111e8accbbf3cf6cabbd0e4203059187b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 4 Oct 2025 21:20:08 -0500 Subject: improve logging of DownloadDenied and DownloadFailed events --- src/slskd/Application.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd/Application.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index d8dab87c..7efd5c0d 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -187,8 +187,8 @@ namespace slskd Client.LoggedIn += Client_LoggedIn; Client.StateChanged += Client_StateChanged; Client.DistributedNetworkStateChanged += Client_DistributedNetworkStateChanged; - Client.DownloadDenied += (e, args) => Log.Information("Download of {Filename} from {Username} was denied: {Message}", args.Filename, args.Username, args.Message); - Client.DownloadFailed += (e, args) => Log.Information("Download of {Filename} from {Username} failed", args.Filename, args.Username); + Client.DownloadDenied += (e, args) => Log.Error("Download of {Filename} from {Username} was denied by the remote user: {Message}", args.Filename, args.Username, args.Message); + Client.DownloadFailed += (e, args) => Log.Error("Download of {Filename} from {Username} reported as failed by the remote user", args.Filename, args.Username); Client.ExcludedSearchPhrasesReceived += Client_ExcludedSearchPhrasesReceived; -- cgit v1.2.3 From 0600bc4f3a3623ac86b05fb778197fd821bce571 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Oct 2025 16:35:51 -0500 Subject: add timings for EnqueueDownload --- src/slskd/Application.cs | 328 ++++++++++++++++++++++++----------------------- 1 file changed, 169 insertions(+), 159 deletions(-) (limited to 'src/slskd/Application.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 7efd5c0d..48b8fb22 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -529,211 +529,221 @@ namespace slskd // todo: consider moving this somewhere else; it's pretty long and complicated private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename) { - if (Users.IsBlacklisted(username, endpoint.Address)) - { - Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address); - throw new DownloadEnqueueException("File not shared."); - } - - // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file - // it helps, too, that this will tell us whether the file is even shared. - (string Host, string Filename, long Size) resolved; + var stopwatch = new Stopwatch(); + var decisionStopwatch = new Stopwatch(); try { - resolved = await Shares.ResolveFileAsync(filename); - } - catch (NotFoundException) - { - throw new DownloadEnqueueException("File not shared."); - } + stopwatch.Start(); - // get the user's group. this will be the name of the user's group, if they have been added to a - // user defined group, or one of the built-ins; 'default', 'privileged', 'leecher', or 'blacklisted' - var group = await Users.GetOrFetchGroupAsync(username); + if (Users.IsBlacklisted(username, endpoint.Address)) + { + Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address); + throw new DownloadEnqueueException("File not shared."); + } - // privileged users aren't subject to limits (for now) - // i'm putting this off because 1) limits are unique to slskd, so all other clients are "unlimited" - // and 2) i can't figure out what the limits would be, if not unlimited. users should get some level - // of control, but i'd need to figure out a lower bound - if (string.Equals(group, PrivilegedGroup)) - { - Log.Debug("Limits bypassed for {Username} and {File}; user is privileged", username, filename); - await Transfers.Uploads.EnqueueAsync(username, filename); - return; - } + // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file + // it helps, too, that this will tell us whether the file is even shared. + (string Host, string Filename, long Size) resolved; - // we'll fall back to global limits for any limit that isn't set at the group level - var global = Options.Global.Limits; + try + { + resolved = await Shares.ResolveFileAsync(filename); + } + catch (NotFoundException) + { + throw new DownloadEnqueueException("File not shared."); + } - // resolve the limits for this user's group. - Options.LimitsOptions limits; + // get the user's group. this will be the name of the user's group, if they have been added to a + // user defined group, or one of the built-ins; 'default', 'privileged', 'leecher', or 'blacklisted' + var group = await Users.GetOrFetchGroupAsync(username); - if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions)) - { - limits = userDefinedOptions.Limits; - } - else - { - limits = group switch + // privileged users aren't subject to limits (for now) + // i'm putting this off because 1) limits are unique to slskd, so all other clients are "unlimited" + // and 2) i can't figure out what the limits would be, if not unlimited. users should get some level + // of control, but i'd need to figure out a lower bound + if (string.Equals(group, PrivilegedGroup)) { - DefaultGroup => Options.Groups.Default.Limits, - LeecherGroup => Options.Groups.Leechers.Limits, - _ => Options.Groups.Default.Limits, // that's weird! we'll just go with defaults.. - }; - } + Log.Debug("Limits bypassed for {Username} and {File}; user is privileged", username, filename); + await Transfers.Uploads.EnqueueAsync(username, filename); + return; + } - bool IsNull(Options.LimitsOptions.Limits lim, Options.LimitsOptions.Limits global) - => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim.Failures ?? global.Failures) is null); + // we'll fall back to global limits for any limit that isn't set at the group level + var global = Options.Global.Limits; - /* - * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued. - * the strategy here is to summarize all uploads: - * 1) belonging to this user - * 2) that were started within the time period - * 3) that did not end due to an error (state includes errored, exception column is set) - */ - (bool Files, bool Megabytes) OverLimits( - (int Files, long Bytes) stats, - Options.LimitsOptions.Limits options, - Options.LimitsOptions.Limits defaults, - long size) - { - var files = false; - var megabytes = false; - var byteLimitInMegabytes = options?.Megabytes ?? defaults?.Megabytes; + // resolve the limits for this user's group. + Options.LimitsOptions limits; - if (byteLimitInMegabytes is not null && (stats.Bytes + size) > (byteLimitInMegabytes * 1000L * 1000L)) + if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions)) { - Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimitInMegabytes * 1000L * 1000L); - megabytes = true; + limits = userDefinedOptions.Limits; } - - var fileLimit = options?.Files ?? defaults?.Files; - - if (fileLimit is not null && (stats.Files + 1) > fileLimit) + else { - Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, fileLimit); - files = true; + limits = group switch + { + DefaultGroup => Options.Groups.Default.Limits, + LeecherGroup => Options.Groups.Leechers.Limits, + _ => Options.Groups.Default.Limits, // that's weird! we'll just go with defaults.. + }; } - return (files, megabytes); - } + bool IsNull(Options.LimitsOptions.Limits lim, Options.LimitsOptions.Limits global) + => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim.Failures ?? global.Failures) is null); + + /* + * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued. + * the strategy here is to summarize all uploads: + * 1) belonging to this user + * 2) that were started within the time period + * 3) that did not end due to an error (state includes errored, exception column is set) + */ + (bool Files, bool Megabytes) OverLimits( + (int Files, long Bytes) stats, + Options.LimitsOptions.Limits options, + Options.LimitsOptions.Limits defaults, + long size) + { + var files = false; + var megabytes = false; + var byteLimitInMegabytes = options?.Megabytes ?? defaults?.Megabytes; - var sw = new Stopwatch(); - sw.Start(); + if (byteLimitInMegabytes is not null && (stats.Bytes + size) > (byteLimitInMegabytes * 1000L * 1000L)) + { + Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimitInMegabytes * 1000L * 1000L); + megabytes = true; + } - // start with the queue, since that should contain the fewest files and should be the least expensive to check - // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set - // for terminal transfers. - if (!IsNull(limits?.Queued, global?.Queued)) - { - var queued = Transfers.Uploads.Summarize( - expression: t => t.Username == username && t.EndedAt == null); + var fileLimit = options?.Files ?? defaults?.Files; + + if (fileLimit is not null && (stats.Files + 1) > fileLimit) + { + Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, fileLimit); + files = true; + } - Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, sw.ElapsedMilliseconds); + return (files, megabytes); + } - var over = OverLimits(queued, limits?.Queued, global?.Queued, resolved.Size); + decisionStopwatch.Start(); - if (over.Files || over.Megabytes) + // start with the queue, since that should contain the fewest files and should be the least expensive to check + // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set + // for terminal transfers. + if (!IsNull(limits?.Queued, global?.Queued)) { - Log.Information("Rejected enqueue request for user {Username}: Queued limits exceeded", username); + var queued = Transfers.Uploads.Summarize( + expression: t => t.Username == username && t.EndedAt == null); + + Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, decisionStopwatch.ElapsedMilliseconds); + + var over = OverLimits(queued, limits?.Queued, global?.Queued, resolved.Size); + + if (over.Files || over.Megabytes) + { + Log.Information("Rejected enqueue request for user {Username}: Queued limits exceeded", username); - // note: return exactly 'Too many files' or 'Too many megabytes' to ensure interop with other clients. - // these messages are retryable, while anything else is not - throw new DownloadEnqueueException($"Too many {(over.Megabytes ? "megabytes" : "files")}"); + // note: return exactly 'Too many files' or 'Too many megabytes' to ensure interop with other clients. + // these messages are retryable, while anything else is not + throw new DownloadEnqueueException($"Too many {(over.Megabytes ? "megabytes" : "files")}"); + } } - } - // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum - // transfers that 'count' for the weekly limit are uploads that: - // * started within the last week - // * which have or have not ended (assuming queued files will complete) - // * that were not errored - if (!IsNull(limits?.Weekly, global?.Weekly)) - { - var erroredState = TransferStates.Completed | TransferStates.Errored; - var cutoffDateTime = DateTime.UtcNow.AddDays(-7); + // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum + // transfers that 'count' for the weekly limit are uploads that: + // * started within the last week + // * which have or have not ended (assuming queued files will complete) + // * that were not errored + if (!IsNull(limits?.Weekly, global?.Weekly)) + { + var erroredState = TransferStates.Completed | TransferStates.Errored; + var cutoffDateTime = DateTime.UtcNow.AddDays(-7); - var failures = Transfers.Uploads.Summarize( - expression: t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && (t.State.HasFlag(erroredState) || t.Exception != null)); + var failures = Transfers.Uploads.Summarize( + expression: t => + t.Username == username + && t.StartedAt >= cutoffDateTime + && (t.State.HasFlag(erroredState) || t.Exception != null)); - Log.Debug("Fetched weekly failures: {Failures} ({Time}ms)", failures.Files, sw.ElapsedMilliseconds); + Log.Debug("Fetched weekly failures: {Failures} ({Time}ms)", failures.Files, decisionStopwatch.ElapsedMilliseconds); - var failureLimit = limits?.Weekly?.Failures ?? global?.Weekly?.Failures; + var failureLimit = limits?.Weekly?.Failures ?? global?.Weekly?.Failures; - if (failureLimit is not null && failures.Files >= failureLimit) - { - Log.Information("Rejected enqueue request for user {Username}: Weekly failure limit met or exceeded", username); - throw new DownloadEnqueueException("Too many failed transfers this week"); - } + if (failureLimit is not null && failures.Files >= failureLimit) + { + Log.Information("Rejected enqueue request for user {Username}: Weekly failure limit met or exceeded", username); + throw new DownloadEnqueueException("Too many failed transfers this week"); + } - var weekly = Transfers.Uploads.Summarize( - expression: t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && !t.State.HasFlag(erroredState) - && t.Exception == null); + var weekly = Transfers.Uploads.Summarize( + expression: t => + t.Username == username + && t.StartedAt >= cutoffDateTime + && !t.State.HasFlag(erroredState) + && t.Exception == null); - Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, sw.ElapsedMilliseconds); + Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, decisionStopwatch.ElapsedMilliseconds); - var over = OverLimits(weekly, limits?.Weekly, global?.Weekly, resolved.Size); + var over = OverLimits(weekly, limits?.Weekly, global?.Weekly, resolved.Size); - if (over.Files || over.Megabytes) - { - Log.Information("Rejected enqueue request for user {Username}: Weekly limits exceeded", username); - throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} this week"); + if (over.Files || over.Megabytes) + { + Log.Information("Rejected enqueue request for user {Username}: Weekly limits exceeded", username); + throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} this week"); + } } - } - // lastly, check daily limits. the criteria for this is the same as weekly, just looking over the previous day instead - // of the previous 7. - if (!IsNull(limits?.Daily, global?.Daily)) - { - var erroredState = TransferStates.Completed | TransferStates.Errored; - var cutoffDateTime = DateTime.UtcNow.AddDays(-1); + // lastly, check daily limits. the criteria for this is the same as weekly, just looking over the previous day instead + // of the previous 7. + if (!IsNull(limits?.Daily, global?.Daily)) + { + var erroredState = TransferStates.Completed | TransferStates.Errored; + var cutoffDateTime = DateTime.UtcNow.AddDays(-1); - var failures = Transfers.Uploads.Summarize( - expression: t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && (t.State.HasFlag(erroredState) || t.Exception != null)); + var failures = Transfers.Uploads.Summarize( + expression: t => + t.Username == username + && t.StartedAt >= cutoffDateTime + && (t.State.HasFlag(erroredState) || t.Exception != null)); - Log.Debug("Fetched daily failures: {Failures} ({Time}ms)", failures.Files, sw.ElapsedMilliseconds); + Log.Debug("Fetched daily failures: {Failures} ({Time}ms)", failures.Files, decisionStopwatch.ElapsedMilliseconds); - var failureLimit = limits?.Daily?.Failures ?? global?.Daily?.Failures; + var failureLimit = limits?.Daily?.Failures ?? global?.Daily?.Failures; - if (failureLimit is not null && failures.Files >= failureLimit) - { - Log.Information("Rejected enqueue request for user {Username}: Daily failure limit met or exceeded", username); - throw new DownloadEnqueueException("Too many failed transfers today"); - } + if (failureLimit is not null && failures.Files >= failureLimit) + { + Log.Information("Rejected enqueue request for user {Username}: Daily failure limit met or exceeded", username); + throw new DownloadEnqueueException("Too many failed transfers today"); + } - var daily = Transfers.Uploads.Summarize( - expression: t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && !t.State.HasFlag(erroredState) - && t.Exception == null); + var daily = Transfers.Uploads.Summarize( + expression: t => + t.Username == username + && t.StartedAt >= cutoffDateTime + && !t.State.HasFlag(erroredState) + && t.Exception == null); - Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, sw.ElapsedMilliseconds); + Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, decisionStopwatch.ElapsedMilliseconds); - var over = OverLimits(daily, limits?.Daily, global?.Daily, resolved.Size); + var over = OverLimits(daily, limits?.Daily, global?.Daily, resolved.Size); - if (over.Files || over.Megabytes) - { - Log.Information("Rejected enqueue request for user {Username}: Daily limits exceeded", username); - throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} today"); + if (over.Files || over.Megabytes) + { + Log.Information("Rejected enqueue request for user {Username}: Daily limits exceeded", username); + throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} today"); + } } - } - sw.Stop(); - Log.Debug("Enqueue decision made in {Duration}ms", sw.ElapsedMilliseconds); - - await Transfers.Uploads.EnqueueAsync(username, filename); + await Transfers.Uploads.EnqueueAsync(username, filename); + } + finally + { + decisionStopwatch.Stop(); + stopwatch.Stop(); + Log.Debug("EnqueueDownload for {Username}/{Filename} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", username, filename, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds); + } } /// -- cgit v1.2.3 From a7bba2d2684f6fad2fee3abbb4e7108089c5ab62 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 9 Oct 2025 19:04:14 -0500 Subject: disable (effectively) the write buffer for connections other than distributed --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Application.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 48b8fb22..7ebc5d10 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -374,7 +374,7 @@ namespace slskd var connectionOptions = new ConnectionOptions( readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Read, writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Write, - writeQueueSize: OptionsAtStartup.Soulseek.Connection.Buffer.WriteQueue, + writeQueueSize: int.MaxValue, // no write queue for peer, server or transfer connections connectTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Connect, inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity, proxyOptions: proxyOptions); -- cgit v1.2.3 From 4d10f21b831ecb4135b6f56c1c37c9cf90931f99 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 9 Oct 2025 19:04:52 -0500 Subject: set socket read and write timeouts --- src/slskd/Application.cs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) (limited to 'src/slskd/Application.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 7ebc5d10..7754c4ef 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -380,8 +380,10 @@ namespace slskd proxyOptions: proxyOptions); // os-specific keepalive is configured for long-lived connections for the server and distributed parent/children - var serverOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, OptionsAtStartup.Soulseek.Connection)); - var distributedOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, OptionsAtStartup.Soulseek.Connection)); + var serverOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketOptions(socket, OptionsAtStartup.Soulseek.Connection)); + var distributedOptions = connectionOptions.With( + writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.WriteQueue, // write queue set to keep distributed children from impacting performance + configureSocketAction: socket => ConfigureSocketOptions(socket, OptionsAtStartup.Soulseek.Connection)); var transferOptions = connectionOptions.With( readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer, @@ -495,7 +497,7 @@ namespace slskd return Task.CompletedTask; } - private void ConfigureSocketKeepAlive(Socket socket, Options.SoulseekOptions.ConnectionOptions options) + private void ConfigureSocketOptions(Socket socket, Options.SoulseekOptions.ConnectionOptions options) { /* os-specific keepalive is configured for long-lived connections for the server and distributed parent/children @@ -507,6 +509,11 @@ namespace slskd */ try { + // these are set in Soulseek.NET too, but to be super, super sure, do it again; these options can cause + // I/O loops to hang indefinitely and are suspected to be a cause of 'stuck' transfers + socket.SendTimeout = options.Timeout.Inactivity; + socket.ReceiveTimeout = options.Timeout.Inactivity; + socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); if (OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive) @@ -1391,8 +1398,8 @@ namespace slskd inactivityTimeout: connection.Timeout.Inactivity, proxyOptions: proxyPatch); - serverPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, options: connection)); - distributedPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, options: connection)); + serverPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketOptions(socket, options: connection)); + distributedPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketOptions(socket, options: connection)); transferPatch = connectionPatch.With( readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer, -- cgit v1.2.3 From 4b3a876411b09aa104c40aea094a9dc34e1d23e3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 Oct 2025 00:29:38 -0500 Subject: configure connection timeouts explicitly --- src/slskd/Application.cs | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) (limited to 'src/slskd/Application.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 7754c4ef..98226d4f 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -380,14 +380,18 @@ namespace slskd proxyOptions: proxyOptions); // os-specific keepalive is configured for long-lived connections for the server and distributed parent/children - var serverOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketOptions(socket, OptionsAtStartup.Soulseek.Connection)); + var serverOptions = connectionOptions.With( + inactivityTimeout: -1, // don't disconnect due to inactivity + configureSocket: socket => ConfigureSocketKeepaliveOptions(socket, OptionsAtStartup.Soulseek.Connection)); + var distributedOptions = connectionOptions.With( - writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.WriteQueue, // write queue set to keep distributed children from impacting performance - configureSocketAction: socket => ConfigureSocketOptions(socket, OptionsAtStartup.Soulseek.Connection)); + writeQueueSize: OptionsAtStartup.Soulseek.Connection.Buffer.WriteQueue, // write queue set to keep distributed children from impacting performance + configureSocket: socket => ConfigureSocketKeepaliveOptions(socket, OptionsAtStartup.Soulseek.Connection)); var transferOptions = connectionOptions.With( readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer, - writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer); + writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer, + inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Transfer); var patch = new SoulseekClientOptionsPatch( listenIPAddress: IPAddress.Parse(OptionsAtStartup.Soulseek.ListenIpAddress), @@ -497,7 +501,7 @@ namespace slskd return Task.CompletedTask; } - private void ConfigureSocketOptions(Socket socket, Options.SoulseekOptions.ConnectionOptions options) + private void ConfigureSocketKeepaliveOptions(Socket socket, Options.SoulseekOptions.ConnectionOptions options) { /* os-specific keepalive is configured for long-lived connections for the server and distributed parent/children @@ -509,11 +513,6 @@ namespace slskd */ try { - // these are set in Soulseek.NET too, but to be super, super sure, do it again; these options can cause - // I/O loops to hang indefinitely and are suspected to be a cause of 'stuck' transfers - socket.SendTimeout = options.Timeout.Inactivity; - socket.ReceiveTimeout = options.Timeout.Inactivity; - socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); if (OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive) @@ -1398,12 +1397,18 @@ namespace slskd inactivityTimeout: connection.Timeout.Inactivity, proxyOptions: proxyPatch); - serverPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketOptions(socket, options: connection)); - distributedPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketOptions(socket, options: connection)); + serverPatch = connectionPatch.With( + inactivityTimeout: -1, // don't disconnect due to inactivity + configureSocket: socket => ConfigureSocketKeepaliveOptions(socket, options: connection)); + + distributedPatch = connectionPatch.With( + writeQueueSize: connection.Buffer.WriteQueue, // write queue set to keep distributed children from impacting performance + configureSocket: socket => ConfigureSocketKeepaliveOptions(socket, options: connection)); transferPatch = connectionPatch.With( readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer, - writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer); + writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer, + inactivityTimeout: connection.Timeout.Transfer); } var patch = new SoulseekClientOptionsPatch( -- cgit v1.2.3 From b38cb680321d3444abe89ae0306026e1d1d4aa5c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 13 Oct 2025 18:54:57 -0500 Subject: limit concurrent enqueue requests to 20 --- src/slskd/Application.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src/slskd/Application.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 98226d4f..c1e09d42 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -219,6 +219,7 @@ namespace slskd private OptionsAtStartup OptionsAtStartup { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1); + private SemaphoreSlim EnqueueRequestRateLimiter { get; } = new SemaphoreSlim(20, 20); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } private DateTime SharesRefreshStarted { get; set; } @@ -538,6 +539,8 @@ namespace slskd var stopwatch = new Stopwatch(); var decisionStopwatch = new Stopwatch(); + await EnqueueRequestRateLimiter.WaitAsync(); + try { stopwatch.Start(); @@ -748,6 +751,9 @@ namespace slskd { decisionStopwatch.Stop(); stopwatch.Stop(); + + EnqueueRequestRateLimiter.Release(); + Log.Debug("EnqueueDownload for {Username}/{Filename} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", username, filename, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds); } } -- cgit v1.2.3