From 0273fb1fdde5f01fc0a545eadb0da23f62ed01ac Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 9 Oct 2025 19:02:39 -0500 Subject: move stateChanged delegate invoke to finally --- src/slskd/Transfers/Downloads/DownloadService.cs | 41 +++++++++++++----------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index db1a92ad..65404945 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -279,29 +279,34 @@ namespace slskd.Transfers.Downloads var topts = new TransferOptions( stateChanged: (args) => { - Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", transfer.Filename, transfer.Username, args.PreviousState, args.Transfer.State); - - // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions; - // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup - if (Application.IsShuttingDown) + try { - Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); - return; - } + Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", transfer.Filename, transfer.Username, args.PreviousState, args.Transfer.State); - transfer = transfer.WithSoulseekTransfer(args.Transfer); + // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions; + // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup + if (Application.IsShuttingDown) + { + Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); + return; + } - // we don't know when the download is actually enqueued (remotely) until it switches into that state - // when it is enqueued locally is irrelevant, due to internal throttling etc - if (args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) - { - transfer.EnqueuedAt ??= DateTime.UtcNow; - } + transfer = transfer.WithSoulseekTransfer(args.Transfer); - // todo: broadcast - SynchronizedUpdate(transfer); + // we don't know when the download is actually enqueued (remotely) until it switches into that state + // when it is enqueued locally is irrelevant, due to internal throttling etc + if (args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) + { + transfer.EnqueuedAt ??= DateTime.UtcNow; + } - stateChanged?.Invoke(transfer); + // todo: broadcast + SynchronizedUpdate(transfer); + } + finally + { + stateChanged?.Invoke(transfer); + } }, progressUpdated: (args) => rateLimiter.Invoke(() => { -- cgit v1.2.3 From e1c77aca06e0add021c67388468fc72de92f1c26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 9 Oct 2025 19:03:44 -0500 Subject: 'prime' transfer records before enqueue --- src/slskd/Transfers/Downloads/DownloadService.cs | 498 +++++++++++------------ 1 file changed, 249 insertions(+), 249 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 65404945..e29454c9 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -60,18 +60,7 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default); - - /// - /// Enqueues the specified from the specified . - /// - /// The username of remote user. - /// The remote filename to download. - /// The size of the file. - /// An optional delegate to invoke the transfer state changes. - /// The token to monitor for cancellation. - /// The operation context. - Task EnqueueAsync(string username, string filename, long size, Action stateChanged = null, CancellationToken cancellationToken = default); + Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default); /// /// Downloads the specified enqueued from the remote user. @@ -479,300 +468,311 @@ namespace slskd.Transfers.Downloads } /// - /// Enqueues the specified from the specified . + /// Enqueues the requested list of . /// - /// The username of remote user. - /// The remote filename to download. - /// The size of the file. - /// An optional delegate to invoke the transfer state changes. + /// + /// If one file in the specified collection fails, the rest will continue. An will be + /// thrown after all files are dispositioned if any throws. + /// + /// The username of the remote user. + /// The list of files to enqueue. /// The token to monitor for cancellation. /// The operation context. - public Task EnqueueAsync(string username, string filename, long size, Action stateChanged = null, CancellationToken cancellationToken = default) + /// Thrown when the username is null or an empty string. + /// Thrown when no files are requested. + /// Thrown when at least one of the requested files throws. + public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { - throw new ArgumentNullException(nameof(username), "Username is required"); - } - - if (string.IsNullOrEmpty(filename)) - { - throw new ArgumentNullException(nameof(filename), "Filename is required"); - } - - if (size <= 0) - { - throw new ArgumentOutOfRangeException(nameof(size), "Size must be greater than zero"); + throw new ArgumentException("Username is required", nameof(username)); } - var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}"; - - if (!Locks.TryAdd(lockName, true)) + if (!files.Any()) { - Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName); - return null; + throw new ArgumentException("At least one file is required", nameof(files)); } - Guid id = Guid.NewGuid(); + List acquiredLocks = []; try { - Log.Debug("Acquired lock {LockName}", lockName); - - Log.Information("Download of {Filename} from {Username} requested", filename, username); - - using var context = ContextFactory.CreateDbContext(); - - /* - first, get all past downloads from this user for this filename - */ - var existingRecords = context.Transfers - .Where(t => t.Direction == TransferDirection.Download) - .Where(t => t.Username == username) - .Where(t => t.Filename == filename) - .AsNoTracking() - .ToList(); - - var existingInProgressRecords = existingRecords - .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) - .ToList(); - - /* - if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already - an existing transfer record covering this file, and we're already enqueued. nothing more to do! - */ - if (existingInProgressRecords.Count != 0) - { - Log.Information("Download of {Filename} from {Username} is already queued or is in progress (ids: {Ids})", filename, username, string.Join(", ", existingInProgressRecords.Select(t => t.Id))); - return null; - } - - /* - check the tracked download dictionary in Soulseek.NET to see if it knows about this already - it shouldn't, if the slskd database doesn't. but things could get desynced - */ - if (Client.Downloads.Any(u => u.Username == username && u.Filename == filename)) - { - throw new DuplicateTransferException("A duplicate download of the same file from the same user is already registered"); - } - - /* - we're cleared to enqueue! create a new transfer record, and automatically mark any existing records - we found as 'removed' to clean up the UI - */ - var transfer = new Transfer() - { - Id = id, - Username = username, - Direction = TransferDirection.Download, - Filename = filename, // important! use the remote filename - Size = size, - StartOffset = 0, // todo: maybe implement resumeable downloads? - RequestedAt = DateTime.UtcNow, - State = TransferStates.Queued | TransferStates.Locally, - }; - - context.Add(transfer); - - foreach (var record in existingRecords.Where(t => !t.Removed)) - { - record.Removed = true; - context.Update(record); - Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", filename, username, record.Id); - } - - context.SaveChanges(); - - Log.Information("Successfully enqueued download of {Filename} from {Username} (id: {Id})", filename, username, id); + List enqueued = []; + List failed = []; /* - schedule the download immediately + first, check inputs and do an _exhaustive_ check for all of the files provided, separating files out + into good/bad - Task.Run can fail due to thread pool exhaustion or OOM, and this *SHOULD* throw up the chain and - fail the enqueue request + acquire locks for each, and track them so we can release them later (in the finally block) */ - _ = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken)).ContinueWith(task => + foreach (var file in files) { - if (task.IsCompletedSuccessfully) + var transfer = new Transfer() { - Log.Information("Task for download of {Filename} from {Username} completed successfully", filename, username); - return; + Id = Guid.NewGuid(), + Username = username, + Direction = TransferDirection.Download, + Filename = file.Filename, // important! use the remote filename + Size = file.Size, + StartOffset = 0, // todo: maybe implement resumeable downloads? + RequestedAt = DateTime.UtcNow, + State = TransferStates.Queued | TransferStates.Locally, + }; + + var lockName = $"{nameof(EnqueueAsync)}:{username}:{file.Filename}"; + + if (!Locks.TryAdd(lockName, true)) + { + Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName); + transfer.Exception = "A download for this file from this user is already underway"; + transfer.State = TransferStates.Aborted | TransferStates.Completed; + failed.Add(transfer); + continue; } - /* - things that can cause us to arrive here: - - * transfer record deleted somehow - * transfer record updated so that it's no longer in Queued | Locally - * Soulseek.NET already tracking an identical download (slskd <> Soulseek.NET desync) - */ - Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", filename, username, task.Exception.Message); - try { - var transfer = Find(t => t.Id == id); - - if (transfer is not null) + acquiredLocks.Add(lockName); + Log.Debug("Acquired lock {LockName}", lockName); + + Log.Information("Download of {Filename} from {Username} requested", file.Filename, username); + + using var context = ContextFactory.CreateDbContext(); + + /* + first, get all past downloads from this user for this filename + */ + var existingRecords = context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => t.Username == username) + .Where(t => t.Filename == file.Filename) + .AsNoTracking() + .ToList(); + + var existingInProgressRecords = existingRecords + .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) + .ToList(); + + /* + if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already + an existing transfer record covering this file, and we're already enqueued. nothing more to do! + + check the tracked download dictionary in Soulseek.NET to see if it knows about this already + it shouldn't, if the slskd database doesn't. but things could get desynced + */ + if (existingInProgressRecords.Count != 0 || Client.Downloads.Any(u => u.Username == username && u.Filename == file.Filename)) { - transfer.EndedAt ??= DateTime.UtcNow; - transfer.Exception ??= task.Exception.Message; - transfer.State = TransferStates.Completed | transfer.State; + Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName); + transfer.Exception = "A download for this file from this user is already underway"; + transfer.State = TransferStates.Aborted | TransferStates.Completed; + failed.Add(transfer); + continue; + } - Update(transfer); + /* + we've passed 3 different checks to ensure that this file is not already being downloaded, so + add it to the database and remove any existing (past) records of it from the UI + */ + context.Add(transfer); + + foreach (var record in existingRecords.Where(t => !t.Removed)) + { + record.Removed = true; + context.Update(record); + Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", file.Filename, username, record.Id); } + + context.SaveChanges(); + enqueued.Add(transfer); + + Log.Information("Successfully enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transfer.Id); } catch (Exception ex) { - Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", id, ex.Message); - throw; + // note: there's nothing to cancel or download yet, so any failure to execute the above is an error + Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); + transfer.Exception = ex.Message; + transfer.State = TransferStates.Errored | TransferStates.Completed; + failed.Add(transfer); + continue; } - }, cancellationToken); + } - return Task.FromResult(transfer); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", filename, username, ex.Message); + /* + the files are all now in the database in the Queued | Locally state. - try + we'll proceed with downloading them, but in a separate task run in the background + */ + _ = Task.Run(async () => { - var transfer = Find(t => t.Id == id); + /* + enqueue each of the specified files, waiting to ensure that the remote client has responded to our + request to enqueue before moving on to the next - if (transfer is not null) - { - transfer.EndedAt ??= DateTime.UtcNow; - transfer.Exception ??= ex.Message; - transfer.State = TransferStates.Completed | transfer.State; + we do this because Soulseek.NET sends a TransferRequest/40 which expects a TransferResponse/41 in return, + telling us that either 1) the transfer can begin immediately 2) the transfer was enqueued remotely + or 3) the transfer was rejected - Update(transfer); - } - } - catch (Exception innerEx) - { - Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", id, innerEx.Message); - throw; - } + if at a later date Soulseek.NET is refactored to use different logic, we'll want to rethink this, particularly + to avoid the need to wait for a confirmation from the remote client. - throw; - } - finally - { - if (Locks.TryRemove(lockName, out _)) - { - Log.Debug("Released lock {LockName}", lockName); - } - } - } + note: we can't just fire off all of these requests at the same time, because the remote client will get + overwhelmed, responses will be delayed, and the timeout within Soulseek.NET that's waiting for the + TransferResponse/41 message will expire and fail the download + */ + foreach (var transfer in enqueued) + { + try + { + var enqueuedTcs = new TaskCompletionSource(); + List transitions = []; - /// - /// Enqueues the requested list of . - /// - /// - /// If one file in the specified collection fails, the rest will continue. An will be - /// thrown after all files are dispositioned if any throws. - /// - /// The username of the remote user. - /// The list of files to enqueue. - /// The token to monitor for cancellation. - /// The operation context. - /// Thrown when the username is null or an empty string. - /// Thrown when no files are requested. - /// Thrown when at least one of the requested files throws. - public async Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) - { - if (string.IsNullOrEmpty(username)) - { - throw new ArgumentException("Username is required", nameof(username)); - } + // set a hard limit on the time we are willing to wait for the remote client to confirm or reject + // the enqueue of the file. we have to do this so that we don't get stuck indefinitely + using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(1)); + timeoutCts.Token.Register(() => + { + if (!enqueuedTcs.Task.IsCompleted) + { + Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit. State transition history: {History}", transfer.Filename, username, string.Join(", ", transitions)); + enqueuedTcs.TrySetException(new TimeoutException("Download failed to enqueue remotely after hard time limit")); + } + }); - if (!files.Any()) - { - throw new ArgumentException("At least one file is required", nameof(files)); - } + void stateChanged(Transfer transfer) + { + transitions.Add(transfer.State.ToString()); - List transfers = []; - List exceptions = []; + // _contractually_ (covered by unit tests!) all downloads will at some point enter the Queued | Remotely state + // there _should be_ no way we can get hung up here, but if we do + if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely)) + { + enqueuedTcs.TrySetResult(transfer); + } - /* - enqueue each of the specified files, waiting to ensure that the remote client has responded to our - request to enqueue before moving on to the next + // if something goes wrong and we never get to enqueued, trip the result when we transition into + // completed, so we don't get stuck. we shouldn't take this to mean we were successful, we're just + // trying to ensure we don't get stuck + if (transfer.State.HasFlag(TransferStates.Completed)) + { + enqueuedTcs.TrySetResult(transfer); + } + } - we do this because Soulseek.NET sends a TransferRequest/40 which expects a TransferResponse/41 in return, - telling us that either 1) the transfer can begin immediately 2) the transfer was enqueued remotely - or 3) the transfer was rejected + bool waitForEnqueue = false; - if at a later date Soulseek.NET is refactored to use different logic, we'll want to rethink this, particularly - to avoid the need to wait for a confirmation from the remote client. + // enqueue the file. this call will return when the record has been inserted and the download task + // kicked off. the stateChanged delegate will be passed down to the download task, which will eventually trip it + _ = Task.Run(() => DownloadAsync(transfer, waitForEnqueue ? stateChanged : (_) => { }, cancellationToken)).ContinueWith(task => + { + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); + return; + } - note: we can't just fire off all of these requests at the same time, because the remote client will get - overwhelmed, responses will be delayed, and the timeout within Soulseek.NET that's waiting for the - TransferResponse/41 message will expire and fail the download - */ - foreach (var file in files) - { - if (cancellationToken.IsCancellationRequested) - { - break; - } + /* + things that can cause us to arrive here: - try - { - var enqueuedTcs = new TaskCompletionSource(); - List transitions = []; + * transfer record deleted somehow + * transfer record updated so that it's no longer in Queued | Locally + * Soulseek.NET already tracking an identical download (slskd <> Soulseek.NET desync) + */ + Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", transfer.Filename, transfer.Username, task.Exception.Message); - // set a hard limit on the time we are willing to wait for the remote client to confirm or reject - // the enqueue of the file. we have to do this so that we don't get stuck indefinitely - using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(1)); - timeoutCts.Token.Register(() => - { - if (!enqueuedTcs.Task.IsCompleted) - { - Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit. State transition history: {History}", file.Filename, username, string.Join(", ", transitions)); - enqueuedTcs.TrySetException(new TimeoutException("Download failed to enqueue remotely after hard time limit")); + try + { + var foundTransfer = Find(t => t.Id == transfer.Id); + + if (transfer is not null) + { + transfer.EndedAt ??= DateTime.UtcNow; + transfer.Exception ??= task.Exception.InnerException.Message; + + if (!transfer.State.HasFlag(TransferStates.Completed)) + { + transfer.State = TransferStates.Completed | task.Exception.InnerException switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; + } + + Update(transfer); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message); + } + }, cancellationToken); + + // wait for the download to either enter the Queued | Remotely or Completed states, or for the hard limit + // timeout to trip and set an exception + if (waitForEnqueue) + { + await enqueuedTcs.Task; + } } - }); + catch (Exception ex) + { + Log.Error(ex, "Failed to download {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); - void stateChanged(Transfer transfer) - { - transitions.Add(transfer.State.ToString()); + try + { + var transferRecord = Find(t => t.Id == transfer.Id); - // _contractually_ (covered by unit tests!) all downloads will at some point enter the Queued | Remotely state - // there _should be_ no way we can get hung up here, but if we do - if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely)) - { - enqueuedTcs.TrySetResult(transfer); - } + if (transfer is not null) + { + transfer.EndedAt ??= DateTime.UtcNow; + transfer.Exception ??= ex.Message; + + if (!transfer.State.HasFlag(TransferStates.Completed)) + { + transfer.State = TransferStates.Completed | ex switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; + } + + Update(transfer); + } + } + catch (Exception innerEx) + { + Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); + } - // if something goes wrong and we never get to enqueued, trip the result when we transition into - // completed, so we don't get stuck. we shouldn't take this to mean we were successful, we're just - // trying to ensure we don't get stuck - if (transfer.State.HasFlag(TransferStates.Completed)) - { - enqueuedTcs.TrySetResult(transfer); + continue; } } + }, cancellationToken).ContinueWith(task => + { + if (task.IsCompletedSuccessfully) + { + Log.Warning("Task for enqueue of {Count} files from {Username} completed successfully", files.Count(), username); + return; + } - // enqueue the file. this call will return when the record has been inserted and the download task - // kicked off. the stateChanged delegate will be passed down to the download task, which will eventually trip it - await EnqueueAsync(username, file.Filename, file.Size, stateChanged, cancellationToken); - - // wait for the download to either enter the Queued | Remotely or Completed states, or for the hard limit - // timeout to trip and set an exception - var transfer = await enqueuedTcs.Task; + Log.Error(task.Exception, "Task for enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); + }); - transfers.Add(transfer); - } - catch (Exception ex) - { - exceptions.Add(ex); - } + return (enqueued, failed); } - - if (exceptions.Count != 0) + finally { - throw new AggregateException(exceptions); + foreach (var lockName in acquiredLocks) + { + if (Locks.TryRemove(lockName, out _)) + { + Log.Debug("Released lock {LockName}", lockName); + } + } } - - return transfers.ToList(); } /// -- 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(-) 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(-) 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 ab799665b545d54afab66f3da2eba6295be4b34a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 10 Oct 2025 09:23:14 -0500 Subject: bump Soulseek.NET to 8.3.0 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index ae042d68..7f5c1004 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -68,7 +68,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From 3519905e397f5d2707aefc39db74ccb93fff8f4a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 10 Oct 2025 09:23:35 -0500 Subject: request up to 10 transfers concurrently --- src/slskd/Transfers/Downloads/DownloadService.cs | 205 ++++++++++++----------- 1 file changed, 110 insertions(+), 95 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index e29454c9..81d8394b 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -470,10 +470,6 @@ namespace slskd.Transfers.Downloads /// /// Enqueues the requested list of . /// - /// - /// If one file in the specified collection fails, the rest will continue. An will be - /// thrown after all files are dispositioned if any throws. - /// /// The username of the remote user. /// The list of files to enqueue. /// The token to monitor for cancellation. @@ -481,7 +477,7 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) + public Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -621,78 +617,130 @@ namespace slskd.Transfers.Downloads overwhelmed, responses will be delayed, and the timeout within Soulseek.NET that's waiting for the TransferResponse/41 message will expire and fail the download */ - foreach (var transfer in enqueued) + var concurrentRequests = 10; + var maxTimeToWaitForTransferAck = TimeSpan.FromMinutes(1); + + var semaphore = new SemaphoreSlim(initialCount: concurrentRequests, maxCount: concurrentRequests); + + var tasks = enqueued.Select(async transfer => { + await semaphore.WaitAsync(); + try { - var enqueuedTcs = new TaskCompletionSource(); - List transitions = []; + Log.Debug("Acquired download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); - // set a hard limit on the time we are willing to wait for the remote client to confirm or reject - // the enqueue of the file. we have to do this so that we don't get stuck indefinitely - using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(1)); - timeoutCts.Token.Register(() => + try { - if (!enqueuedTcs.Task.IsCompleted) - { - Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit. State transition history: {History}", transfer.Filename, username, string.Join(", ", transitions)); - enqueuedTcs.TrySetException(new TimeoutException("Download failed to enqueue remotely after hard time limit")); - } - }); + var enqueuedTcs = new TaskCompletionSource(); + List transitions = []; - void stateChanged(Transfer transfer) - { - transitions.Add(transfer.State.ToString()); + // set a hard limit on the time we are willing to wait for the remote client to confirm or reject + // the enqueue of the file. we have to do this so that we don't get stuck indefinitely + using var timeoutCts = new CancellationTokenSource(maxTimeToWaitForTransferAck); + timeoutCts.Token.Register(() => + { + if (!enqueuedTcs.Task.IsCompleted) + { + Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit. State transition history: {History}", transfer.Filename, username, string.Join(", ", transitions)); + enqueuedTcs.TrySetException(new TimeoutException("Download failed to enqueue remotely after hard time limit")); + } + }); - // _contractually_ (covered by unit tests!) all downloads will at some point enter the Queued | Remotely state - // there _should be_ no way we can get hung up here, but if we do - if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely)) + void stateChanged(Transfer transfer) { - enqueuedTcs.TrySetResult(transfer); + transitions.Add(transfer.State.ToString()); + + // _contractually_ (covered by unit tests!) all downloads will at some point enter the Queued | Remotely state + // there _should be_ no way we can get hung up here, but if we do, also check for Completed as a backstop + if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely)) + { + enqueuedTcs.TrySetResult(transfer); + } + + // if something goes wrong and we never get to enqueued, trip the result when we transition into + // completed, so we don't get stuck. we shouldn't take this to mean we were successful, we're just + // trying to ensure we don't get stuck + if (transfer.State.HasFlag(TransferStates.Completed)) + { + if (transfer.State.HasFlag(TransferStates.Succeeded)) + { + enqueuedTcs.TrySetResult(transfer); + } + else + { + enqueuedTcs.TrySetException(new TransferException(transfer.Exception)); + } + } } - // if something goes wrong and we never get to enqueued, trip the result when we transition into - // completed, so we don't get stuck. we shouldn't take this to mean we were successful, we're just - // trying to ensure we don't get stuck - if (transfer.State.HasFlag(TransferStates.Completed)) + // enqueue the file. this call will return when the record has been inserted and the download task + // kicked off. the stateChanged delegate will be passed down to the download task, which will eventually trip it + _ = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken)).ContinueWith(task => { - enqueuedTcs.TrySetResult(transfer); - } - } + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); + return; + } - bool waitForEnqueue = false; + /* + things that can cause us to arrive here: - // enqueue the file. this call will return when the record has been inserted and the download task - // kicked off. the stateChanged delegate will be passed down to the download task, which will eventually trip it - _ = Task.Run(() => DownloadAsync(transfer, waitForEnqueue ? stateChanged : (_) => { }, cancellationToken)).ContinueWith(task => - { - if (task.IsCompletedSuccessfully) - { - Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); - return; - } + * transfer record deleted somehow + * transfer record updated so that it's no longer in Queued | Locally + * Soulseek.NET already tracking an identical download (slskd <> Soulseek.NET desync) + */ + Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", transfer.Filename, transfer.Username, task.Exception.Message); - /* - things that can cause us to arrive here: + try + { + var foundTransfer = Find(t => t.Id == transfer.Id); - * transfer record deleted somehow - * transfer record updated so that it's no longer in Queued | Locally - * Soulseek.NET already tracking an identical download (slskd <> Soulseek.NET desync) - */ - Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", transfer.Filename, transfer.Username, task.Exception.Message); + if (transfer is not null) + { + transfer.EndedAt ??= DateTime.UtcNow; + transfer.Exception ??= task.Exception.InnerException.Message; + + if (!transfer.State.HasFlag(TransferStates.Completed)) + { + transfer.State = TransferStates.Completed | task.Exception.InnerException switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; + } + + Update(transfer); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message); + } + }, cancellationToken); + + // wait for the download to either enter the Queued | Remotely or Completed states, or for the hard limit + // timeout to trip and set an exception + await enqueuedTcs.Task; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to download {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); try { - var foundTransfer = Find(t => t.Id == transfer.Id); + var transferRecord = Find(t => t.Id == transfer.Id); if (transfer is not null) { transfer.EndedAt ??= DateTime.UtcNow; - transfer.Exception ??= task.Exception.InnerException.Message; + transfer.Exception ??= ex.Message; if (!transfer.State.HasFlag(TransferStates.Completed)) { - transfer.State = TransferStates.Completed | task.Exception.InnerException switch + transfer.State = TransferStates.Completed | ex switch { OperationCanceledException => TransferStates.Cancelled, TimeoutException => TransferStates.TimedOut, @@ -703,53 +751,20 @@ namespace slskd.Transfers.Downloads Update(transfer); } } - catch (Exception ex) + catch (Exception innerEx) { - Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message); + Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); } - }, cancellationToken); - - // wait for the download to either enter the Queued | Remotely or Completed states, or for the hard limit - // timeout to trip and set an exception - if (waitForEnqueue) - { - await enqueuedTcs.Task; } } - catch (Exception ex) + finally { - Log.Error(ex, "Failed to download {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); - - try - { - var transferRecord = Find(t => t.Id == transfer.Id); - - if (transfer is not null) - { - transfer.EndedAt ??= DateTime.UtcNow; - transfer.Exception ??= ex.Message; - - if (!transfer.State.HasFlag(TransferStates.Completed)) - { - transfer.State = TransferStates.Completed | ex switch - { - OperationCanceledException => TransferStates.Cancelled, - TimeoutException => TransferStates.TimedOut, - _ => TransferStates.Errored, - }; - } - - Update(transfer); - } - } - catch (Exception innerEx) - { - Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); - } - - continue; + semaphore.Release(); + Log.Debug("Released download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); } - } + }); + + await Task.WhenAll(tasks); }, cancellationToken).ContinueWith(task => { if (task.IsCompletedSuccessfully) @@ -759,9 +774,9 @@ namespace slskd.Transfers.Downloads } Log.Error(task.Exception, "Task for enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); - }); + }, cancellationToken: CancellationToken.None); - return (enqueued, failed); + return Task.FromResult((enqueued, failed)); } finally { -- cgit v1.2.3 From 4936f6eb85c84cd2986721c21b8acd64bf1a1de6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 10 Oct 2025 09:31:25 -0500 Subject: return early if there's nothing to enqueue --- src/slskd/Transfers/Downloads/DownloadService.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 81d8394b..ba88777c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -595,6 +595,11 @@ namespace slskd.Transfers.Downloads } } + if (enqueued.Count == 0) + { + return (enqueued, failed); + } + /* the files are all now in the database in the Queued | Locally state. -- cgit v1.2.3 From e66714d0d51552b7228e5deeb4c08d1f2c9c49e3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 10 Oct 2025 09:31:41 -0500 Subject: get the user's endpoint before we start (make sure they are online) --- src/slskd/Transfers/Downloads/DownloadService.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index ba88777c..6a149ff8 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -489,6 +489,19 @@ namespace slskd.Transfers.Downloads throw new ArgumentException("At least one file is required", nameof(files)); } + IPEndPoint endpoint; + + try + { + // get the user's ip and port. this will throw if they are offline. + endpoint = await Client.GetUserEndPointAsync(username, cancellationToken); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue {Count} files from {Username}: {Message}", files.Count(), username, ex.Message); + throw; + } + List acquiredLocks = []; try -- cgit v1.2.3 From b5b4f6d7cbc1bdfaa0c4b659030872e83facafdb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 10 Oct 2025 09:31:58 -0500 Subject: prime the peer connection cache before starting downloads --- src/slskd/Transfers/Downloads/DownloadService.cs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 6a149ff8..c8f82167 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -25,6 +25,8 @@ namespace slskd.Transfers.Downloads using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; + using System.Net; + using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; @@ -477,7 +479,7 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - public Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) + public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -613,6 +615,17 @@ namespace slskd.Transfers.Downloads return (enqueued, failed); } + // prime the cache for this user, to 1) make sure we can connect, and 2) avoid needing to race for it in the loop + try + { + await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message); + throw; + } + /* the files are all now in the database in the Queued | Locally state. @@ -794,7 +807,7 @@ namespace slskd.Transfers.Downloads Log.Error(task.Exception, "Task for enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); }, cancellationToken: CancellationToken.None); - return Task.FromResult((enqueued, failed)); + return (enqueued, failed); } finally { -- cgit v1.2.3 From 515b0910ab63100c7421c30211ff1c932c70c6f5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 10 Oct 2025 18:13:12 -0500 Subject: space --- src/slskd/Transfers/Downloads/DownloadService.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index c8f82167..a462f3de 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -26,7 +26,6 @@ namespace slskd.Transfers.Downloads using System.Linq; using System.Linq.Expressions; using System.Net; - using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; -- cgit v1.2.3