From ce33585c58a35d9616fa77204c82cd02fc27c553 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Oct 2025 17:50:26 -0500 Subject: get rid of the confusing 't' --- src/slskd/Transfers/Uploads/UploadService.cs | 68 +++++++++++++++------------- 1 file changed, 37 insertions(+), 31 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 6db9f6a5..ee6185cc 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -69,7 +69,7 @@ namespace slskd.Transfers.Uploads /// /// Uploads the specified enqueued to the requesting user. /// - /// The transfer to upload. + /// The Transfer to upload. /// The operation context. /// Thrown if the specified Transfer is null. /// Thrown if the specified Transfer ID can't be found in the database. @@ -211,7 +211,7 @@ namespace slskd.Transfers.Uploads /// /// Uploads the specified enqueued to the requesting user. /// - /// The transfer to upload. + /// The Transfer to upload. /// The operation context. /// Thrown if the specified Transfer is null. /// Thrown if the specified Transfer ID can't be found in the database. @@ -228,7 +228,7 @@ namespace slskd.Transfers.Uploads return null; } - Transfer t = transfer; + Log.Debug("Acquired lock {LockName}", lockName); /* fetch an updated copy of the transfer record from the database; now that we are locked, we *should* @@ -237,12 +237,12 @@ namespace slskd.Transfers.Uploads we're not using DbContext and tracked changes here because we don't want to hold a connection open for the duration of the upload */ - t = Find(t => t.Id == transfer.Id) + transfer = Find(t => t.Id == transfer.Id) ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); - if (t.State != (TransferStates.Queued | TransferStates.Locally)) + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) { - throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {t.State}"); + throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); } /* @@ -250,7 +250,7 @@ namespace slskd.Transfers.Uploads check that list to see if there's already an instance of this upload in it, just in case we've gotten out of sync somehow */ - if (Client.Uploads.Any(u => u.Username == t.Username && u.Filename == t.Filename)) + if (Client.Uploads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) { throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered"); } @@ -259,14 +259,14 @@ namespace slskd.Transfers.Uploads // statistics. this is so that we can accurately determine their effective group. try { - if (!Users.IsWatched(t.Username)) + if (!Users.IsWatched(transfer.Username)) { - await Users.WatchAsync(t.Username); + await Users.WatchAsync(transfer.Username); } } catch (Exception ex) { - Log.Warning(ex, "Failed to watch user {Username}", t.Username); + Log.Warning(ex, "Failed to watch user {Username}", transfer.Username); } var cts = new CancellationTokenSource(); @@ -300,25 +300,24 @@ namespace slskd.Transfers.Uploads */ try { - Log.Debug("Acquired lock {LockName}", lockName); - Log.Information("Initializing upload {Filename} to {Username}", t.Filename, t.Username); + Log.Information("Initializing upload of {Filename} to {Username}", transfer.Filename, transfer.Username); // locate the file on disk. we checked this once already when enqueueing, but it may have moved since // can throw NotFoundException - (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: t.Filename); + (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: transfer.Filename); using var rateLimiter = new RateLimiter(250, flushOnDispose: true); var topts = new TransferOptions( stateChanged: (args) => { - Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, t.Username, args.PreviousState, args.Transfer.State); + Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, 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) { - Log.Debug("Upload update of {Filename} to {Username} not persisted; app is shutting down", t.Filename, t.Username); + Log.Debug("Upload update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); return; } @@ -367,10 +366,10 @@ namespace slskd.Transfers.Uploads slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); // register the cancellation token - CancellationTokens.TryAdd(t.Id, cts); + CancellationTokens.TryAdd(transfer.Id, cts); // add the transfer to the UploadQueue so that it can become eligible for selection - Queue.Enqueue(t.Username, t.Filename); + Queue.Enqueue(transfer.Username, transfer.Filename); transfer.EnqueuedAt = DateTime.UtcNow; SynchronizedUpdate(transfer); @@ -379,8 +378,8 @@ namespace slskd.Transfers.Uploads if (host == Program.LocalHostName) { completedTransfer = await Client.UploadAsync( - username: t.Username, - remoteFilename: t.Filename, + username: transfer.Username, + remoteFilename: transfer.Filename, size: localFileLength, inputStreamFactory: (startOffset) => { @@ -398,14 +397,14 @@ namespace slskd.Transfers.Uploads else { completedTransfer = await Client.UploadAsync( - username: t.Username, - remoteFilename: t.Filename, + username: transfer.Username, + remoteFilename: transfer.Filename, size: localFileLength, - inputStreamFactory: (startOffset) => Relay.GetFileStreamAsync(agentName: host, filename: t.Filename, startOffset, id: t.Id), + inputStreamFactory: (startOffset) => Relay.GetFileStreamAsync(agentName: host, filename: transfer.Filename, startOffset, id: transfer.Id), options: topts, cancellationToken: cts.Token); - Relay.TryCloseFileStream(host, id: t.Id); + Relay.TryCloseFileStream(host, id: transfer.Id); } // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we @@ -423,7 +422,7 @@ namespace slskd.Transfers.Uploads { Timestamp = transfer.EndedAt.Value, LocalFilename = localFilename, - RemoteFilename = t.Filename, + RemoteFilename = transfer.Filename, Transfer = transfer, }); @@ -439,11 +438,18 @@ namespace slskd.Transfers.Uploads throw; } - catch (OperationCanceledException ex) + catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) { transfer.EndedAt = DateTime.UtcNow; transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Cancelled; + transfer.State = TransferStates.Completed; + + transfer.State |= ex switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; // todo: broadcast SynchronizedUpdate(transfer, cancellable: false); @@ -452,7 +458,7 @@ namespace slskd.Transfers.Uploads } catch (Exception ex) { - Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", t.Filename, t.Username, ex.Message); + Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); transfer.EndedAt = DateTime.UtcNow; transfer.Exception = ex.Message; @@ -469,7 +475,7 @@ namespace slskd.Transfers.Uploads { try { - Relay.TryCloseFileStream(host, id: t.Id); + Relay.TryCloseFileStream(host, id: transfer.Id); } catch { @@ -482,16 +488,16 @@ namespace slskd.Transfers.Uploads Locks.TryRemove(lockName, out _); Log.Debug("Released lock {LockName}", lockName); - CancellationTokens.TryRemove(t.Id, out _); + CancellationTokens.TryRemove(transfer.Id, out _); // if for some reason this logic exits without the slotReleased delegate and Complete() being invoked, // the file will get stuck in the queue and prevent any further uploads to the user. be extra cautious // and ensure it gets removed - Queue.TryComplete(username: t.Username, filename: t.Filename); + Queue.TryComplete(username: transfer.Username, filename: transfer.Filename); } catch (Exception ex) { - Log.Error(ex, "Failed to finalize upload of {Filename} to {Username}: {Message}", t.Filename, t.Username, ex.Message); + Log.Error(ex, "Failed to finalize upload of {Filename} to {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); throw; } } -- cgit v1.2.3 From ef9acb6f51294737546c28cc330563b55f90d1a7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Oct 2025 17:55:27 -0500 Subject: implement DownloadAsync --- src/slskd/Transfers/Downloads/DownloadService.cs | 292 ++++++++++++++++++++++- 1 file changed, 289 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index ef8e84bf..72d762c0 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -59,7 +59,18 @@ 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); + Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + + /// + /// Downloads the specified enqueued from the remote user. + /// + /// The Transfer to download. + /// The operation context. + /// Thrown if the specified Transfer is null. + /// Thrown if the specified Transfer ID can't be found in the database. + /// Thrown if the specified Transfer is not in the Queued | Locally state. + /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. + Task DownloadAsync(Transfer transfer); /// /// Finds a single download matching the specified . @@ -144,6 +155,7 @@ namespace slskd.Transfers.Downloads private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private EventBus EventBus { get; } + private ConcurrentDictionary Locks { get; } = new(); /// /// Adds the specified . Supersedes any existing record for the same file and username. @@ -171,6 +183,278 @@ namespace slskd.Transfers.Downloads context.SaveChanges(); } + /// + /// Downloads the specified enqueued from the remote user. + /// + /// The Transfer to download. + /// The operation context. + /// Thrown if the specified Transfer is null. + /// Thrown if the specified Transfer ID can't be found in the database. + /// Thrown if the specified Transfer is not in the Queued | Locally state. + /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. + public async Task DownloadAsync(Transfer transfer) + { + var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; + + if (!Locks.TryAdd(lockName, true)) + { + Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); + return null; + } + + Log.Debug("Acquired lock {LockName}", lockName); + + /* + fetch an updated copy of the transfer record from the database; now that we are locked, we *should* + have exclusive access to this record + + we're not using DbContext and tracked changes here because we don't want to hold a connection + open for the duration of the download + */ + transfer = Find(t => t.Id == transfer.Id) + ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + + /* + Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; + check that list to see if there's already an instance of this download in it, just in case we've gotten + out of sync somehow + */ + if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) + { + throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); + } + + var cts = new CancellationTokenSource(); + var syncRoot = new SemaphoreSlim(1, 1); + + void SynchronizedUpdate(Transfer transfer, bool cancellable = true) + { + syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); + + try + { + Update(transfer); + } + finally + { + syncRoot.Release(); + } + } + + /* + from this point forward, any exit from this method MUST result in an update to the Transfer record + in the database that sets EndedAt and ensures that the State property includes the Completed flag + + failure to do so means records will get "stuck" in the database/on the UI + + additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot + */ + try + { + Log.Information("Initializing download of {Filename} from {Username}", transfer.Filename, transfer.Username); + + using var rateLimiter = new RateLimiter(250, flushOnDispose: true); + + 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) + { + Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); + return; + } + + transfer = transfer.WithSoulseekTransfer(args.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 (transfer.EnqueuedAt is null && args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) + { + transfer.EnqueuedAt = DateTime.UtcNow; + } + + // todo: broadcast + SynchronizedUpdate(transfer); + }, + progressUpdated: (args) => rateLimiter.Invoke(() => + { + // don't do anything unless the `transfer` within the outer scope is in the + // InProgress state; this will help prevent out-of-band updates that are sometimes + // being made after the transfer is completed, causing them to appear 'stuck' + if (transfer.State == TransferStates.InProgress) + { + syncRoot.Wait(cts.Token); + + try + { + // check again to see if the state changed while we were waiting to obtain the lock + if (transfer.State == TransferStates.InProgress) + { + // update only the properties that we expect to change between progress updates + // this helps prevent this update from 'stepping' on other updates + transfer.BytesTransferred = args.Transfer.BytesTransferred; + transfer.AverageSpeed = args.Transfer.AverageSpeed; + + using var context = ContextFactory.CreateDbContext(); + + context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + } + } + finally + { + syncRoot.Release(); + } + } + }), + disposeOutputStreamOnCompletion: true); + + // register the cancellation token + CancellationTokens.TryAdd(transfer.Id, cts); + + var completedTransfer = await Client.DownloadAsync( + username: transfer.Username, + remoteFilename: transfer.Filename, + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + options: new CreateFileOptions + { + Access = System.IO.FileAccess.Write, + Mode = System.IO.FileMode.Create, // overwrites file if it exists + Share = System.IO.FileShare.None, // exclusive access for the duration of the download + UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() + : null, + })), + size: transfer.Size, + startOffset: 0, + token: null, + cancellationToken: cts.Token, + options: topts); + + // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we + // flushe any pending update, _probably_ pushing the state of the transfer back to InProgress + rateLimiter.Dispose(); + + // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state + // over the top of the transfer record, then persist it + transfer = transfer.WithSoulseekTransfer(completedTransfer); + + // todo: broadcast to signalr hub + SynchronizedUpdate(transfer, cancellable: false); + + // move the file from incomplete to complete + var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); + + var finalFilename = Files.MoveFile( + sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + destinationDirectory: destinationDirectory, + overwrite: false, + deleteSourceDirectoryIfEmptyAfterMove: true); + + Log.Debug("Moved file to {Destination}", finalFilename); + + // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, + // and the file has been moved from the incomplete directory to the downloads directory + if (OptionsMonitor.CurrentValue.Relay.Enabled) + { + _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); + } + + EventBus.Raise(new DownloadFileCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + LocalFilename = finalFilename, + RemoteFilename = transfer.Filename, + Transfer = transfer, + }); + + // try to figure out if this file is the last of a directory, and if so, raise the associated + // event. this can be tricky because we want to be sure that this is the last file in this specific + // directory, excluding any pending downloads in a subdirectory. + var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); + var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); + var pendingDownloadsInDirectory = Client.Downloads + .Where(t => t.Username == transfer.Username) + .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); + + if (!pendingDownloadsInDirectory.Any()) + { + EventBus.Raise(new DownloadDirectoryCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + Username = transfer.Username, + LocalDirectoryName = destinationDirectory, + RemoteDirectoryName = remoteDirectoryName, + }); + } + + if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) + { + _ = FTP.UploadAsync(finalFilename); + } + + return transfer; + } + catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) + { + transfer.EndedAt = DateTime.UtcNow; + transfer.Exception = ex.Message; + transfer.State = TransferStates.Completed; + + transfer.State |= ex switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; + + // todo: broadcast + SynchronizedUpdate(transfer, cancellable: false); + + throw; + } + catch (Exception ex) + { + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); + + transfer.EndedAt = DateTime.UtcNow; + transfer.Exception = ex.Message; + transfer.State = TransferStates.Completed | TransferStates.Errored; + + // todo: broadcast + SynchronizedUpdate(transfer, cancellable: false); + + throw; + } + finally + { + try + { + Locks.TryRemove(lockName, out _); + Log.Debug("Released lock {LockName}", lockName); + + CancellationTokens.TryRemove(transfer.Id, out _); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to finalize download of {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); + throw; + } + } + } + /// /// Enqueues the requested list of . /// @@ -184,7 +468,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 EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) + public Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) { if (string.IsNullOrEmpty(username)) { @@ -198,7 +482,7 @@ namespace slskd.Transfers.Downloads return EnqueueAsyncInternal(username, files); - async Task EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files) + async Task> EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files) { try { @@ -208,6 +492,7 @@ namespace slskd.Transfers.Downloads await Client.ConnectToUserAsync(username, invalidateCache: false); Log.Debug("Connection for user '{Username}' primed", username); + var transfers = new List(); var thrownExceptions = new List(); foreach (var file in files) @@ -460,6 +745,7 @@ namespace slskd.Transfers.Downloads } Log.Information("Successfully enqueued {Count} file(s) from user {Username}", files.Count(), username); + return transfers; } catch (Exception ex) { -- cgit v1.2.3 From 8e6bb172f5626dc8058b1b40934e1e5b84b01f37 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Oct 2025 19:03:50 -0500 Subject: minor tweaks --- src/slskd/Transfers/Uploads/UploadService.cs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index ee6185cc..8fa08cea 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -511,11 +511,21 @@ namespace slskd.Transfers.Uploads /// The operation context. public async Task EnqueueAsync(string username, string filename) { + if (string.IsNullOrEmpty(username)) + { + throw new ArgumentNullException(nameof(username), "Username is required"); + } + + if (string.IsNullOrEmpty(filename)) + { + throw new ArgumentNullException(nameof(filename), "Filename is required"); + } + var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}"; if (!Locks.TryAdd(lockName, true)) { - Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); + Log.Debug("Ignoring concurrent upload enqueue attempt; lock {LockName} already held", lockName); return null; } @@ -606,7 +616,7 @@ namespace slskd.Transfers.Uploads { record.Removed = true; context.Update(record); - Log.Debug("Marked existing upload record {Filename} to {Username} removed (id: {Id})", filename, username, record.Id); + Log.Debug("Marked existing upload record of {Filename} to {Username} removed (id: {Id})", filename, username, record.Id); } context.SaveChanges(); @@ -700,8 +710,10 @@ namespace slskd.Transfers.Uploads } finally { - Locks.TryRemove(lockName, out _); - Log.Debug("Released lock {LockName}", lockName); + if (Locks.TryRemove(lockName, out _)) + { + Log.Debug("Released lock {LockName}", lockName); + } } } -- cgit v1.2.3 From 5c5318b6f1f3aac1a0eda59090c89ad0dd27ca46 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Oct 2025 19:04:43 -0500 Subject: add singular EnqueueAsync, simplify multiple variant --- src/slskd/Transfers/Downloads/DownloadService.cs | 434 ++++++++++------------- 1 file changed, 179 insertions(+), 255 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 72d762c0..bf501c33 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -61,6 +61,15 @@ namespace slskd.Transfers.Downloads /// Thrown when at least one of the requested files throws. Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + /// + /// Enqueues the specified from the specified . + /// + /// The username of remote user. + /// The remote filename to download. + /// The size of the file. + /// The operation context. + Task EnqueueAsync(string username, string filename, long size); + /// /// Downloads the specified enqueued from the remote user. /// @@ -456,303 +465,218 @@ namespace slskd.Transfers.Downloads } /// - /// Enqueues the requested list of . + /// Enqueues the specified from the specified . /// - /// - /// 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 username of remote user. + /// The remote filename to download. + /// The size of the file. /// 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 Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) + public Task EnqueueAsync(string username, string filename, long size) { if (string.IsNullOrEmpty(username)) { - throw new ArgumentException("Username is required", nameof(username)); + throw new ArgumentNullException(nameof(username), "Username is required"); } - if (!files.Any()) + if (string.IsNullOrEmpty(filename)) + { + throw new ArgumentNullException(nameof(filename), "Filename is required"); + } + + if (size <= 0) { - throw new ArgumentException("At least one file is require", nameof(files)); + throw new ArgumentOutOfRangeException(nameof(size), "Size must be greater than zero"); } - return EnqueueAsyncInternal(username, files); + var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}"; - async Task> EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files) + if (!Locks.TryAdd(lockName, true)) { - try - { - Log.Information("Downloading {Count} files from user {Username}", files.Count(), username); + Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} a;ready held", lockName); + return null; + } - Log.Debug("Priming connection for user {Username}", username); - await Client.ConnectToUserAsync(username, invalidateCache: false); - Log.Debug("Connection for user '{Username}' primed", username); + Guid id = Guid.NewGuid(); - var transfers = new List(); - var thrownExceptions = new List(); + try + { + Log.Debug("Acquired lock {LockName}", lockName); - foreach (var file in files) - { - Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username); + Log.Information("Download of {Filename} from {Username} requested", filename, username); - var id = Guid.NewGuid(); + using var context = ContextFactory.CreateDbContext(); - var transfer = new Transfer() - { - Id = id, - Username = username, - Direction = TransferDirection.Download, - Filename = file.Filename, - Size = file.Size, - StartOffset = 0, - RequestedAt = DateTime.UtcNow, - }; - - // persist the transfer to the database so we have a record that it was attempted - AddOrSupersede(transfer); - - var cts = new CancellationTokenSource(); - CancellationTokens.TryAdd(id, cts); - - var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - // this task does the actual work of downloading the file. if the transfer is successfully queued - // remotely, the waitUntilEnqueue completion source is set, which yields execution to below so we can - // return and let the caller know. - var downloadTask = Task.Run(async () => - { - using var rateLimiter = new RateLimiter(250, flushOnDispose: true); - var syncRoot = new SemaphoreSlim(1, 1); + /* + 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(); - void SynchronizedUpdate(Transfer transfer, bool cancellable = true) - { - syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); + var existingInProgressRecords = existingRecords + .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) + .ToList(); - try - { - Update(transfer); - } - finally - { - syncRoot.Release(); - } - } + /* + 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; + } - try - { - var topts = new TransferOptions( - disposeOutputStreamOnCompletion: true, - stateChanged: (args) => - { - Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, args.PreviousState, args.Transfer.State); - - if (Application.IsShuttingDown) - { - Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", file.Filename, username); - return; - } - - transfer = transfer.WithSoulseekTransfer(args.Transfer); - - if ((args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) || args.Transfer.State == TransferStates.Initializing) - { - transfer.EnqueuedAt = DateTime.UtcNow; - waitUntilEnqueue.TrySetResult(true); - } - - SynchronizedUpdate(transfer); - }, - progressUpdated: (args) => rateLimiter.Invoke(() => - { - // don't do anything unless the `transfer` within the outer scope is in the - // InProgress state; this will help prevent out-of-band updates that are sometimes - // being made after the transfer is completed, causing them to appear 'stuck' - if (transfer.State == TransferStates.InProgress) - { - syncRoot.Wait(cts.Token); - - try - { - // check again to see if the state changed while we were waiting to obtain the lock - if (transfer.State == TransferStates.InProgress) - { - // update only the properties that we expect to change between progress updates - // this helps prevent this update from 'stepping' on other updates - transfer.BytesTransferred = args.Transfer.BytesTransferred; - transfer.AverageSpeed = args.Transfer.AverageSpeed; - - using var context = ContextFactory.CreateDbContext(); - - context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter - .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); - } - } - finally - { - syncRoot.Release(); - } - } - })); - - var completedTransfer = await Client.DownloadAsync( - username: username, - remoteFilename: file.Filename, - outputStreamFactory: () => Task.FromResult( - Files.CreateFile( - filename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - options: new CreateFileOptions - { - Access = System.IO.FileAccess.Write, - Mode = System.IO.FileMode.Create, // overwrites file if it exists - Share = System.IO.FileShare.None, // exclusive access for the duration of the download - UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) - ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() - : null, - })), - size: file.Size, - startOffset: 0, - token: null, - cancellationToken: cts.Token, - options: topts); - - // explicitly dispose the rate limiter to prevent updates from it - // beyond this point, which may overwrite the final state - rateLimiter.Dispose(); - - transfer = transfer.WithSoulseekTransfer(completedTransfer); - - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); - - var destinationDirectory = System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); - - var finalFilename = Files.MoveFile( - sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - destinationDirectory: destinationDirectory, - overwrite: false, - deleteSourceDirectoryIfEmptyAfterMove: true); - - Log.Debug("Moved file to {Destination}", finalFilename); - - // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, - // and the file has been moved from the incomplete directory to the downloads directory - if (OptionsMonitor.CurrentValue.Relay.Enabled) - { - _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); - } + /* + 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"); + } - EventBus.Raise(new DownloadFileCompleteEvent - { - Timestamp = transfer.EndedAt.Value, - LocalFilename = finalFilename, - RemoteFilename = transfer.Filename, - Transfer = transfer, - }); - - // try to figure out if this file is the last of a directory, and if so, raise the associated - // event. this can be tricky because we want to be sure that this is the last file in this specific - // directory, excluding any pending downloads in a subdirectory. - var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); - var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); - var pendingDownloadsInDirectory = Client.Downloads - .Where(t => t.Username == transfer.Username) - .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); - - if (!pendingDownloadsInDirectory.Any()) - { - EventBus.Raise(new DownloadDirectoryCompleteEvent - { - Timestamp = transfer.EndedAt.Value, - Username = transfer.Username, - LocalDirectoryName = destinationDirectory, - RemoteDirectoryName = remoteDirectoryName, - }); - } + /* + 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, + }; - if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) - { - _ = FTP.UploadAsync(finalFilename); - } - } - catch (OperationCanceledException ex) - { - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Cancelled; + context.Add(transfer); - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); + 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); + } - throw; - } - catch (Exception ex) - { - Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", file.Filename, username, ex.Message); + context.SaveChanges(); - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Errored; + Log.Information("Successfully enqueued download of {Filename} from {Username} (id: {Id})", filename, username, id); - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); + /* + schedule the download immediately - throw; - } - finally - { - CancellationTokens.TryRemove(id, out _); - } - }); + Task.Run can fail due to thread pool exhaustion or OOM, and this *SHOULD* throw up the chain and + fail the enqueue request + */ + _ = Task.Run(() => DownloadAsync(transfer)).ContinueWith(task => + { + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for download of {Filename} from {Username} completed successfully", filename, username); + return; + } - // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or - // the downloadTask throws due to an error prior to successfully queueing. - var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask); + /* + things that can cause us to arrive here: - // if the download task completed first it is a very good indication that it threw an exception or was - // otherwise not successful. try to figure out why and update everything to reflect the failure, but - // continue processing the batch - if (task == downloadTask) - { - Exception ex = downloadTask.Exception; + * 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); - // todo: figure out why this needs to be unwrapped just for this one case. is this always an aggregate? - if (ex is AggregateException aggEx) - { - var rejected = aggEx.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); - if (rejected.Any()) - { - ex = rejected.First(); - } - } + try + { + var transfer = Find(t => t.Id == id); - Log.Error("Failed to download {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); - thrownExceptions.Add(ex); - } - else + if (transfer is not null) { - Log.Debug("Successfully enqueued {Filename} from user {Username}", file.Filename, username); + transfer.EndedAt ??= DateTime.UtcNow; + transfer.Exception ??= task.Exception.Message; + transfer.State = TransferStates.Completed | transfer.State; + + Update(transfer); } } - - if (thrownExceptions.Any()) + catch (Exception ex) { - throw new AggregateException(thrownExceptions); + Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", id, ex.Message); + throw; } + }); + + return Task.FromResult(transfer); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", filename, username, ex.Message); + + try + { + var transfer = Find(t => t.Id == id); - Log.Information("Successfully enqueued {Count} file(s) from user {Username}", files.Count(), username); - return transfers; + if (transfer is not null) + { + transfer.EndedAt ??= DateTime.UtcNow; + transfer.Exception ??= ex.Message; + transfer.State = TransferStates.Completed | transfer.State; + + Update(transfer); + } } - catch (Exception ex) + catch (Exception innerEx) { - Log.Error(ex, "Failed to download one or more files from user {Username}: {Message}", username, ex.Message); + Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", id, innerEx.Message); throw; } + + throw; } + finally + { + if (Locks.TryRemove(lockName, out _)) + { + Log.Debug("Released lock {LockName}", lockName); + } + } + } + + /// + /// 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 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) + { + if (string.IsNullOrEmpty(username)) + { + throw new ArgumentException("Username is required", nameof(username)); + } + + if (!files.Any()) + { + throw new ArgumentException("At least one file is required", nameof(files)); + } + + var tasks = files.Select(file => EnqueueAsync(username, file.Filename, file.Size)); + + var transfers = await Task.WhenAll(tasks); + + return transfers.ToList(); } /// -- cgit v1.2.3 From efcc4bc19ec53b464304d1afa9eeb2d4c181c9c3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 3 Oct 2025 19:07:27 -0500 Subject: Update src/slskd/Transfers/Downloads/DownloadService.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bf501c33..3a8e52e9 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -492,7 +492,7 @@ namespace slskd.Transfers.Downloads if (!Locks.TryAdd(lockName, true)) { - Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} a;ready held", lockName); + Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName); return null; } -- cgit v1.2.3 From c8e43f739b967470900072530ca7138c3b18b106 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 4 Oct 2025 17:58:00 -0500 Subject: move checks inside try/catch --- src/slskd/Transfers/Downloads/DownloadService.cs | 50 +++++++-------- src/slskd/Transfers/Uploads/UploadService.cs | 78 ++++++++++++------------ 2 files changed, 64 insertions(+), 64 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bf501c33..eafbf388 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -213,31 +213,6 @@ namespace slskd.Transfers.Downloads Log.Debug("Acquired lock {LockName}", lockName); - /* - fetch an updated copy of the transfer record from the database; now that we are locked, we *should* - have exclusive access to this record - - we're not using DbContext and tracked changes here because we don't want to hold a connection - open for the duration of the download - */ - transfer = Find(t => t.Id == transfer.Id) - ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); - - if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) - { - throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); - } - - /* - Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; - check that list to see if there's already an instance of this download in it, just in case we've gotten - out of sync somehow - */ - if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) - { - throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); - } - var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); @@ -265,6 +240,31 @@ namespace slskd.Transfers.Downloads */ try { + /* + fetch an updated copy of the transfer record from the database; now that we are locked, we *should* + have exclusive access to this record + + we're not using DbContext and tracked changes here because we don't want to hold a connection + open for the duration of the download + */ + transfer = Find(t => t.Id == transfer.Id) + ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + + /* + Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; + check that list to see if there's already an instance of this download in it, just in case we've gotten + out of sync somehow + */ + if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) + { + throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); + } + Log.Information("Initializing download of {Filename} from {Username}", transfer.Filename, transfer.Username); using var rateLimiter = new RateLimiter(250, flushOnDispose: true); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 8fa08cea..bd167a57 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -230,45 +230,6 @@ namespace slskd.Transfers.Uploads Log.Debug("Acquired lock {LockName}", lockName); - /* - fetch an updated copy of the transfer record from the database; now that we are locked, we *should* - have exclusive access to this record - - we're not using DbContext and tracked changes here because we don't want to hold a connection - open for the duration of the upload - */ - transfer = Find(t => t.Id == transfer.Id) - ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); - - if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) - { - throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); - } - - /* - Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; - check that list to see if there's already an instance of this upload in it, just in case we've gotten - out of sync somehow - */ - if (Client.Uploads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) - { - throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered"); - } - - // users with uploads must be watched so that we can keep informed of their online status, privileges, and - // statistics. this is so that we can accurately determine their effective group. - try - { - if (!Users.IsWatched(transfer.Username)) - { - await Users.WatchAsync(transfer.Username); - } - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to watch user {Username}", transfer.Username); - } - var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); @@ -300,6 +261,45 @@ namespace slskd.Transfers.Uploads */ try { + /* + fetch an updated copy of the transfer record from the database; now that we are locked, we *should* + have exclusive access to this record + + we're not using DbContext and tracked changes here because we don't want to hold a connection + open for the duration of the upload + */ + transfer = Find(t => t.Id == transfer.Id) + ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + + /* + Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; + check that list to see if there's already an instance of this upload in it, just in case we've gotten + out of sync somehow + */ + if (Client.Uploads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) + { + throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered"); + } + + // users with uploads must be watched so that we can keep informed of their online status, privileges, and + // statistics. this is so that we can accurately determine their effective group. + try + { + if (!Users.IsWatched(transfer.Username)) + { + await Users.WatchAsync(transfer.Username); + } + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to watch user {Username}", transfer.Username); + } + Log.Information("Initializing upload of {Filename} to {Username}", transfer.Filename, transfer.Username); // locate the file on disk. we checked this once already when enqueueing, but it may have moved since -- cgit v1.2.3 From 845f6406c079d082e4ea9683b3c1966698967c90 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 4 Oct 2025 17:59:22 -0500 Subject: delay lock acquisition --- src/slskd/Transfers/Downloads/DownloadService.cs | 20 ++++++++++---------- src/slskd/Transfers/Uploads/UploadService.cs | 19 ++++++++++--------- 2 files changed, 20 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index eafbf388..be9278b2 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -203,16 +203,6 @@ namespace slskd.Transfers.Downloads /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. public async Task DownloadAsync(Transfer transfer) { - var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; - - if (!Locks.TryAdd(lockName, true)) - { - Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); - return null; - } - - Log.Debug("Acquired lock {LockName}", lockName); - var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); @@ -230,6 +220,14 @@ namespace slskd.Transfers.Downloads } } + var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; + + if (!Locks.TryAdd(lockName, true)) + { + Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); + return null; + } + /* from this point forward, any exit from this method MUST result in an update to the Transfer record in the database that sets EndedAt and ensures that the State property includes the Completed flag @@ -240,6 +238,8 @@ namespace slskd.Transfers.Downloads */ try { + Log.Debug("Acquired lock {LockName}", lockName); + /* fetch an updated copy of the transfer record from the database; now that we are locked, we *should* have exclusive access to this record diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index bd167a57..89700eba 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -220,15 +220,6 @@ namespace slskd.Transfers.Uploads /// Thrown if the specified file can't be found on disk. public async Task UploadAsync(Transfer transfer) { - var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}"; - - if (!Locks.TryAdd(lockName, true)) - { - Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); - return null; - } - - Log.Debug("Acquired lock {LockName}", lockName); var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); @@ -251,6 +242,14 @@ namespace slskd.Transfers.Uploads string localFilename = default; long localFileLength = default; + var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}"; + + if (!Locks.TryAdd(lockName, true)) + { + Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); + return null; + } + /* from this point forward, any exit from this method MUST result in an update to the Transfer record in the database that sets EndedAt and ensures that the State property includes the Completed flag @@ -261,6 +260,8 @@ namespace slskd.Transfers.Uploads */ try { + Log.Debug("Acquired lock {LockName}", lockName); + /* fetch an updated copy of the transfer record from the database; now that we are locked, we *should* have exclusive access to this record -- cgit v1.2.3 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') 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 51dd617a7ebe5f4ad0a4d0312b79f58e0f3363fe Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Oct 2025 00:50:12 -0500 Subject: bump Soulseek.NET to 8.1.2 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index d6e977cb..49e48552 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 71ac8cdb186b2066ee604303ba8d8c6bd20488d3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Oct 2025 00:59:45 -0500 Subject: enqueue files one at a time --- src/slskd/Transfers/Downloads/DownloadService.cs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bd271a89..8969eeaf 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -672,9 +672,25 @@ namespace slskd.Transfers.Downloads throw new ArgumentException("At least one file is required", nameof(files)); } - var tasks = files.Select(file => EnqueueAsync(username, file.Filename, file.Size)); + List transfers = []; + List exceptions = []; - var transfers = await Task.WhenAll(tasks); + foreach (var file in files) + { + try + { + transfers.Add(await EnqueueAsync(username, file.Filename, file.Size)); + } + catch (Exception ex) + { + exceptions.Add(ex); + } + } + + if (exceptions.Any()) + { + throw new AggregateException(exceptions); + } return transfers.ToList(); } -- 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') 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 609d4112d1cc4504ee0cc2030d9ba9dc91ad4841 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Oct 2025 16:46:29 -0500 Subject: set raiseEventsAsynchronously flag --- src/slskd/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 0d879d0c..350f1354 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -590,7 +590,8 @@ namespace slskd new SoulseekClient(options: new SoulseekClientOptions( maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots, - minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum()))); + minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum(), + raiseEventsAsynchronously: true))); // add the core application service to DI as well as a hosted service so that other services can // access instance methods -- cgit v1.2.3 From 3c727be6ebd7afe146acaeb98f669c3cc5df4350 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Oct 2025 16:46:40 -0500 Subject: bump Soulseek.NET to 8.2.1 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 49e48552..ae042d68 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 e6133cdcdc561d541d3e2a56ecebd97604c46bcf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 5 Oct 2025 17:25:31 -0500 Subject: wait until downloads are enqueued before attempting to enqueue more --- src/slskd/Transfers/Downloads/DownloadService.cs | 101 ++++++++++++++++++++--- 1 file changed, 88 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 8969eeaf..db1a92ad 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -55,11 +55,12 @@ namespace slskd.Transfers.Downloads /// /// The username of 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. - Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default); /// /// Enqueues the specified from the specified . @@ -67,19 +68,23 @@ namespace slskd.Transfers.Downloads /// 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); + Task EnqueueAsync(string username, string filename, long size, Action stateChanged = null, CancellationToken cancellationToken = default); /// /// Downloads the specified enqueued from the remote user. /// /// The Transfer to download. + /// An optional delegate to invoke the transfer state changes. + /// The token to monitor for cancellation. /// The operation context. /// Thrown if the specified Transfer is null. /// Thrown if the specified Transfer ID can't be found in the database. /// Thrown if the specified Transfer is not in the Queued | Locally state. /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. - Task DownloadAsync(Transfer transfer); + Task DownloadAsync(Transfer transfer, Action stateChanged = null, CancellationToken cancellationToken = default); /// /// Finds a single download matching the specified . @@ -196,14 +201,16 @@ namespace slskd.Transfers.Downloads /// Downloads the specified enqueued from the remote user. /// /// The Transfer to download. + /// An optional delegate to invoke the transfer state changes. + /// The token to monitor for cancellation. /// The operation context. /// Thrown if the specified Transfer is null. /// Thrown if the specified Transfer ID can't be found in the database. /// Thrown if the specified Transfer is not in the Queued | Locally state. /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. - public async Task DownloadAsync(Transfer transfer) + public async Task DownloadAsync(Transfer transfer, Action stateChanged = null, CancellationToken cancellationToken = default) { - var cts = new CancellationTokenSource(); + var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var syncRoot = new SemaphoreSlim(1, 1); void SynchronizedUpdate(Transfer transfer, bool cancellable = true) @@ -286,13 +293,15 @@ namespace slskd.Transfers.Downloads // 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 (transfer.EnqueuedAt is null && args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) + if (args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) { - transfer.EnqueuedAt = DateTime.UtcNow; + transfer.EnqueuedAt ??= DateTime.UtcNow; } // todo: broadcast SynchronizedUpdate(transfer); + + stateChanged?.Invoke(transfer); }, progressUpdated: (args) => rateLimiter.Invoke(() => { @@ -470,8 +479,10 @@ namespace slskd.Transfers.Downloads /// 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. - public Task EnqueueAsync(string username, string filename, long size) + public Task EnqueueAsync(string username, string filename, long size, Action stateChanged = null, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -574,7 +585,7 @@ namespace slskd.Transfers.Downloads Task.Run can fail due to thread pool exhaustion or OOM, and this *SHOULD* throw up the chain and fail the enqueue request */ - _ = Task.Run(() => DownloadAsync(transfer)).ContinueWith(task => + _ = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken)).ContinueWith(task => { if (task.IsCompletedSuccessfully) { @@ -609,7 +620,7 @@ namespace slskd.Transfers.Downloads Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", id, ex.Message); throw; } - }); + }, cancellationToken); return Task.FromResult(transfer); } @@ -656,11 +667,12 @@ namespace slskd.Transfers.Downloads /// /// 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) + public async Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -675,11 +687,74 @@ namespace slskd.Transfers.Downloads List transfers = []; List exceptions = []; + /* + 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 + + 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 + + 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. + + 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; + } + try { - transfers.Add(await EnqueueAsync(username, file.Filename, file.Size)); + var enqueuedTcs = new TaskCompletionSource(); + List transitions = []; + + // 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")); + } + }); + + void stateChanged(Transfer 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 + 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)) + { + enqueuedTcs.TrySetResult(transfer); + } + } + + // 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; + + transfers.Add(transfer); } catch (Exception ex) { @@ -687,7 +762,7 @@ namespace slskd.Transfers.Downloads } } - if (exceptions.Any()) + if (exceptions.Count != 0) { throw new AggregateException(exceptions); } -- cgit v1.2.3 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(-) (limited to 'src') 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(-) (limited to 'src') 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(-) (limited to 'src') 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') 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(-) (limited to 'src') 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(-) (limited to 'src') 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(+) (limited to 'src') 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(+) (limited to 'src') 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(-) (limited to 'src') 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(-) (limited to 'src') 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 From e1a39de7d5e8127a2a3b52ecc5d09bb4961c40e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 Oct 2025 00:28:41 -0500 Subject: add transfer timeout setting --- config/slskd.example.yml | 1 + docs/config.md | 7 ++++++- src/slskd/Core/Options.cs | 9 +++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index ad3c6113..419c0c9f 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -207,6 +207,7 @@ # timeout: # connect: 10000 # inactivity: 15000 +# transfer: 30000 # buffer: # read: 16384 # write: 16384 diff --git a/docs/config.md b/docs/config.md index 10f296f5..5a4d3155 100644 --- a/docs/config.md +++ b/docs/config.md @@ -705,10 +705,14 @@ Higher connect timeout values will help ensure that operations (browse, download Inactivity timeouts help the application determine when a distributed parent connection has stopped sending data and when connections that have delivered search results (and are unlikely to be used further) from remaining open longer than needed. Reducing this timeout can help low spec systems if port exhaustion is a concern but may result in the application "hunting" for a distributed parent connection needlessly. +Transfer connections use their own timeout value; other Soulseek clients regulate transfer speed by controlling how often data is sent (e.g. send full speed for 5 seconds, send nothing for 25 seconds), +and as such transfers can easily time out due to inactivity if using a lower value. This setting must be at least 30 seconds. + | Command-Line | Environment Variable | Description | | --------------------------- | ------------------------------- | ------------------------------------------------ | | `--slsk-connection-timeout` | `SLSKD_SLSK_CONNECTION_TIMEOUT` | The connection timeout value, in milliseconds | | `--slsk-inactivity-timeout` | `SLSKD_SLSK_INACTIVITY_TIMEOUT` | The connection inactivity value, in milliseconds | +| `--slsk-transfer-timeout` | `SLSKD_SLSK_TRANSFER_TIMEOUT` | The transfer connection timeout value, in milliseconds | #### **YAML** ```yaml @@ -716,7 +720,8 @@ soulseek: connection: timeout: connect: 10000 - inactivity: 15000 + inactivity: 15000 + transfer: 30000 ``` ### Buffers diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 352d23e9..38416ca2 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1675,6 +1675,15 @@ namespace slskd [Description("connection inactivity timeout, in milliseconds")] [Range(1000, int.MaxValue)] public int Inactivity { get; init; } = 15000; + + /// + /// Gets the transfer connection timeout, in milliseconds. + /// + [Argument(default, "slsk-transfer-timeout")] + [EnvironmentVariable("SLSK_TRANSFER_TIMEOUT")] + [Description("transfer connection timeout, in milliseconds")] + [Range(30_000, int.MaxValue)] + public int Transfer { get; init; } = 60000; } /// -- cgit v1.2.3 From 165a480f02408d817f93482966aa586057b38d01 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 Oct 2025 00:28:54 -0500 Subject: bump Soulseek.NET to 8.4.0 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 7f5c1004..29d362ef 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 ef1038be546899752d37482d8ac2c239813c7315 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 Oct 2025 00:29:11 -0500 Subject: rename configureSocketAction to match the Soulseek.NET type --- src/slskd/Core/Extensions.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Extensions.cs b/src/slskd/Core/Extensions.cs index 65942180..db75cc9c 100644 --- a/src/slskd/Core/Extensions.cs +++ b/src/slskd/Core/Extensions.cs @@ -51,7 +51,7 @@ namespace slskd /// The connection timeout, in milliseconds, for client and peer TCP connections. /// The inactivity timeout, in milliseconds, for peer TCP connections. /// Optional SOCKS 5 proxy configuration options. - /// + /// /// The delegate invoked during instantiation to configure the server Socket instance. /// /// The new instance. @@ -63,14 +63,14 @@ namespace slskd int? connectTimeout = null, int? inactivityTimeout = null, ProxyOptions proxyOptions = null, - Action configureSocketAction = null) => new ConnectionOptions( + Action configureSocket = null) => new ConnectionOptions( readBufferSize: readBufferSize ?? o.ReadBufferSize, writeBufferSize: writeBufferSize ?? o.WriteBufferSize, writeQueueSize: writeQueueSize ?? o.WriteQueueSize, connectTimeout: connectTimeout ?? o.ConnectTimeout, inactivityTimeout: inactivityTimeout ?? o.InactivityTimeout, proxyOptions: proxyOptions ?? o.ProxyOptions, - configureSocket: configureSocketAction ?? o.ConfigureSocket); + configureSocket: configureSocket ?? o.ConfigureSocket); /// /// Creates a new instance of from this instance of . -- 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') 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 9bff52c48d333f8b8d7d5e227d28d65628b1c0a7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 Oct 2025 18:49:50 -0500 Subject: add sync update at class level --- src/slskd/Transfers/Downloads/DownloadService.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index a462f3de..9a64c386 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1014,5 +1014,19 @@ namespace slskd.Transfers.Downloads context.Update(transfer); context.SaveChanges(); } + + private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default) + { + semaphore.Wait(cancellationToken); + + try + { + Update(transfer); + } + finally + { + semaphore.Release(); + } + } } } \ No newline at end of file -- cgit v1.2.3 From dba88b05e9433f7726bacfd1f1fc48c394c7aadb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 Oct 2025 18:50:20 -0500 Subject: use sync update --- src/slskd/Transfers/Downloads/DownloadService.cs | 27 ++++++------------------ 1 file changed, 7 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9a64c386..3bc3d6af 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -201,21 +201,8 @@ namespace slskd.Transfers.Downloads public async Task DownloadAsync(Transfer transfer, Action stateChanged = null, CancellationToken cancellationToken = default) { var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - var syncRoot = new SemaphoreSlim(1, 1); - - void SynchronizedUpdate(Transfer transfer, bool cancellable = true) - { - syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); - - try - { - Update(transfer); - } - finally - { - syncRoot.Release(); - } - } + var updateSemaphore = new SemaphoreSlim(1, 1); + var progressSemaphore = new SemaphoreSlim(1, 1); var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; @@ -277,7 +264,7 @@ namespace slskd.Transfers.Downloads // 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); + Log.Debug("Download update of {Filename} from {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); return; } @@ -291,7 +278,7 @@ namespace slskd.Transfers.Downloads } // todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, semaphore: updateSemaphore, cancellationToken: cts.Token); } finally { @@ -365,7 +352,7 @@ namespace slskd.Transfers.Downloads transfer = transfer.WithSoulseekTransfer(completedTransfer); // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: updateSemaphore, cancellationToken: CancellationToken.None); // move the file from incomplete to complete var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); @@ -434,7 +421,7 @@ namespace slskd.Transfers.Downloads }; // todo: broadcast - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: updateSemaphore, cancellationToken: CancellationToken.None); throw; } @@ -447,7 +434,7 @@ namespace slskd.Transfers.Downloads transfer.State = TransferStates.Completed | TransferStates.Errored; // todo: broadcast - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: updateSemaphore, cancellationToken: CancellationToken.None); throw; } -- cgit v1.2.3 From 78a9e94a4bfd5e67e0751fe573ef948790020eae Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 11 Oct 2025 18:50:35 -0500 Subject: don't update progress if previous update still pending --- src/slskd/Transfers/Downloads/DownloadService.cs | 38 ++++++++++++++---------- 1 file changed, 23 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 3bc3d6af..6a60c836 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -292,28 +292,36 @@ namespace slskd.Transfers.Downloads // being made after the transfer is completed, causing them to appear 'stuck' if (transfer.State == TransferStates.InProgress) { - syncRoot.Wait(cts.Token); - - try + // don't wait for the semaphore; if a previous progress update is still hanging, don't make + // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems + // but the alternative is to continue to stack slow writes on top of one another + if (progressSemaphore.Wait(millisecondsTimeout: 0, cts.Token)) { - // check again to see if the state changed while we were waiting to obtain the lock - if (transfer.State == TransferStates.InProgress) + try { - // update only the properties that we expect to change between progress updates - // this helps prevent this update from 'stepping' on other updates - transfer.BytesTransferred = args.Transfer.BytesTransferred; - transfer.AverageSpeed = args.Transfer.AverageSpeed; + // check again to see if the state changed while we were waiting to obtain the lock + if (transfer.State == TransferStates.InProgress) + { + // update only the properties that we expect to change between progress updates + // this helps prevent this update from 'stepping' on other updates + transfer.BytesTransferred = args.Transfer.BytesTransferred; + transfer.AverageSpeed = args.Transfer.AverageSpeed; - using var context = ContextFactory.CreateDbContext(); + using var context = ContextFactory.CreateDbContext(); - context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter - .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + } + } + finally + { + progressSemaphore.Release(); } } - finally + else { - syncRoot.Release(); + Log.Debug("Skipped progress update of {Filename} from {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size); } } }), -- cgit v1.2.3 From 339641fb463420fa331fad3793885d7af83d27a9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 Oct 2025 13:18:07 -0500 Subject: add a concurrency limit to RateLimiter --- src/slskd/Common/RateLimiter.cs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/RateLimiter.cs b/src/slskd/Common/RateLimiter.cs index 8a7a63c6..b57c2f88 100644 --- a/src/slskd/Common/RateLimiter.cs +++ b/src/slskd/Common/RateLimiter.cs @@ -19,6 +19,7 @@ namespace slskd { using System; using System.ComponentModel; + using System.Threading; /// /// Ensures a minimum interval between successive invocations of a delegate. @@ -29,8 +30,11 @@ namespace slskd /// Initializes a new instance of the class. /// /// The minimum interval between invocations. + /// + /// Limit the number of concurrent executions of the specified action, in cases where the logic runs slower than the configured interval. Set this to null to remove the limit. + /// /// A value indicating whether pending action(s) should be executed during disposal. - public RateLimiter(int interval, bool flushOnDispose = false) + public RateLimiter(int interval, int? concurrencyLimit = 1, bool flushOnDispose = false) { Timer = new System.Timers.Timer(interval) { @@ -40,6 +44,11 @@ namespace slskd Timer.Elapsed += Timer_Elapsed; FlushOnDispose = flushOnDispose; + + if (concurrencyLimit.HasValue) + { + ConcurrentExecutionPreventionSemaphore = new SemaphoreSlim(concurrencyLimit.Value, concurrencyLimit.Value); + } } private bool Disposed { get; set; } @@ -47,6 +56,7 @@ namespace slskd private bool Init { get; set; } private Action Staged { get; set; } private System.Timers.Timer Timer { get; set; } + private SemaphoreSlim ConcurrentExecutionPreventionSemaphore { get; } = null; /// /// Releases all resources used by the . @@ -102,8 +112,18 @@ namespace slskd private void Timer_Elapsed(object sender, EventArgs args) { - Staged?.Invoke(); - Staged = null; + if (ConcurrentExecutionPreventionSemaphore?.Wait(0) ?? true) + { + try + { + Staged?.Invoke(); + Staged = null; + } + finally + { + ConcurrentExecutionPreventionSemaphore?.Release(); + } + } } } } \ No newline at end of file -- cgit v1.2.3 From 7cdba8bcfbaace65db333def290c7be928f76eed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 Oct 2025 13:18:34 -0500 Subject: switch back to shared syncRoot --- src/slskd/Transfers/Downloads/DownloadService.cs | 27 ++++++++++++------------ 1 file changed, 13 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 6a60c836..4c70bca5 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -201,8 +201,7 @@ namespace slskd.Transfers.Downloads public async Task DownloadAsync(Transfer transfer, Action stateChanged = null, CancellationToken cancellationToken = default) { var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - var updateSemaphore = new SemaphoreSlim(1, 1); - var progressSemaphore = new SemaphoreSlim(1, 1); + var syncRoot = new SemaphoreSlim(1, 1); var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; @@ -251,7 +250,7 @@ namespace slskd.Transfers.Downloads Log.Information("Initializing download of {Filename} from {Username}", transfer.Filename, transfer.Username); - using var rateLimiter = new RateLimiter(250, flushOnDispose: true); + using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); var topts = new TransferOptions( stateChanged: (args) => @@ -278,7 +277,7 @@ namespace slskd.Transfers.Downloads } // todo: broadcast - SynchronizedUpdate(transfer, semaphore: updateSemaphore, cancellationToken: cts.Token); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); } finally { @@ -295,18 +294,18 @@ namespace slskd.Transfers.Downloads // don't wait for the semaphore; if a previous progress update is still hanging, don't make // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems // but the alternative is to continue to stack slow writes on top of one another - if (progressSemaphore.Wait(millisecondsTimeout: 0, cts.Token)) + if (syncRoot.Wait(millisecondsTimeout: 0, cts.Token)) { try { + // update only the properties that we expect to change between progress updates + // this helps prevent this update from 'stepping' on other updates + transfer.BytesTransferred = args.Transfer.BytesTransferred; + transfer.AverageSpeed = args.Transfer.AverageSpeed; + // check again to see if the state changed while we were waiting to obtain the lock if (transfer.State == TransferStates.InProgress) { - // update only the properties that we expect to change between progress updates - // this helps prevent this update from 'stepping' on other updates - transfer.BytesTransferred = args.Transfer.BytesTransferred; - transfer.AverageSpeed = args.Transfer.AverageSpeed; - using var context = ContextFactory.CreateDbContext(); context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter @@ -316,7 +315,7 @@ namespace slskd.Transfers.Downloads } finally { - progressSemaphore.Release(); + syncRoot.Release(); } } else @@ -360,7 +359,7 @@ namespace slskd.Transfers.Downloads transfer = transfer.WithSoulseekTransfer(completedTransfer); // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, semaphore: updateSemaphore, cancellationToken: CancellationToken.None); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); // move the file from incomplete to complete var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); @@ -429,7 +428,7 @@ namespace slskd.Transfers.Downloads }; // todo: broadcast - SynchronizedUpdate(transfer, semaphore: updateSemaphore, cancellationToken: CancellationToken.None); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); throw; } @@ -442,7 +441,7 @@ namespace slskd.Transfers.Downloads transfer.State = TransferStates.Completed | TransferStates.Errored; // todo: broadcast - SynchronizedUpdate(transfer, semaphore: updateSemaphore, cancellationToken: CancellationToken.None); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); throw; } -- cgit v1.2.3 From 1fe11a21c69c90c83ec78da3095f1cc1b22523a5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 Oct 2025 13:18:57 -0500 Subject: bail out of progress update if semaphore can't be obtained immediately --- src/slskd/Transfers/Uploads/UploadService.cs | 45 ++++++++++++++++------------ 1 file changed, 26 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 89700eba..037438cf 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -220,7 +220,6 @@ namespace slskd.Transfers.Uploads /// Thrown if the specified file can't be found on disk. public async Task UploadAsync(Transfer transfer) { - var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); @@ -307,7 +306,7 @@ namespace slskd.Transfers.Uploads // can throw NotFoundException (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: transfer.Filename); - using var rateLimiter = new RateLimiter(250, flushOnDispose: true); + using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); var topts = new TransferOptions( stateChanged: (args) => @@ -334,28 +333,36 @@ namespace slskd.Transfers.Uploads // being made after the transfer is completed, causing them to appear 'stuck' if (transfer.State == TransferStates.InProgress) { - syncRoot.Wait(cts.Token); - - try + // don't wait for the semaphore; if a previous progress update is still hanging, don't make + // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems + // but the alternative is to continue to stack slow writes on top of one another + if (syncRoot.Wait(millisecondsTimeout: 0, cts.Token)) { - // update only the properties that we expect to change between progress updates - // this helps prevent this update from 'stepping' on other updates - transfer.BytesTransferred = args.Transfer.BytesTransferred; - transfer.AverageSpeed = args.Transfer.AverageSpeed; - - // check again to see if the state changed while we were waiting to obtain the lock - if (transfer.State == TransferStates.InProgress) + try { - using var context = ContextFactory.CreateDbContext(); - - context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter - .SetProperty(t => t.BytesTransferred, args.Transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, args.Transfer.AverageSpeed)); + // update only the properties that we expect to change between progress updates + // this helps prevent this update from 'stepping' on other updates + transfer.BytesTransferred = args.Transfer.BytesTransferred; + transfer.AverageSpeed = args.Transfer.AverageSpeed; + + // check again to see if the state changed while we were waiting to obtain the lock + if (transfer.State == TransferStates.InProgress) + { + using var context = ContextFactory.CreateDbContext(); + + context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter + .SetProperty(t => t.BytesTransferred, args.Transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, args.Transfer.AverageSpeed)); + } + } + finally + { + syncRoot.Release(); } } - finally + else { - syncRoot.Release(); + Log.Debug("Skipped progress update of {Filename} to {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size); } } }), -- cgit v1.2.3 From 0fe0125a8a33a25f4452437693eb1008244d8f55 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 Oct 2025 15:57:50 -0500 Subject: move SynchronizedUpdate --- src/slskd/Transfers/Uploads/UploadService.cs | 40 ++++++++++++++-------------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 037438cf..c4f123d4 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -223,20 +223,6 @@ namespace slskd.Transfers.Uploads var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); - void SynchronizedUpdate(Transfer transfer, bool cancellable = true) - { - syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); - - try - { - Update(transfer); - } - finally - { - syncRoot.Release(); - } - } - string host = default; string localFilename = default; long localFileLength = default; @@ -324,7 +310,7 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); }, progressUpdated: (args) => rateLimiter.Invoke(() => { @@ -379,7 +365,7 @@ namespace slskd.Transfers.Uploads // add the transfer to the UploadQueue so that it can become eligible for selection Queue.Enqueue(transfer.Username, transfer.Filename); transfer.EnqueuedAt = DateTime.UtcNow; - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); Soulseek.Transfer completedTransfer; @@ -424,7 +410,7 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(completedTransfer); // todo: broadcast - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); EventBus.Raise(new UploadFileCompleteEvent { @@ -442,7 +428,7 @@ namespace slskd.Transfers.Uploads transfer.Exception = "File could not be found"; transfer.State = TransferStates.Completed | TransferStates.Aborted; - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); throw; } @@ -460,7 +446,7 @@ namespace slskd.Transfers.Uploads }; // todo: broadcast - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); throw; } @@ -473,7 +459,7 @@ namespace slskd.Transfers.Uploads transfer.State = TransferStates.Completed | TransferStates.Errored; // todo: broadcast - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); throw; } @@ -1005,5 +991,19 @@ namespace slskd.Transfers.Uploads return (host, filename, length); } + + private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default) + { + semaphore.Wait(cancellationToken); + + try + { + Update(transfer); + } + finally + { + semaphore.Release(); + } + } } } \ No newline at end of file -- cgit v1.2.3 From 8466136a29e9986dc8812b57a0691dad1e08e09e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 Oct 2025 16:03:18 -0500 Subject: tweak for consistency with download --- src/slskd/Transfers/Uploads/UploadService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index c4f123d4..7cbc98d0 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -337,8 +337,8 @@ namespace slskd.Transfers.Uploads using var context = ContextFactory.CreateDbContext(); context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter - .SetProperty(t => t.BytesTransferred, args.Transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, args.Transfer.AverageSpeed)); + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); } } finally -- cgit v1.2.3 From 73d621141b9910645d4a1bc41b7bbbb05aedf1da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 12 Oct 2025 16:09:15 -0500 Subject: remove deprecated double-check of state --- src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++++-------- src/slskd/Transfers/Uploads/UploadService.cs | 14 +++++--------- 2 files changed, 9 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 4c70bca5..75a3c383 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -303,15 +303,11 @@ namespace slskd.Transfers.Downloads transfer.BytesTransferred = args.Transfer.BytesTransferred; transfer.AverageSpeed = args.Transfer.AverageSpeed; - // check again to see if the state changed while we were waiting to obtain the lock - if (transfer.State == TransferStates.InProgress) - { - using var context = ContextFactory.CreateDbContext(); + using var context = ContextFactory.CreateDbContext(); - context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter - .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); - } + context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); } finally { diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 7cbc98d0..4b35bffb 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -331,15 +331,11 @@ namespace slskd.Transfers.Uploads transfer.BytesTransferred = args.Transfer.BytesTransferred; transfer.AverageSpeed = args.Transfer.AverageSpeed; - // check again to see if the state changed while we were waiting to obtain the lock - if (transfer.State == TransferStates.InProgress) - { - using var context = ContextFactory.CreateDbContext(); - - context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter - .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); - } + using var context = ContextFactory.CreateDbContext(); + + context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); } finally { -- 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') 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 From 263af8626fb439e75c4341a7f3bcf36878b33b5b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 13 Oct 2025 21:36:48 -0500 Subject: check for duplicates --- src/slskd/Transfers/Downloads/DownloadService.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 75a3c383..b6f22944 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -480,6 +480,11 @@ namespace slskd.Transfers.Downloads throw new ArgumentException("At least one file is required", nameof(files)); } + if (files.Count() != files.Distinct().Count()) + { + throw new ArgumentException("Two or more files in request are duplicated", nameof(files)); + } + IPEndPoint endpoint; try -- cgit v1.2.3 From 75ad65dbed0333fd6bd0441a5599527c539366e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 13 Oct 2025 21:48:08 -0500 Subject: move database operations out of loop --- src/slskd/Transfers/Downloads/DownloadService.cs | 37 ++++++++++++------------ 1 file changed, 18 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index b6f22944..57a6ff37 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -499,11 +499,25 @@ namespace slskd.Transfers.Downloads } List acquiredLocks = []; + List enqueued = []; + List failed = []; try { - List enqueued = []; - List failed = []; + using var context = ContextFactory.CreateDbContext(); + + /* + 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) + .AsNoTracking() + .ToList(); + + var existingInProgressRecords = existingRecords + .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) + .ToList(); /* first, check inputs and do an _exhaustive_ check for all of the files provided, separating files out @@ -543,22 +557,6 @@ namespace slskd.Transfers.Downloads 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! @@ -588,7 +586,6 @@ namespace slskd.Transfers.Downloads 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); @@ -604,6 +601,8 @@ namespace slskd.Transfers.Downloads } } + var recordsCreated = context.SaveChanges(); + if (enqueued.Count == 0) { return (enqueued, failed); -- cgit v1.2.3 From 32b41f04184fd82c24761d8f0b336e830b7d6db2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 14 Oct 2025 18:30:55 -0500 Subject: set concurrent search limit to 2 (from the default 10) --- src/slskd/Program.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 350f1354..b7463575 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -591,6 +591,7 @@ namespace slskd maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots, minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum(), + maximumConcurrentSearches: 2, raiseEventsAsynchronously: true))); // add the core application service to DI as well as a hosted service so that other services can -- cgit v1.2.3 From a972672bb344899686d450254d34944a9caab805 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 16 Oct 2025 08:46:10 -0500 Subject: set unix file mode after moving downloaded files --- src/slskd/Files/FileService.cs | 19 ++++++++++++++++++- src/slskd/Transfers/Downloads/DownloadService.cs | 9 ++++++--- 2 files changed, 24 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index a07bd051..e4adc7e7 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -379,6 +379,7 @@ namespace slskd.Files /// /// The fully qualified filename of the file to move. /// The fully qualified directory to which to move the source file. + /// An optional Unix file mode to apply to the destination file. /// An optional value indicating whether the destination file should be overwritten if it already exists. /// /// An optional value indicating whether the parent directory of the source file should be deleted if it is empty after the move. @@ -387,7 +388,7 @@ namespace slskd.Files /// Thrown if either of the specified file or directories are null or contain only whitespace. /// Thrown if the specified does not exist. /// Thrown if the file can't be moved, or the option is set and the operation fails. - public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false) + public virtual string MoveFile(string sourceFilename, string destinationDirectory, UnixFileMode? unixFileMode = null, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false) { ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); @@ -425,6 +426,22 @@ namespace slskd.Files Log.Debug("Successfully moved {Source} to {Destination}", sourceFilename, destinationFilename); + // attempting to use UnixCreateMode on Windows raises an Exception + // we *MUST* check the OS and skip this on Windows + if (!OperatingSystem.IsWindows()) + { + var appOption = OptionsMonitor.CurrentValue.Permissions.File.Mode; + var mode = unixFileMode ?? appOption?.ToUnixFileMode(); + + // if options haven't been passed in and none have been set in app config, omit this + // so that the application's umask will be applied, saving users the hassle of setting it twice. + if (mode.HasValue) + { + File.SetUnixFileMode(destinationFilename, mode.Value); + Log.Debug("Successfully set Unix file mode to {Mode}", mode); + } + } + // if the parent directory is empty after the move, delete it if (deleteSourceDirectoryIfEmptyAfterMove && !Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) { diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 75a3c383..e66808a4 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -325,6 +325,10 @@ namespace slskd.Transfers.Downloads // register the cancellation token CancellationTokens.TryAdd(transfer.Id, cts); + System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() + : null; + var completedTransfer = await Client.DownloadAsync( username: transfer.Username, remoteFilename: transfer.Filename, @@ -336,9 +340,7 @@ namespace slskd.Transfers.Downloads Access = System.IO.FileAccess.Write, Mode = System.IO.FileMode.Create, // overwrites file if it exists Share = System.IO.FileShare.None, // exclusive access for the duration of the download - UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) - ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() - : null, + UnixCreateMode = unixFileMode, })), size: transfer.Size, startOffset: 0, @@ -363,6 +365,7 @@ namespace slskd.Transfers.Downloads var finalFilename = Files.MoveFile( sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), destinationDirectory: destinationDirectory, + unixFileMode: unixFileMode, overwrite: false, deleteSourceDirectoryIfEmptyAfterMove: true); -- cgit v1.2.3 From 0a511c76d86109d9e974929752b59b94899d700b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 17 Oct 2025 08:55:08 -0500 Subject: limit concurrent download enqueue requests to 1 --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index fdbca1dc..a45e4bd1 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -23,6 +23,7 @@ namespace slskd.Transfers.API using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; + using System.Threading; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -51,6 +52,7 @@ namespace slskd.Transfers.API OptionsSnapshot = optionsSnapshot; } + private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(1, 1); private ITransferService Transfers { get; } private IOptionsSnapshot OptionsSnapshot { get; } @@ -204,13 +206,18 @@ namespace slskd.Transfers.API [ProducesResponseType(201)] [ProducesResponseType(typeof(string), 403)] [ProducesResponseType(typeof(string), 500)] - public async Task EnqueueAsync([FromRoute, Required] string username, [FromBody] IEnumerable requests) + public async Task EnqueueAsync([FromRoute, Required] string username, [FromBody] IEnumerable requests, CancellationToken cancellationToken) { if (Program.IsRelayAgent) { return Forbid(); } + if (!DownloadRequestLimiter.Wait(0)) + { + return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); + } + try { await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size))); @@ -220,6 +227,10 @@ namespace slskd.Transfers.API { return StatusCode(500, ex.Message); } + finally + { + DownloadRequestLimiter.Release(); + } } /// -- cgit v1.2.3 From 8adea69d86bcbb1fe4ff3ab60e6a51d2b9155315 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 17 Oct 2025 08:58:32 -0500 Subject: limit concurrent search start requests to 1 --- .../Search/API/Controllers/SearchesController.cs | 50 ++++++++++++++-------- 1 file changed, 32 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index 1d00b482..c51d537e 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -20,6 +20,7 @@ using Microsoft.Extensions.Options; namespace slskd.Search.API { using System; + using System.Threading; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -49,6 +50,7 @@ namespace slskd.Search.API OptionsSnapshot = optionsSnapshot; } + private static SemaphoreSlim SearchRequestLimiter { get; } = new SemaphoreSlim(1, 1); private ISearchService Searches { get; } private IOptionsSnapshot OptionsSnapshot { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); @@ -75,29 +77,41 @@ namespace slskd.Search.API return BadRequest("SearchText may not be null or empty"); } - var id = request.Id ?? Guid.NewGuid(); - - Search search; - - try + if (!SearchRequestLimiter.Wait(0)) { - search = await Searches.StartAsync(id, SearchQuery.FromText(request.SearchText), SearchScope.Network, request.ToSearchOptions()); - return Ok(search); + return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); } - catch (Exception ex) when (ex is ArgumentException || ex is Soulseek.DuplicateTokenException) - { - Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); - return BadRequest(ex.Message); - } - catch (InvalidOperationException ex) + + try { - Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); - return Conflict(ex.Message); + var id = request.Id ?? Guid.NewGuid(); + + Search search; + + try + { + search = await Searches.StartAsync(id, SearchQuery.FromText(request.SearchText), SearchScope.Network, request.ToSearchOptions()); + return Ok(search); + } + catch (Exception ex) when (ex is ArgumentException || ex is Soulseek.DuplicateTokenException) + { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); + return BadRequest(ex.Message); + } + catch (InvalidOperationException ex) + { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); + return Conflict(ex.Message); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); + return StatusCode(500, ex.Message); + } } - catch (Exception ex) + finally { - Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); - return StatusCode(500, ex.Message); + SearchRequestLimiter.Release(); } } -- cgit v1.2.3 From 41e59c5aeea36def2832847e3aabd3023d2cc8f6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 17 Oct 2025 17:48:32 -0500 Subject: pass cancellation token --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 8 ++++++-- src/slskd/Transfers/Downloads/DownloadService.cs | 2 ++ 2 files changed, 8 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index a45e4bd1..0afb79ca 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -206,7 +206,11 @@ namespace slskd.Transfers.API [ProducesResponseType(201)] [ProducesResponseType(typeof(string), 403)] [ProducesResponseType(typeof(string), 500)] - public async Task EnqueueAsync([FromRoute, Required] string username, [FromBody] IEnumerable requests, CancellationToken cancellationToken) +#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) +#pragma warning disable SA1611 // Element parameters should be documented + public async Task EnqueueAsync([FromRoute, Required] string username, [FromBody] IEnumerable requests, CancellationToken cancellationToken = default) +#pragma warning restore SA1611 // Element parameters should be documented +#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) { if (Program.IsRelayAgent) { @@ -220,7 +224,7 @@ namespace slskd.Transfers.API try { - await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size))); + await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)), cancellationToken); return StatusCode(201); } catch (Exception ex) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index e66808a4..e2fa3e32 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -511,6 +511,8 @@ namespace slskd.Transfers.Downloads */ foreach (var file in files) { + cancellationToken.ThrowIfCancellationRequested(); + var transfer = new Transfer() { Id = Guid.NewGuid(), -- cgit v1.2.3 From 37f0e5598da904f7d59d7f258f9ee1f81068b489 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 Oct 2025 15:00:18 -0500 Subject: add additional logging, check status of fire-and-forget tasks --- src/slskd/Transfers/Downloads/DownloadService.cs | 219 ++++++++++++++--------- 1 file changed, 130 insertions(+), 89 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index e2fa3e32..e1d9c053 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -606,12 +606,16 @@ namespace slskd.Transfers.Downloads if (enqueued.Count == 0) { + Log.Warning("None of the {Count} requested files from {Username} could be enqueued as they are already in progress", files.Count(), username); return (enqueued, failed); } + Log.Debug("Attempting to enqueue {Count} files from {Username}", enqueued.Count, username); + // 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 { + Log.Debug("Priming message connection to {Username}", enqueued.Count, username); await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken); } catch (Exception ex) @@ -625,7 +629,9 @@ namespace slskd.Transfers.Downloads we'll proceed with downloading them, but in a separate task run in the background */ - _ = Task.Run(async () => + Log.Debug("Scheduling batch enqueue Task for {Count} files from {Username}", enqueued.Count, username); + + var batchEnqueueTask = Task.Run(async () => { /* enqueue each of the specified files, waiting to ensure that the remote client has responded to our @@ -647,125 +653,92 @@ namespace slskd.Transfers.Downloads var semaphore = new SemaphoreSlim(initialCount: concurrentRequests, maxCount: concurrentRequests); + Log.Debug("Scheduling Tasks to download {Count} files from {Username}", enqueued.Count, username); + var tasks = enqueued.Select(async transfer => { + Log.Debug("Awaiting download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); await semaphore.WaitAsync(); try { Log.Debug("Acquired download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); - try - { - var enqueuedTcs = new TaskCompletionSource(); - List transitions = []; + var enqueuedTcs = new TaskCompletionSource(); + List transitions = []; - // 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(() => + // 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) { - 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")); - } - }); + 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")); + } + }); - void stateChanged(Transfer transfer) + void stateChanged(Transfer 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)) { - transitions.Add(transfer.State.ToString()); + enqueuedTcs.TrySetResult(transfer); + } - // _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)) + // 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); } - - // 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)) + else { - if (transfer.State.HasFlag(TransferStates.Succeeded)) - { - enqueuedTcs.TrySetResult(transfer); - } - else - { - enqueuedTcs.TrySetException(new TransferException(transfer.Exception)); - } + enqueuedTcs.TrySetException(new TransferException(transfer.Exception)); } } + } - // 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 => - { - if (task.IsCompletedSuccessfully) - { - Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); - return; - } - - /* - 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}", transfer.Filename, transfer.Username, task.Exception.Message); - - try - { - var foundTransfer = Find(t => t.Id == transfer.Id); + Log.Debug("Scheduling Task for download of {Filename} from {Username}", transfer.Filename, transfer.Username); - if (transfer is not null) - { - transfer.EndedAt ??= DateTime.UtcNow; - transfer.Exception ??= task.Exception.InnerException.Message; + // 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 + var downloadTask = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken)).ContinueWith(task => + { + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); + return; + } - 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); + /* + things that can cause us to arrive here: - // 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); + * 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); try { - var transferRecord = Find(t => t.Id == transfer.Id); + var foundTransfer = Find(t => t.Id == transfer.Id); if (transfer is not null) { transfer.EndedAt ??= DateTime.UtcNow; - transfer.Exception ??= ex.Message; + transfer.Exception ??= task.Exception.InnerException.Message; if (!transfer.State.HasFlag(TransferStates.Completed)) { - transfer.State = TransferStates.Completed | ex switch + transfer.State = TransferStates.Completed | task.Exception.InnerException switch { OperationCanceledException => TransferStates.Cancelled, TimeoutException => TransferStates.TimedOut, @@ -776,11 +749,60 @@ namespace slskd.Transfers.Downloads Update(transfer); } } - catch (Exception innerEx) + catch (Exception ex) + { + Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message); + } + }, cancellationToken); + + if (downloadTask.Status == TaskStatus.Canceled) + { + throw new OperationCanceledException($"The download Task for {transfer.Filename} from {transfer.Username} was cancelled"); + } + + if (downloadTask.Status == TaskStatus.Faulted) + { + throw new Exception($"The download Task for {transfer.Filename} from {transfer.Username} faulted: {downloadTask.Exception}", downloadTask.Exception); + } + + Log.Debug("Download Task status: {Status}", downloadTask.Status); + + Log.Debug("Waiting for download of {Filename} from {Username} to transition into {State}", transfer.Filename, transfer.Username, TransferStates.Queued | TransferStates.Remotely); + + // 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 transferRecord = Find(t => t.Id == transfer.Id); + + if (transfer is not null) { - Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); + 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); + } } finally { @@ -789,6 +811,7 @@ namespace slskd.Transfers.Downloads } }); + Log.Debug("Waiting for all {Count} download Tasks for {Username} to complete", enqueued.Count, username); await Task.WhenAll(tasks); }, cancellationToken).ContinueWith(task => { @@ -801,8 +824,26 @@ 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); + if (batchEnqueueTask.Status == TaskStatus.Canceled) + { + throw new OperationCanceledException($"The batch enqueue Task for {enqueued.Count} files from {username} was cancelled"); + } + + if (batchEnqueueTask.Status == TaskStatus.Faulted) + { + throw new Exception($"The batch enqueue Task for {enqueued.Count} files from {username} faulted: {batchEnqueueTask.Exception}", batchEnqueueTask.Exception); + } + + Log.Debug("Batch enqueue Task status: {Status}", batchEnqueueTask.Status); + Log.Information("Successfully enqueued {Count} files from {Username}", enqueued.Count, username); + return (enqueued, failed); } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue one or more of {Count} files from {Username}: {Message}", files.Count(), username, ex.Message); + throw; + } finally { foreach (var lockName in acquiredLocks) -- cgit v1.2.3 From 0019807a920c7ac55a1c7e63e87157b490b95076 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 Oct 2025 16:21:27 -0500 Subject: more logging tweaks --- src/slskd/Transfers/Downloads/DownloadService.cs | 48 ++++++++++++++++++++---- 1 file changed, 40 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index e1d9c053..f4e48e60 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -200,6 +200,16 @@ namespace slskd.Transfers.Downloads /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. public async Task DownloadAsync(Transfer transfer, Action stateChanged = null, CancellationToken cancellationToken = default) { + if (transfer is null) + { + throw new ArgumentNullException(nameof(transfer), "A valid, enqueued Transfer is required"); + } + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var syncRoot = new SemaphoreSlim(1, 1); @@ -207,8 +217,8 @@ namespace slskd.Transfers.Downloads if (!Locks.TryAdd(lockName, true)) { - Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); - return null; + Log.Debug("Download attempt failed; lock {LockName} already held", lockName); + throw new DuplicateTransferException("A duplicate download of the same file to the same user is already in progress"); } /* @@ -248,8 +258,6 @@ namespace slskd.Transfers.Downloads throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); } - Log.Information("Initializing download of {Filename} from {Username}", transfer.Filename, transfer.Username); - using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); var topts = new TransferOptions( @@ -329,6 +337,8 @@ namespace slskd.Transfers.Downloads ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null; + Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); + var completedTransfer = await Client.DownloadAsync( username: transfer.Username, remoteFilename: transfer.Filename, @@ -348,6 +358,8 @@ namespace slskd.Transfers.Downloads cancellationToken: cts.Token, options: topts); + Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); + // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we // flushe any pending update, _probably_ pushing the state of the transfer back to InProgress rateLimiter.Dispose(); @@ -359,6 +371,8 @@ namespace slskd.Transfers.Downloads // todo: broadcast to signalr hub SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); + // move the file from incomplete to complete var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); @@ -369,7 +383,9 @@ namespace slskd.Transfers.Downloads overwrite: false, deleteSourceDirectoryIfEmptyAfterMove: true); - Log.Debug("Moved file to {Destination}", finalFilename); + Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); + + Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username); // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, // and the file has been moved from the incomplete directory to the downloads directory @@ -411,10 +427,15 @@ namespace slskd.Transfers.Downloads _ = FTP.UploadAsync(finalFilename); } + Log.Debug("Completed post-download logic for {Filename} from {Username} successfully", transfer.Filename, transfer.Username); + Log.Information("Download of {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); + return transfer; } catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) { + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); + transfer.EndedAt = DateTime.UtcNow; transfer.Exception = ex.Message; transfer.State = TransferStates.Completed; @@ -446,17 +467,20 @@ namespace slskd.Transfers.Downloads } finally { + Log.Debug("Finalizing download of {Filename} from {Username}", transfer.Filename, transfer.Username); + try { Locks.TryRemove(lockName, out _); Log.Debug("Released lock {LockName}", lockName); CancellationTokens.TryRemove(transfer.Id, out _); + + Log.Debug("Finalization of download of {Filename} from {Username} completed", transfer.Filename, transfer.Username); } catch (Exception ex) { Log.Error(ex, "Failed to finalize download of {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); - throw; } } } @@ -817,11 +841,11 @@ namespace slskd.Transfers.Downloads { if (task.IsCompletedSuccessfully) { - Log.Warning("Task for enqueue of {Count} files from {Username} completed successfully", files.Count(), username); + Log.Warning("Task for batch enqueue of {Count} files from {Username} completed successfully", files.Count(), username); return; } - Log.Error(task.Exception, "Task for enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); + Log.Error(task.Exception, "Task for batch enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); }, cancellationToken: CancellationToken.None); if (batchEnqueueTask.Status == TaskStatus.Canceled) @@ -846,13 +870,21 @@ namespace slskd.Transfers.Downloads } finally { + Log.Debug("Finalizing enqueue of one or more files from {Username}", username); + foreach (var lockName in acquiredLocks) { if (Locks.TryRemove(lockName, out _)) { Log.Debug("Released lock {LockName}", lockName); } + else + { + Log.Error("Failed to release lock for {LockName}", lockName); + } } + + Log.Debug("Finalization of enqueue of one or more files from {Username} completed", username); } } -- cgit v1.2.3 From 6580c6ec514fa708d42ffa06e8996a3738e3ad28 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 Oct 2025 16:25:35 -0500 Subject: add logger, log exceptions when enqueueing --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 0afb79ca..f38c4b87 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -28,6 +28,7 @@ namespace slskd.Transfers.API using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Serilog; /// /// Transfers. @@ -55,6 +56,7 @@ namespace slskd.Transfers.API private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(1, 1); private ITransferService Transfers { get; } private IOptionsSnapshot OptionsSnapshot { get; } + private ILogger Log { get; set; } = Serilog.Log.ForContext(); /// /// Cancels the specified download. @@ -229,6 +231,7 @@ namespace slskd.Transfers.API } catch (Exception ex) { + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message); return StatusCode(500, ex.Message); } finally -- cgit v1.2.3 From 5498bda398a568cdeef8d39e0d6197f671fd1a5f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 Oct 2025 17:02:39 -0500 Subject: tweaks --- src/slskd/Transfers/Downloads/DownloadService.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index f4e48e60..2fb34ca0 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -509,6 +509,8 @@ namespace slskd.Transfers.Downloads IPEndPoint endpoint; + Log.Information("Requested enqueue of {Count} files from user {Username}", files.Count(), username); + try { // get the user's ip and port. this will throw if they are offline. @@ -565,7 +567,7 @@ namespace slskd.Transfers.Downloads acquiredLocks.Add(lockName); Log.Debug("Acquired lock {LockName}", lockName); - Log.Information("Download of {Filename} from {Username} requested", file.Filename, username); + Log.Debug("Checking whether download of {Filename} from {Username} is already in progress", file.Filename, username); using var context = ContextFactory.CreateDbContext(); @@ -604,6 +606,7 @@ namespace slskd.Transfers.Downloads add it to the database and remove any existing (past) records of it from the UI */ context.Add(transfer); + Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id); foreach (var record in existingRecords.Where(t => !t.Removed)) { @@ -634,7 +637,7 @@ namespace slskd.Transfers.Downloads return (enqueued, failed); } - Log.Debug("Attempting to enqueue {Count} files from {Username}", enqueued.Count, username); + Log.Debug("Attempting to remotely enqueue {Count} files from {Username}", enqueued.Count, username); // 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 -- cgit v1.2.3 From 270ba2ec1f6d6afa34c326d7a76d98c701a285db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 Oct 2025 17:33:07 -0500 Subject: fix use of wrong transfer object in cleanup --- src/slskd/Transfers/Downloads/DownloadService.cs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 2fb34ca0..2ad73f74 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -758,14 +758,14 @@ namespace slskd.Transfers.Downloads { var foundTransfer = Find(t => t.Id == transfer.Id); - if (transfer is not null) + if (foundTransfer is not null) { - transfer.EndedAt ??= DateTime.UtcNow; - transfer.Exception ??= task.Exception.InnerException.Message; + foundTransfer.EndedAt ??= DateTime.UtcNow; + foundTransfer.Exception ??= task.Exception.InnerException.Message; - if (!transfer.State.HasFlag(TransferStates.Completed)) + if (!foundTransfer.State.HasFlag(TransferStates.Completed)) { - transfer.State = TransferStates.Completed | task.Exception.InnerException switch + foundTransfer.State = TransferStates.Completed | task.Exception.InnerException switch { OperationCanceledException => TransferStates.Cancelled, TimeoutException => TransferStates.TimedOut, @@ -773,7 +773,7 @@ namespace slskd.Transfers.Downloads }; } - Update(transfer); + Update(foundTransfer); } } catch (Exception ex) @@ -806,16 +806,16 @@ namespace slskd.Transfers.Downloads try { - var transferRecord = Find(t => t.Id == transfer.Id); + var foundTransfer = Find(t => t.Id == transfer.Id); - if (transfer is not null) + if (foundTransfer is not null) { - transfer.EndedAt ??= DateTime.UtcNow; - transfer.Exception ??= ex.Message; + foundTransfer.EndedAt ??= DateTime.UtcNow; + foundTransfer.Exception ??= ex.Message; - if (!transfer.State.HasFlag(TransferStates.Completed)) + if (!foundTransfer.State.HasFlag(TransferStates.Completed)) { - transfer.State = TransferStates.Completed | ex switch + foundTransfer.State = TransferStates.Completed | ex switch { OperationCanceledException => TransferStates.Cancelled, TimeoutException => TransferStates.TimedOut, -- cgit v1.2.3 From 9793dcd8313a02c071b6553bd608221ba0ec41c6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 Oct 2025 17:33:36 -0500 Subject: try/catch and swallow errors thrown while running post processing --- src/slskd/Transfers/Downloads/DownloadService.cs | 78 +++++++++++++----------- 1 file changed, 44 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 2ad73f74..efa5d644 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -385,49 +385,59 @@ namespace slskd.Transfers.Downloads Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); - Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username); - - // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, - // and the file has been moved from the incomplete directory to the downloads directory - if (OptionsMonitor.CurrentValue.Relay.Enabled) + try { - _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); - } + Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username); - EventBus.Raise(new DownloadFileCompleteEvent - { - Timestamp = transfer.EndedAt.Value, - LocalFilename = finalFilename, - RemoteFilename = transfer.Filename, - Transfer = transfer, - }); - - // try to figure out if this file is the last of a directory, and if so, raise the associated - // event. this can be tricky because we want to be sure that this is the last file in this specific - // directory, excluding any pending downloads in a subdirectory. - var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); - var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); - var pendingDownloadsInDirectory = Client.Downloads - .Where(t => t.Username == transfer.Username) - .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); - - if (!pendingDownloadsInDirectory.Any()) - { - EventBus.Raise(new DownloadDirectoryCompleteEvent + // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, + // and the file has been moved from the incomplete directory to the downloads directory + if (OptionsMonitor.CurrentValue.Relay.Enabled) + { + _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); + } + + EventBus.Raise(new DownloadFileCompleteEvent { Timestamp = transfer.EndedAt.Value, - Username = transfer.Username, - LocalDirectoryName = destinationDirectory, - RemoteDirectoryName = remoteDirectoryName, + LocalFilename = finalFilename, + RemoteFilename = transfer.Filename, + Transfer = transfer, }); - } - if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) + // try to figure out if this file is the last of a directory, and if so, raise the associated + // event. this can be tricky because we want to be sure that this is the last file in this specific + // directory, excluding any pending downloads in a subdirectory. + var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); + var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); + var pendingDownloadsInDirectory = Client.Downloads + .Where(t => t.Username == transfer.Username) + .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); + + if (!pendingDownloadsInDirectory.Any()) + { + EventBus.Raise(new DownloadDirectoryCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + Username = transfer.Username, + LocalDirectoryName = destinationDirectory, + RemoteDirectoryName = remoteDirectoryName, + }); + } + + if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) + { + _ = FTP.UploadAsync(finalFilename); + } + + Log.Debug("Completed post-download logic for {Filename} from {Username} successfully", transfer.Filename, transfer.Username); + } + catch (Exception ex) { - _ = FTP.UploadAsync(finalFilename); + // log, but don't throw. the file ended up in the download folder and is complete; if we throw it looks like it didn't complete + // todo: add a visual indicator/new state for Transfers that indicate this state. or move all of this logic out and handle it via events + Log.Error(ex, "Failed to run post-download processes for {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); } - Log.Debug("Completed post-download logic for {Filename} from {Username} successfully", transfer.Filename, transfer.Username); Log.Information("Download of {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); return transfer; -- cgit v1.2.3 From b4f57596898948606d014dda6f7531d0567a5b63 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 Oct 2025 17:34:20 -0500 Subject: don't swallow relay errors --- src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index efa5d644..9beb8077 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -385,16 +385,16 @@ namespace slskd.Transfers.Downloads Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); - try + if (OptionsMonitor.CurrentValue.Relay.Enabled) { - Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username); + _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); + } + try + { // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, // and the file has been moved from the incomplete directory to the downloads directory - if (OptionsMonitor.CurrentValue.Relay.Enabled) - { - _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); - } + Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username); EventBus.Raise(new DownloadFileCompleteEvent { -- cgit v1.2.3 From 5899521238415c6f5fc8b3fb37ceab2cbd82b328 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 Oct 2025 18:01:55 -0500 Subject: tweax --- src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9beb8077..f4e10565 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -628,7 +628,7 @@ namespace slskd.Transfers.Downloads context.SaveChanges(); enqueued.Add(transfer); - Log.Information("Successfully enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transfer.Id); + Log.Information("Successfully locally enqueued download of {Filename} from {Username}", file.Filename, username, transfer.Id); } catch (Exception ex) { @@ -652,7 +652,7 @@ namespace slskd.Transfers.Downloads // 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 { - Log.Debug("Priming message connection to {Username}", enqueued.Count, username); + Log.Debug("Priming message connection to {Username}", username); await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken); } catch (Exception ex) @@ -666,7 +666,7 @@ namespace slskd.Transfers.Downloads we'll proceed with downloading them, but in a separate task run in the background */ - Log.Debug("Scheduling batch enqueue Task for {Count} files from {Username}", enqueued.Count, username); + Log.Debug("Scheduling batch remote enqueue Task for {Count} files from {Username}", enqueued.Count, username); var batchEnqueueTask = Task.Run(async () => { @@ -703,6 +703,7 @@ namespace slskd.Transfers.Downloads var enqueuedTcs = new TaskCompletionSource(); List transitions = []; + TransferStates state = TransferStates.None; // 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 @@ -718,6 +719,7 @@ namespace slskd.Transfers.Downloads void stateChanged(Transfer transfer) { + state = transfer.State; transitions.Add(transfer.State.ToString()); // _contractually_ (covered by unit tests!) all downloads will at some point enter the Queued | Remotely state @@ -809,6 +811,8 @@ namespace slskd.Transfers.Downloads // 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; + + Log.Debug("Download of {Filename} from {Username} successfully entered state {State}", state); } catch (Exception ex) { @@ -854,7 +858,7 @@ namespace slskd.Transfers.Downloads { if (task.IsCompletedSuccessfully) { - Log.Warning("Task for batch enqueue of {Count} files from {Username} completed successfully", files.Count(), username); + Log.Information("Task for batch enqueue of {Count} files from {Username} completed successfully", files.Count(), username); return; } -- cgit v1.2.3 From e2daded033140b49025428a42f5281b509c42b2e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 Oct 2025 18:22:42 -0500 Subject: param mismatch --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index f4e10565..a84a494d 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -812,7 +812,7 @@ namespace slskd.Transfers.Downloads // timeout to trip and set an exception await enqueuedTcs.Task; - Log.Debug("Download of {Filename} from {Username} successfully entered state {State}", state); + Log.Debug("Download of {Filename} from {Username} successfully entered state {State}", transfer.Filename, transfer.Username, state); } catch (Exception ex) { -- cgit v1.2.3 From a260cf9637adf8969d15582802dbd94f074f36d2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 18 Oct 2025 18:23:06 -0500 Subject: add unhandled exception logging --- src/slskd/Program.cs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b7463575..264089da 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1134,6 +1134,27 @@ namespace slskd } })) .CreateLogger(); + + // occurs when a faulted task's unobserved exception is about to trigger exception escalation policy, which, by default, would terminate the process. + TaskScheduler.UnobservedTaskException += (sender, e) => + { + Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message); + e.SetObserved(); + }; + + AppDomain.CurrentDomain.UnhandledException += (sender, e) => + { + var exception = e.ExceptionObject as Exception; + + if (e.IsTerminating) + { + Serilog.Log.Logger.Fatal(exception, "Unhandled fatal exception: {Message}", e.IsTerminating); + } + else + { + Serilog.Log.Logger.Error(exception, "Unhandled exception: {Message}", exception.Message); + } + }; } private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile, bool reloadOnChange) -- cgit v1.2.3 From 899ecdbdf74ce4bff122d026be84de16631a7bbc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 19 Oct 2025 12:08:19 -0500 Subject: fix bug with thread pool statistics --- src/slskd/Program.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b7463575..6de76b0d 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -236,6 +236,7 @@ namespace slskd private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); private static ILogger Log { get; set; } = new ConsoleWriteLineLogger(); private static Mutex Mutex { get; } = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName)); + private static IDisposable DotNetRuntimeStats { get; set; } [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -704,8 +705,10 @@ namespace slskd .AllowCredentials() .WithExposedHeaders("X-URL-Base", "X-Total-Count"))); - services.AddSystemMetrics(); - using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); + // note: don't dispose this (or let it be disposed) or some of the stats, like those related + // to the thread pool won't work + DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Default().StartCollecting(); + services.AddSystemMetrics(registerDefaultCollectors: true); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); -- cgit v1.2.3 From af1137276286a1521a165bf371a3a5ec1e532789 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 19 Oct 2025 12:11:19 -0500 Subject: nevermind --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6de76b0d..059a7ca1 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -708,7 +708,7 @@ namespace slskd // note: don't dispose this (or let it be disposed) or some of the stats, like those related // to the thread pool won't work DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Default().StartCollecting(); - services.AddSystemMetrics(registerDefaultCollectors: true); + services.AddSystemMetrics(); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); -- cgit v1.2.3 From 3ad70da8345653dd004cc1ae588ac05753da9005 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 19 Oct 2025 12:28:06 -0500 Subject: prime connection before enqueueing locally --- src/slskd/Transfers/Downloads/DownloadService.cs | 26 +++++++++++------------- 1 file changed, 12 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index a84a494d..a46130c9 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -532,6 +532,18 @@ namespace slskd.Transfers.Downloads throw; } + // 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 + { + Log.Debug("Priming message connection to {Username}", username); + await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message); + throw; + } + List acquiredLocks = []; try @@ -647,20 +659,6 @@ namespace slskd.Transfers.Downloads return (enqueued, failed); } - Log.Debug("Attempting to remotely enqueue {Count} files from {Username}", enqueued.Count, username); - - // 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 - { - Log.Debug("Priming message connection to {Username}", username); - 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. -- cgit v1.2.3 From f48395f036cb63499a7d3a0dbaa2b5873d4a1f32 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 19 Oct 2025 19:10:41 -0500 Subject: temporarily disable unobserved exceptions --- src/slskd/Program.cs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index bc426146..bf0428d7 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -23,6 +23,8 @@ namespace slskd using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; + using System.Diagnostics; + using System.IO; using System.Linq; using System.Net; @@ -1138,12 +1140,12 @@ namespace slskd })) .CreateLogger(); - // occurs when a faulted task's unobserved exception is about to trigger exception escalation policy, which, by default, would terminate the process. - TaskScheduler.UnobservedTaskException += (sender, e) => - { - Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message); - e.SetObserved(); - }; + // // occurs when a faulted task's unobserved exception is about to trigger exception escalation policy, which, by default, would terminate the process. + // TaskScheduler.UnobservedTaskException += (sender, e) => + // { + // Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message); + // e.SetObserved(); + // }; AppDomain.CurrentDomain.UnhandledException += (sender, e) => { -- cgit v1.2.3 From e00dffb4ce2856ec9bf3559770b8d558d9643718 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Oct 2025 07:56:51 -0500 Subject: remove locking fron DownloadAsync --- src/slskd/Transfers/Downloads/DownloadService.cs | 26 +----------------------- 1 file changed, 1 insertion(+), 25 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 015ec384..d617befe 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -213,14 +213,6 @@ namespace slskd.Transfers.Downloads var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var syncRoot = new SemaphoreSlim(1, 1); - var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; - - if (!Locks.TryAdd(lockName, true)) - { - Log.Debug("Download attempt failed; lock {LockName} already held", lockName); - throw new DuplicateTransferException("A duplicate download of the same file to the same user is already in progress"); - } - /* from this point forward, any exit from this method MUST result in an update to the Transfer record in the database that sets EndedAt and ensures that the State property includes the Completed flag @@ -231,8 +223,6 @@ namespace slskd.Transfers.Downloads */ try { - Log.Debug("Acquired lock {LockName}", lockName); - /* fetch an updated copy of the transfer record from the database; now that we are locked, we *should* have exclusive access to this record @@ -477,21 +467,7 @@ namespace slskd.Transfers.Downloads } finally { - Log.Debug("Finalizing download of {Filename} from {Username}", transfer.Filename, transfer.Username); - - try - { - Locks.TryRemove(lockName, out _); - Log.Debug("Released lock {LockName}", lockName); - - CancellationTokens.TryRemove(transfer.Id, out _); - - Log.Debug("Finalization of download of {Filename} from {Username} completed", transfer.Filename, transfer.Username); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to finalize download of {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); - } + CancellationTokens.TryRemove(transfer.Id, out _); } } -- cgit v1.2.3 From bdacfba1a18b081758e695160b69919c5a236947 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Oct 2025 07:29:18 -0500 Subject: make downloadasync private, schedule execution of cleanup method --- src/slskd/Transfers/Downloads/DownloadService.cs | 1255 +++++++++++----------- 1 file changed, 627 insertions(+), 628 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index d617befe..cdff2394 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -63,19 +63,6 @@ namespace slskd.Transfers.Downloads /// Thrown when at least one of the requested files throws. 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. - /// - /// The Transfer to download. - /// An optional delegate to invoke the transfer state changes. - /// The token to monitor for cancellation. - /// The operation context. - /// Thrown if the specified Transfer is null. - /// Thrown if the specified Transfer ID can't be found in the database. - /// Thrown if the specified Transfer is not in the Queued | Locally state. - /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. - Task DownloadAsync(Transfer transfer, Action stateChanged = null, CancellationToken cancellationToken = default); - /// /// Finds a single download matching the specified . /// @@ -148,6 +135,8 @@ namespace slskd.Transfers.Downloads FTP = ftpClient; Relay = relayService; EventBus = eventBus; + + Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); } private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); @@ -188,469 +177,185 @@ namespace slskd.Transfers.Downloads } /// - /// Downloads the specified enqueued from the remote user. + /// Enqueues the requested list of . /// - /// The Transfer to download. - /// An optional delegate to invoke the transfer state changes. + /// The username of the remote user. + /// The list of files to enqueue. /// The token to monitor for cancellation. /// The operation context. - /// Thrown if the specified Transfer is null. - /// Thrown if the specified Transfer ID can't be found in the database. - /// Thrown if the specified Transfer is not in the Queued | Locally state. - /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. - public async Task DownloadAsync(Transfer transfer, 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 (transfer is null) + if (string.IsNullOrEmpty(username)) { - throw new ArgumentNullException(nameof(transfer), "A valid, enqueued Transfer is required"); + throw new ArgumentException("Username is required", nameof(username)); } - if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + if (!files.Any()) { - throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + throw new ArgumentException("At least one file is required", nameof(files)); } - var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - var syncRoot = new SemaphoreSlim(1, 1); + if (files.Count() != files.Distinct().Count()) + { + throw new ArgumentException("Two or more files in request are duplicated", nameof(files)); + } - /* - from this point forward, any exit from this method MUST result in an update to the Transfer record - in the database that sets EndedAt and ensures that the State property includes the Completed flag + IPEndPoint endpoint; - failure to do so means records will get "stuck" in the database/on the UI + Log.Information("Requested enqueue of {Count} files from user {Username}", files.Count(), username); - additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot - */ try { - /* - fetch an updated copy of the transfer record from the database; now that we are locked, we *should* - have exclusive access to this record + // 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; + } - we're not using DbContext and tracked changes here because we don't want to hold a connection - open for the duration of the download + // 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 + { + Log.Debug("Priming message connection to {Username}", username); + await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message); + throw; + } + + List acquiredLocks = []; + List enqueued = []; + List failed = []; + + try + { + using var context = ContextFactory.CreateDbContext(); + + /* + get all past downloads from this user for this filename */ - transfer = Find(t => t.Id == transfer.Id) - ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + var existingRecords = context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => t.Username == username) + .AsNoTracking() + .ToList(); - if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) - { - throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); - } + var existingInProgressRecords = existingRecords + .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) + .ToList(); /* - Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; - check that list to see if there's already an instance of this download in it, just in case we've gotten - out of sync somehow + first, check inputs and do an _exhaustive_ check for all of the files provided, separating files out + into good/bad + + acquire locks for each, and track them so we can release them later (in the finally block) */ - if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) + foreach (var file in files) { - throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); - } + cancellationToken.ThrowIfCancellationRequested(); - using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); + var transfer = new Transfer() + { + 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 topts = new TransferOptions( - stateChanged: (args) => + var lockName = $"{nameof(EnqueueAsync)}:{username}:{file.Filename}"; + + if (!Locks.TryAdd(lockName, true)) { - try - { - Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", transfer.Filename, transfer.Username, args.PreviousState, args.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; + } - // 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} from {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); - return; - } + try + { + acquiredLocks.Add(lockName); + Log.Debug("Acquired lock {LockName}", lockName); - transfer = transfer.WithSoulseekTransfer(args.Transfer); + Log.Debug("Checking whether download of {Filename} from {Username} is already in progress", file.Filename, username); - // 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; - } + /* + 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! - // todo: broadcast - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); + 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)) + { + 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; } - finally + + /* + 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); + Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id); + + foreach (var record in existingRecords.Where(t => !t.Removed)) { - stateChanged?.Invoke(transfer); + record.Removed = true; + context.Update(record); + Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", file.Filename, username, record.Id); } - }, - progressUpdated: (args) => rateLimiter.Invoke(() => + + enqueued.Add(transfer); + + Log.Information("Successfully locally enqueued download of {Filename} from {Username}", file.Filename, username, transfer.Id); + } + catch (Exception ex) { - // don't do anything unless the `transfer` within the outer scope is in the - // InProgress state; this will help prevent out-of-band updates that are sometimes - // being made after the transfer is completed, causing them to appear 'stuck' - if (transfer.State == TransferStates.InProgress) - { - // don't wait for the semaphore; if a previous progress update is still hanging, don't make - // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems - // but the alternative is to continue to stack slow writes on top of one another - if (syncRoot.Wait(millisecondsTimeout: 0, cts.Token)) - { - try - { - // update only the properties that we expect to change between progress updates - // this helps prevent this update from 'stepping' on other updates - transfer.BytesTransferred = args.Transfer.BytesTransferred; - transfer.AverageSpeed = args.Transfer.AverageSpeed; + // 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; + } + } - using var context = ContextFactory.CreateDbContext(); + var recordsCreated = context.SaveChanges(); - context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter - .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); - } - finally - { - syncRoot.Release(); - } - } - else - { - Log.Debug("Skipped progress update of {Filename} from {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size); - } - } - }), - disposeOutputStreamOnCompletion: true); + if (enqueued.Count == 0) + { + Log.Warning("None of the {Count} requested files from {Username} could be enqueued as they are already in progress", files.Count(), username); + return (enqueued, failed); + } - // register the cancellation token - CancellationTokens.TryAdd(transfer.Id, cts); + /* + the files are all now in the database in the Queued | Locally state. - System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) - ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() - : null; + we'll proceed with downloading them, but in a separate task run in the background + */ + Log.Debug("Scheduling batch remote enqueue Task for {Count} files from {Username}", enqueued.Count, username); - Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); - - var completedTransfer = await Client.DownloadAsync( - username: transfer.Username, - remoteFilename: transfer.Filename, - outputStreamFactory: () => Task.FromResult( - Files.CreateFile( - filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - options: new CreateFileOptions - { - Access = System.IO.FileAccess.Write, - Mode = System.IO.FileMode.Create, // overwrites file if it exists - Share = System.IO.FileShare.None, // exclusive access for the duration of the download - UnixCreateMode = unixFileMode, - })), - size: transfer.Size, - startOffset: 0, - token: null, - cancellationToken: cts.Token, - options: topts); - - Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); - - // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we - // flushe any pending update, _probably_ pushing the state of the transfer back to InProgress - rateLimiter.Dispose(); - - // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state - // over the top of the transfer record, then persist it - transfer = transfer.WithSoulseekTransfer(completedTransfer); - - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - - Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); - - // move the file from incomplete to complete - var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); - - var finalFilename = Files.MoveFile( - sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - destinationDirectory: destinationDirectory, - unixFileMode: unixFileMode, - overwrite: false, - deleteSourceDirectoryIfEmptyAfterMove: true); - - Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); - - if (OptionsMonitor.CurrentValue.Relay.Enabled) - { - _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); - } - - try - { - // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, - // and the file has been moved from the incomplete directory to the downloads directory - Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username); - - EventBus.Raise(new DownloadFileCompleteEvent - { - Timestamp = transfer.EndedAt.Value, - LocalFilename = finalFilename, - RemoteFilename = transfer.Filename, - Transfer = transfer, - }); - - // try to figure out if this file is the last of a directory, and if so, raise the associated - // event. this can be tricky because we want to be sure that this is the last file in this specific - // directory, excluding any pending downloads in a subdirectory. - var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); - var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); - var pendingDownloadsInDirectory = Client.Downloads - .Where(t => t.Username == transfer.Username) - .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); - - if (!pendingDownloadsInDirectory.Any()) - { - EventBus.Raise(new DownloadDirectoryCompleteEvent - { - Timestamp = transfer.EndedAt.Value, - Username = transfer.Username, - LocalDirectoryName = destinationDirectory, - RemoteDirectoryName = remoteDirectoryName, - }); - } - - if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) - { - _ = FTP.UploadAsync(finalFilename); - } - - Log.Debug("Completed post-download logic for {Filename} from {Username} successfully", transfer.Filename, transfer.Username); - } - catch (Exception ex) - { - // log, but don't throw. the file ended up in the download folder and is complete; if we throw it looks like it didn't complete - // todo: add a visual indicator/new state for Transfers that indicate this state. or move all of this logic out and handle it via events - Log.Error(ex, "Failed to run post-download processes for {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); - } - - Log.Information("Download of {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); - - return transfer; - } - catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) - { - Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed; - - transfer.State |= ex switch - { - OperationCanceledException => TransferStates.Cancelled, - TimeoutException => TransferStates.TimedOut, - _ => TransferStates.Errored, - }; - - // todo: broadcast - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - - throw; - } - catch (Exception ex) - { - Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Errored; - - // todo: broadcast - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - - throw; - } - finally - { - CancellationTokens.TryRemove(transfer.Id, out _); - } - } - - /// - /// Enqueues the requested list of . - /// - /// 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<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) - { - if (string.IsNullOrEmpty(username)) - { - throw new ArgumentException("Username is required", nameof(username)); - } - - if (!files.Any()) - { - throw new ArgumentException("At least one file is required", nameof(files)); - } - - if (files.Count() != files.Distinct().Count()) - { - throw new ArgumentException("Two or more files in request are duplicated", nameof(files)); - } - - IPEndPoint endpoint; - - Log.Information("Requested enqueue of {Count} files from user {Username}", files.Count(), username); - - 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; - } - - // 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 - { - Log.Debug("Priming message connection to {Username}", username); - await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message); - throw; - } - - List acquiredLocks = []; - List enqueued = []; - List failed = []; - - try - { - using var context = ContextFactory.CreateDbContext(); - - /* - 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) - .AsNoTracking() - .ToList(); - - var existingInProgressRecords = existingRecords - .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) - .ToList(); - - /* - first, check inputs and do an _exhaustive_ check for all of the files provided, separating files out - into good/bad - - acquire locks for each, and track them so we can release them later (in the finally block) - */ - foreach (var file in files) - { - cancellationToken.ThrowIfCancellationRequested(); - - var transfer = new Transfer() - { - 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; - } - - try - { - acquiredLocks.Add(lockName); - Log.Debug("Acquired lock {LockName}", lockName); - - Log.Debug("Checking whether download of {Filename} from {Username} is already in progress", file.Filename, username); - - /* - 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)) - { - 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; - } - - /* - 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); - Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id); - - 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); - } - - enqueued.Add(transfer); - - Log.Information("Successfully locally enqueued download of {Filename} from {Username}", file.Filename, username, transfer.Id); - } - catch (Exception ex) - { - // 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; - } - } - - var recordsCreated = context.SaveChanges(); - - if (enqueued.Count == 0) - { - Log.Warning("None of the {Count} requested files from {Username} could be enqueued as they are already in progress", files.Count(), username); - return (enqueued, failed); - } - - /* - the files are all now in the database in the Queued | Locally state. - - we'll proceed with downloading them, but in a separate task run in the background - */ - Log.Debug("Scheduling batch remote enqueue Task for {Count} files from {Username}", enqueued.Count, username); - - var batchEnqueueTask = Task.Run(async () => - { - /* - 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 + var batchEnqueueTask = Task.Run(async () => + { + /* + 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 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 @@ -815,267 +520,538 @@ namespace slskd.Transfers.Downloads }; } - Update(transfer); - } - } - catch (Exception innerEx) - { - Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); - } - } - finally - { - semaphore.Release(); - Log.Debug("Released download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); - } - }); + Update(transfer); + } + } + catch (Exception innerEx) + { + Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); + } + } + finally + { + semaphore.Release(); + Log.Debug("Released download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); + } + }); + + Log.Debug("Waiting for all {Count} download Tasks for {Username} to complete", enqueued.Count, username); + await Task.WhenAll(tasks); + }, cancellationToken).ContinueWith(task => + { + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for batch enqueue of {Count} files from {Username} completed successfully", files.Count(), username); + return; + } + + Log.Error(task.Exception, "Task for batch enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); + }, cancellationToken: CancellationToken.None); + + if (batchEnqueueTask.Status == TaskStatus.Canceled) + { + throw new OperationCanceledException($"The batch enqueue Task for {enqueued.Count} files from {username} was cancelled"); + } + + if (batchEnqueueTask.Status == TaskStatus.Faulted) + { + throw new Exception($"The batch enqueue Task for {enqueued.Count} files from {username} faulted: {batchEnqueueTask.Exception}", batchEnqueueTask.Exception); + } + + Log.Debug("Batch enqueue Task status: {Status}", batchEnqueueTask.Status); + Log.Information("Successfully enqueued {Count} files from {Username}", enqueued.Count, username); + + return (enqueued, failed); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue one or more of {Count} files from {Username}: {Message}", files.Count(), username, ex.Message); + throw; + } + finally + { + semaphore.Release(); + Log.Debug("Released enqueue semaphore for user {Username}", username); + } + } + + /// + /// Finds a single download matching the specified . + /// + /// The expression to use to match downloads. + /// The found transfer, or default if not found. + public Transfer Find(Expression> expression) + { + try + { + using var context = ContextFactory.CreateDbContext(); + + return context.Transfers + .AsNoTracking() + .Where(t => t.Direction == TransferDirection.Download) + .Where(expression).FirstOrDefault(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to find download: {Message}", ex.Message); + throw; + } + } + + /// + /// Retrieves the place in the remote queue for the download matching the specified . + /// + /// The unique identifier for the download. + /// The retrieved place in queue. + public async Task GetPlaceInQueueAsync(Guid id) + { + try + { + using var context = ContextFactory.CreateDbContext(); + + var transfer = context.Transfers.Find(id); + + if (transfer == default) + { + throw new NotFoundException($"No download matching id ${id}"); + } + + var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); + + transfer.PlaceInQueue = place; + context.SaveChanges(); + + return place; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to get place in queue for download {Id}: {Message}", id, ex.Message); + throw; + } + } + + /// + /// Returns a list of all downloads matching the optional . + /// + /// An optional expression used to match downloads. + /// Optionally include downloads that have been removed previously. + /// The list of downloads matching the specified expression, or all downloads if no expression is specified. + public List List(Expression> expression = null, bool includeRemoved = false) + { + expression ??= t => true; + + try + { + using var context = ContextFactory.CreateDbContext(); + + return context.Transfers + .AsNoTracking() + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => !t.Removed || includeRemoved) + .Where(expression) + .ToList(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list downloads: {Message}", ex.Message); + throw; + } + } + + /// + /// Removes downloads older than the specified . + /// + /// The age after which downloads are eligible for pruning, in hours. + /// An optional, additional state by which downloads are filtered for pruning. + /// The number of pruned downloads. + public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) + { + if (!stateHasFlag.HasFlag(TransferStates.Completed)) + { + throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); + } + + try + { + using var context = ContextFactory.CreateDbContext(); - Log.Debug("Waiting for all {Count} download Tasks for {Username} to complete", enqueued.Count, username); - await Task.WhenAll(tasks); - }, cancellationToken).ContinueWith(task => - { - if (task.IsCompletedSuccessfully) - { - Log.Information("Task for batch enqueue of {Count} files from {Username} completed successfully", files.Count(), username); - return; - } + var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age); - Log.Error(task.Exception, "Task for batch enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); - }, cancellationToken: CancellationToken.None); + var expired = context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => !t.Removed) + .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) + .Where(t => t.State == stateHasFlag) + .ToList(); - if (batchEnqueueTask.Status == TaskStatus.Canceled) + foreach (var tx in expired) { - throw new OperationCanceledException($"The batch enqueue Task for {enqueued.Count} files from {username} was cancelled"); + tx.Removed = true; } - if (batchEnqueueTask.Status == TaskStatus.Faulted) + var pruned = context.SaveChanges(); + + if (pruned > 0) { - throw new Exception($"The batch enqueue Task for {enqueued.Count} files from {username} faulted: {batchEnqueueTask.Exception}", batchEnqueueTask.Exception); + Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, stateHasFlag); } - Log.Debug("Batch enqueue Task status: {Status}", batchEnqueueTask.Status); - Log.Information("Successfully enqueued {Count} files from {Username}", enqueued.Count, username); - - return (enqueued, failed); + return pruned; } catch (Exception ex) { - Log.Error(ex, "Failed to enqueue one or more of {Count} files from {Username}: {Message}", files.Count(), username, ex.Message); + Log.Error(ex, "Failed to prune downloads: {Message}", ex.Message); throw; } - finally - { - Log.Debug("Finalizing enqueue of one or more files from {Username}", username); - - foreach (var lockName in acquiredLocks) - { - if (Locks.TryRemove(lockName, out _)) - { - Log.Debug("Released lock {LockName}", lockName); - } - else - { - Log.Error("Failed to release lock for {LockName}", lockName); - } - } - - Log.Debug("Finalization of enqueue of one or more files from {Username} completed", username); - } } /// - /// Finds a single download matching the specified . + /// Removes the download matching the specified . /// - /// The expression to use to match downloads. - /// The found transfer, or default if not found. - public Transfer Find(Expression> expression) + /// This is a soft delete; the record is retained for historical retrieval. + /// The unique identifier of the download. + public void Remove(Guid id) { try { using var context = ContextFactory.CreateDbContext(); - return context.Transfers - .AsNoTracking() + var transfer = context.Transfers .Where(t => t.Direction == TransferDirection.Download) - .Where(expression).FirstOrDefault(); + .Where(t => t.Id == id) + .FirstOrDefault(); + + if (transfer == default) + { + throw new NotFoundException($"No download matching id ${id}"); + } + + if (!transfer.State.HasFlag(TransferStates.Completed)) + { + throw new InvalidOperationException($"Invalid attempt to remove a download before it is complete"); + } + + transfer.Removed = true; + + context.SaveChanges(); } catch (Exception ex) { - Log.Error(ex, "Failed to find download: {Message}", ex.Message); + Log.Error(ex, "Failed to remove download {Id}: {Message}", id, ex.Message); throw; } } /// - /// Retrieves the place in the remote queue for the download matching the specified . + /// Cancels the download matching the specified , if it is in progress. /// /// The unique identifier for the download. - /// The retrieved place in queue. - public async Task GetPlaceInQueueAsync(Guid id) + /// A value indicating whether the download was successfully cancelled. + public bool TryCancel(Guid id) + { + if (CancellationTokens.TryRemove(id, out var cts)) + { + cts.Cancel(); + return true; + } + + return false; + } + + /// + /// Synchronously updates the specified . + /// + /// The transfer to update. + public void Update(Transfer transfer) + { + using var context = ContextFactory.CreateDbContext(); + + context.Update(transfer); + context.SaveChanges(); + } + + /// + /// Downloads the specified enqueued from the remote user. + /// + /// The Transfer to download. + /// An optional delegate to invoke the transfer state changes. + /// The token to monitor for cancellation. + /// The operation context. + /// Thrown if the specified Transfer is null. + /// Thrown if the specified Transfer ID can't be found in the database. + /// Thrown if the specified Transfer is not in the Queued | Locally state. + /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. + private async Task DownloadAsync(Transfer transfer, Action stateChanged = null, CancellationToken cancellationToken = default) { + if (transfer is null) + { + throw new ArgumentNullException(nameof(transfer), "A valid, enqueued Transfer is required"); + } + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + + var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var syncRoot = new SemaphoreSlim(1, 1); + + /* + from this point forward, any exit from this method MUST result in an update to the Transfer record + in the database that sets EndedAt and ensures that the State property includes the Completed flag + + failure to do so means records will get "stuck" in the database/on the UI + + additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot + */ try { - using var context = ContextFactory.CreateDbContext(); + /* + fetch an updated copy of the transfer record from the database; now that we are locked, we *should* + have exclusive access to this record + + we're not using DbContext and tracked changes here because we don't want to hold a connection + open for the duration of the download + */ + transfer = Find(t => t.Id == transfer.Id) + ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + + /* + Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; + check that list to see if there's already an instance of this download in it, just in case we've gotten + out of sync somehow + */ + if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) + { + throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); + } + + using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); + + var topts = new TransferOptions( + stateChanged: (args) => + { + try + { + 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) + { + Log.Debug("Download update of {Filename} from {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); + return; + } + + transfer = transfer.WithSoulseekTransfer(args.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; + } + + // todo: broadcast + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); + } + finally + { + stateChanged?.Invoke(transfer); + } + }, + progressUpdated: (args) => rateLimiter.Invoke(() => + { + // don't do anything unless the `transfer` within the outer scope is in the + // InProgress state; this will help prevent out-of-band updates that are sometimes + // being made after the transfer is completed, causing them to appear 'stuck' + if (transfer.State == TransferStates.InProgress) + { + // don't wait for the semaphore; if a previous progress update is still hanging, don't make + // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems + // but the alternative is to continue to stack slow writes on top of one another + if (syncRoot.Wait(millisecondsTimeout: 0, cts.Token)) + { + try + { + // update only the properties that we expect to change between progress updates + // this helps prevent this update from 'stepping' on other updates + transfer.BytesTransferred = args.Transfer.BytesTransferred; + transfer.AverageSpeed = args.Transfer.AverageSpeed; + + using var context = ContextFactory.CreateDbContext(); + + context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + } + finally + { + syncRoot.Release(); + } + } + else + { + Log.Debug("Skipped progress update of {Filename} from {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size); + } + } + }), + disposeOutputStreamOnCompletion: true); - var transfer = context.Transfers.Find(id); + // register the cancellation token + CancellationTokens.TryAdd(transfer.Id, cts); - if (transfer == default) - { - throw new NotFoundException($"No download matching id ${id}"); - } + System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() + : null; - var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); + Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); - transfer.PlaceInQueue = place; - context.SaveChanges(); + var completedTransfer = await Client.DownloadAsync( + username: transfer.Username, + remoteFilename: transfer.Filename, + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + options: new CreateFileOptions + { + Access = System.IO.FileAccess.Write, + Mode = System.IO.FileMode.Create, // overwrites file if it exists + Share = System.IO.FileShare.None, // exclusive access for the duration of the download + UnixCreateMode = unixFileMode, + })), + size: transfer.Size, + startOffset: 0, + token: null, + cancellationToken: cts.Token, + options: topts); - return place; - } - catch (Exception ex) - { - Log.Error(ex, "Failed to get place in queue for download {Id}: {Message}", id, ex.Message); - throw; - } - } + Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); - /// - /// Returns a list of all downloads matching the optional . - /// - /// An optional expression used to match downloads. - /// Optionally include downloads that have been removed previously. - /// The list of downloads matching the specified expression, or all downloads if no expression is specified. - public List List(Expression> expression = null, bool includeRemoved = false) - { - expression ??= t => true; + // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we + // flushe any pending update, _probably_ pushing the state of the transfer back to InProgress + rateLimiter.Dispose(); - try - { - using var context = ContextFactory.CreateDbContext(); + // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state + // over the top of the transfer record, then persist it + transfer = transfer.WithSoulseekTransfer(completedTransfer); - return context.Transfers - .AsNoTracking() - .Where(t => t.Direction == TransferDirection.Download) - .Where(t => !t.Removed || includeRemoved) - .Where(expression) - .ToList(); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to list downloads: {Message}", ex.Message); - throw; - } - } + // todo: broadcast to signalr hub + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - /// - /// Removes downloads older than the specified . - /// - /// The age after which downloads are eligible for pruning, in hours. - /// An optional, additional state by which downloads are filtered for pruning. - /// The number of pruned downloads. - public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) - { - if (!stateHasFlag.HasFlag(TransferStates.Completed)) - { - throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); - } + Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); - try - { - using var context = ContextFactory.CreateDbContext(); + // move the file from incomplete to complete + var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); - var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age); + var finalFilename = Files.MoveFile( + sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + destinationDirectory: destinationDirectory, + unixFileMode: unixFileMode, + overwrite: false, + deleteSourceDirectoryIfEmptyAfterMove: true); - var expired = context.Transfers - .Where(t => t.Direction == TransferDirection.Download) - .Where(t => !t.Removed) - .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - .Where(t => t.State == stateHasFlag) - .ToList(); + Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); - foreach (var tx in expired) + if (OptionsMonitor.CurrentValue.Relay.Enabled) { - tx.Removed = true; + _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); } - var pruned = context.SaveChanges(); - - if (pruned > 0) + try { - Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, stateHasFlag); - } + // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, + // and the file has been moved from the incomplete directory to the downloads directory + Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username); - return pruned; - } - catch (Exception ex) - { - Log.Error(ex, "Failed to prune downloads: {Message}", ex.Message); - throw; - } - } + EventBus.Raise(new DownloadFileCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + LocalFilename = finalFilename, + RemoteFilename = transfer.Filename, + Transfer = transfer, + }); - /// - /// Removes the download matching the specified . - /// - /// This is a soft delete; the record is retained for historical retrieval. - /// The unique identifier of the download. - public void Remove(Guid id) - { - try - { - using var context = ContextFactory.CreateDbContext(); + // try to figure out if this file is the last of a directory, and if so, raise the associated + // event. this can be tricky because we want to be sure that this is the last file in this specific + // directory, excluding any pending downloads in a subdirectory. + var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); + var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); + var pendingDownloadsInDirectory = Client.Downloads + .Where(t => t.Username == transfer.Username) + .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); - var transfer = context.Transfers - .Where(t => t.Direction == TransferDirection.Download) - .Where(t => t.Id == id) - .FirstOrDefault(); + if (!pendingDownloadsInDirectory.Any()) + { + EventBus.Raise(new DownloadDirectoryCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + Username = transfer.Username, + LocalDirectoryName = destinationDirectory, + RemoteDirectoryName = remoteDirectoryName, + }); + } - if (transfer == default) - { - throw new NotFoundException($"No download matching id ${id}"); - } + if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) + { + _ = FTP.UploadAsync(finalFilename); + } - if (!transfer.State.HasFlag(TransferStates.Completed)) + Log.Debug("Completed post-download logic for {Filename} from {Username} successfully", transfer.Filename, transfer.Username); + } + catch (Exception ex) { - throw new InvalidOperationException($"Invalid attempt to remove a download before it is complete"); + // log, but don't throw. the file ended up in the download folder and is complete; if we throw it looks like it didn't complete + // todo: add a visual indicator/new state for Transfers that indicate this state. or move all of this logic out and handle it via events + Log.Error(ex, "Failed to run post-download processes for {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); } - transfer.Removed = true; + Log.Information("Download of {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); - context.SaveChanges(); + return transfer; } - catch (Exception ex) + catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) { - Log.Error(ex, "Failed to remove download {Id}: {Message}", id, ex.Message); + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); + + transfer.EndedAt = DateTime.UtcNow; + transfer.Exception = ex.Message; + transfer.State = TransferStates.Completed; + + transfer.State |= ex switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; + + // todo: broadcast + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + throw; } - } - - /// - /// Cancels the download matching the specified , if it is in progress. - /// - /// The unique identifier for the download. - /// A value indicating whether the download was successfully cancelled. - public bool TryCancel(Guid id) - { - if (CancellationTokens.TryRemove(id, out var cts)) + catch (Exception ex) { - cts.Cancel(); - return true; - } + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - return false; - } + transfer.EndedAt = DateTime.UtcNow; + transfer.Exception = ex.Message; + transfer.State = TransferStates.Completed | TransferStates.Errored; - /// - /// Synchronously updates the specified . - /// - /// The transfer to update. - public void Update(Transfer transfer) - { - using var context = ContextFactory.CreateDbContext(); + // todo: broadcast + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - context.Update(transfer); - context.SaveChanges(); + throw; + } + finally + { + CancellationTokens.TryRemove(transfer.Id, out _); + } } private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default) @@ -1091,5 +1067,28 @@ namespace slskd.Transfers.Downloads semaphore.Release(); } } + + private async Task CleanupEnqueueSemaphoresAsync() + { + if (await EnqueueSemaphoreSyncRoot.WaitAsync(0).ConfigureAwait(false)) + { + try + { + foreach (var kvp in EnqueueSemaphores) + { + if (await kvp.Value.WaitAsync(0).ConfigureAwait(false)) + { + EnqueueSemaphores.TryRemove(kvp.Key, out var removed); + removed.Dispose(); + Log.Debug($"Cleaned up enqueue semaphore for {kvp.Key}"); + } + } + } + finally + { + EnqueueSemaphoreSyncRoot.Release(); + } + } + } } } \ No newline at end of file -- cgit v1.2.3 From bbe6cdb052be982d33828e5ffa7fe499959789b2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Oct 2025 07:29:45 -0500 Subject: add semaphores --- src/slskd/Transfers/Downloads/DownloadService.cs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index cdff2394..e480c70b 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -148,7 +148,19 @@ namespace slskd.Transfers.Downloads private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private EventBus EventBus { get; } - private ConcurrentDictionary Locks { get; } = new(); + + /// + /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they + /// don't already exist, and a timer asynchronously cleans the dictionary up. + /// + private ConcurrentDictionary EnqueueSemaphores { get; } = []; + + /// + /// Synchronizes the cleanup process; after gaining exclusive access over the dictionary, checks each entry + /// to see if the containing semaphore can be obtained immediately. If so, it's not in use and is therefore + /// removed from the dictionary and discarded. + /// + private SemaphoreSlim EnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(initialCount: 1, maxCount: 1); /// /// Adds the specified . Supersedes any existing record for the same file and username. -- cgit v1.2.3 From 5fc58130fd760bcf36bfd5a8fc20974e5856da7b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Oct 2025 07:30:11 -0500 Subject: wait for semaphore before enqueue --- src/slskd/Transfers/Downloads/DownloadService.cs | 110 +++++++++++++---------- 1 file changed, 62 insertions(+), 48 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index e480c70b..2ff65f46 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -61,7 +61,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<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default); + Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default); /// /// Finds a single download matching the specified . @@ -198,7 +198,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 async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -219,9 +219,9 @@ namespace slskd.Transfers.Downloads Log.Information("Requested enqueue of {Count} files from user {Username}", files.Count(), username); + // get the user's ip and port. this will throw if they are offline. try { - // get the user's ip and port. this will throw if they are offline. endpoint = await Client.GetUserEndPointAsync(username, cancellationToken); } catch (Exception ex) @@ -244,14 +244,42 @@ namespace slskd.Transfers.Downloads List acquiredLocks = []; List enqueued = []; - List failed = []; + List failed = []; + SemaphoreSlim semaphore; + Task semaphoreWaitTask; + + // briefly obtain exclusive access over the semaphore dictionary to either get or create a record for this user + // this contends with the cleanup process, which will discard records if the associated semaphore can be acquired + // upon release of the semaphore, this logic will run and will potentially add a record right back + await EnqueueSemaphoreSyncRoot.WaitAsync(cancellationToken); try { + // fetch or create a semaphore record for this user, and set up a task (but don't await it yet! to avoid cleanup contention) + semaphore = EnqueueSemaphores.GetOrAdd(username, (username) => new SemaphoreSlim(initialCount: 1, maxCount: 1)); + semaphoreWaitTask = semaphore.WaitAsync(cancellationToken); + } + finally + { + EnqueueSemaphoreSyncRoot.Release(); + } + + // wait until we can get exclusive access to this user. it's important that we do so, so we can optimize database + // access within the critical section. this allows us to fetch the transfers for this user only once, and we don't + // have to worry about the database changing while we're in the critical section + Log.Debug("Awaiting enqueue semaphore for user {Username}", username); + await semaphoreWaitTask; + + try + { + Log.Debug("Acquired enqueue semaphore for user {Username}", username); + using var context = ContextFactory.CreateDbContext(); /* - get all past downloads from this user for this filename + get all past downloads from this user. this list will remain stable throughout this process because + we have exclusive access for this user. we'll be adding new records, but we've already deduplicated + them so we don't have to worry about duplicate records being created in the critical section */ var existingRecords = context.Transfers .Where(t => t.Direction == TransferDirection.Download) @@ -264,43 +292,17 @@ namespace slskd.Transfers.Downloads .ToList(); /* - first, check inputs and do an _exhaustive_ check for all of the files provided, separating files out - into good/bad + iterate over the files, and either: - acquire locks for each, and track them so we can release them later (in the finally block) + 1. if there's no active download for the file already, insert a record and kick off the download task + 2. if there's an active download already, stick the file in the failed array */ foreach (var file in files) { cancellationToken.ThrowIfCancellationRequested(); - var transfer = new Transfer() - { - 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; - } - try { - acquiredLocks.Add(lockName); - Log.Debug("Acquired lock {LockName}", lockName); - Log.Debug("Checking whether download of {Filename} from {Username} is already in progress", file.Filename, username); /* @@ -310,20 +312,29 @@ namespace slskd.Transfers.Downloads 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)) + var existingInProgressRecord = existingInProgressRecords.FirstOrDefault(t => t.Filename == file.Filename); + + if (existingInProgressRecord is not null || Client.Downloads.Any(u => u.Username == username && u.Filename == file.Filename)) { - 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); + Log.Debug("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} already in progress (id: {Id})", file.Filename, username, existingInProgressRecord.Id); + failed.Add(file.Filename); continue; } - /* - 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 - */ + var transfer = new Transfer() + { + 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, + }; + context.Add(transfer); + Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id); foreach (var record in existingRecords.Where(t => !t.Removed)) @@ -339,16 +350,19 @@ namespace slskd.Transfers.Downloads } catch (Exception ex) { - // 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); + failed.Add(file.Filename); continue; } } - var recordsCreated = context.SaveChanges(); + /* + persist our database changes, including: + + * INSERTs for all of the newly enqueued files + * UPDATEs for any files that are complete but still being shown on the UI + */ + context.SaveChanges(); if (enqueued.Count == 0) { -- cgit v1.2.3 From 9abd8625f47fc9005807ea4e4d0b3cdcee13f42a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Oct 2025 19:32:56 -0500 Subject: finish refactor of downloadasync --- src/slskd/Transfers/Downloads/DownloadService.cs | 55 ++++++++---------------- 1 file changed, 19 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 2ff65f46..b7cacb84 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -814,13 +814,19 @@ namespace slskd.Transfers.Downloads throw new ArgumentNullException(nameof(transfer), "A valid, enqueued Transfer is required"); } + // grab the latest from the database; this may have been sitting behind a semaphore or something + transfer = Find(t => t.Id == transfer.Id) + ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) { throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); } - var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - var syncRoot = new SemaphoreSlim(1, 1); + if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) + { + throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); + } /* from this point forward, any exit from this method MUST result in an update to the Transfer record @@ -830,35 +836,15 @@ namespace slskd.Transfers.Downloads additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot */ + var updateSyncRoot = new SemaphoreSlim(1, 1); + try { - /* - fetch an updated copy of the transfer record from the database; now that we are locked, we *should* - have exclusive access to this record - - we're not using DbContext and tracked changes here because we don't want to hold a connection - open for the duration of the download - */ - transfer = Find(t => t.Id == transfer.Id) - ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); - - if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) - { - throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); - } - - /* - Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; - check that list to see if there's already an instance of this download in it, just in case we've gotten - out of sync somehow - */ - if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) - { - throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); - } - using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + CancellationTokens.TryAdd(transfer.Id, cts); + var topts = new TransferOptions( stateChanged: (args) => { @@ -884,7 +870,7 @@ namespace slskd.Transfers.Downloads } // todo: broadcast - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cts.Token); } finally { @@ -901,7 +887,7 @@ namespace slskd.Transfers.Downloads // don't wait for the semaphore; if a previous progress update is still hanging, don't make // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems // but the alternative is to continue to stack slow writes on top of one another - if (syncRoot.Wait(millisecondsTimeout: 0, cts.Token)) + if (updateSyncRoot.Wait(millisecondsTimeout: 0, cts.Token)) { try { @@ -918,7 +904,7 @@ namespace slskd.Transfers.Downloads } finally { - syncRoot.Release(); + updateSyncRoot.Release(); } } else @@ -929,9 +915,6 @@ namespace slskd.Transfers.Downloads }), disposeOutputStreamOnCompletion: true); - // register the cancellation token - CancellationTokens.TryAdd(transfer.Id, cts); - System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null; @@ -968,7 +951,7 @@ namespace slskd.Transfers.Downloads transfer = transfer.WithSoulseekTransfer(completedTransfer); // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); @@ -1057,7 +1040,7 @@ namespace slskd.Transfers.Downloads }; // todo: broadcast - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); throw; } @@ -1070,7 +1053,7 @@ namespace slskd.Transfers.Downloads transfer.State = TransferStates.Completed | TransferStates.Errored; // todo: broadcast - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); throw; } -- cgit v1.2.3 From 16c9b47cc977800a567b59fba7986d475524ae9d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Oct 2025 15:41:31 -0500 Subject: big refactor :shrug: --- src/slskd/Transfers/Downloads/DownloadService.cs | 444 ++++++++++------------- 1 file changed, 200 insertions(+), 244 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index b7cacb84..10c8c0bc 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -242,33 +242,29 @@ namespace slskd.Transfers.Downloads throw; } - List acquiredLocks = []; List enqueued = []; List failed = []; - SemaphoreSlim semaphore; - Task semaphoreWaitTask; - // briefly obtain exclusive access over the semaphore dictionary to either get or create a record for this user - // this contends with the cleanup process, which will discard records if the associated semaphore can be acquired - // upon release of the semaphore, this logic will run and will potentially add a record right back + SemaphoreSlim userSemaphore; + Task userSemaphoreWaitTask; + + Log.Debug("Awaiting enqueue semaphore sync root"); await EnqueueSemaphoreSyncRoot.WaitAsync(cancellationToken); try { - // fetch or create a semaphore record for this user, and set up a task (but don't await it yet! to avoid cleanup contention) - semaphore = EnqueueSemaphores.GetOrAdd(username, (username) => new SemaphoreSlim(initialCount: 1, maxCount: 1)); - semaphoreWaitTask = semaphore.WaitAsync(cancellationToken); + Log.Debug("Acquired enqueue semaphore sync root"); + userSemaphore = EnqueueSemaphores.GetOrAdd(username, (username) => new SemaphoreSlim(initialCount: 1, maxCount: 1)); + userSemaphoreWaitTask = userSemaphore.WaitAsync(cancellationToken); } finally { EnqueueSemaphoreSyncRoot.Release(); + Log.Debug("Released enqueue semaphore sync root"); } - // wait until we can get exclusive access to this user. it's important that we do so, so we can optimize database - // access within the critical section. this allows us to fetch the transfers for this user only once, and we don't - // have to worry about the database changing while we're in the critical section Log.Debug("Awaiting enqueue semaphore for user {Username}", username); - await semaphoreWaitTask; + await userSemaphoreWaitTask; try { @@ -291,15 +287,23 @@ namespace slskd.Transfers.Downloads .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) .ToList(); + var concurrentEnqueueRequests = 15; // average album length, somewhat arbitrarily chosen + var maxTimeToWaitForEnqueueRequestAck = TimeSpan.FromMinutes(3); + var enqueueSemaphore = new SemaphoreSlim(initialCount: concurrentEnqueueRequests, maxCount: concurrentEnqueueRequests); + /* - iterate over the files, and either: + iterate over each of the files in the request. each file must be dispositioned as one of the following: + + 1. enqueued: passed duplicate checks and successfully kicked off a Task to enqueue the download + 2. failed: download is already in progress, or something went wrong kicking off the Task - 1. if there's no active download for the file already, insert a record and kick off the download task - 2. if there's an active download already, stick the file in the failed array + if we fail to enqueue a file, we must call TryFail() to ensure that if a record was inserted, it is + given a final disposition that will keep it from getting 'stuck' */ foreach (var file in files) { cancellationToken.ThrowIfCancellationRequested(); + Guid transferId = Guid.NewGuid(); try { @@ -321,9 +325,17 @@ namespace slskd.Transfers.Downloads continue; } + /* + add the transfer record to the database in the Queued | Locally state, and set the 'Removed' + property of any existing transfer to 'true', allowing the new record to supersede any old record(s) + on the UI + + we have to persist these changes to the database at this time so the record shows up on the UI, + otherwise the transfers only show up as they are enqueued. + */ var transfer = new Transfer() { - Id = Guid.NewGuid(), + Id = transferId, Username = username, Direction = TransferDirection.Download, Filename = file.Filename, // important! use the remote filename @@ -344,249 +356,149 @@ namespace slskd.Transfers.Downloads Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", file.Filename, username, record.Id); } - enqueued.Add(transfer); - - Log.Information("Successfully locally enqueued download of {Filename} from {Username}", file.Filename, username, transfer.Id); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); - failed.Add(file.Filename); - continue; - } - } - - /* - persist our database changes, including: - - * INSERTs for all of the newly enqueued files - * UPDATEs for any files that are complete but still being shown on the UI - */ - context.SaveChanges(); - - if (enqueued.Count == 0) - { - Log.Warning("None of the {Count} requested files from {Username} could be enqueued as they are already in progress", files.Count(), username); - return (enqueued, failed); - } - - /* - the files are all now in the database in the Queued | Locally state. - - we'll proceed with downloading them, but in a separate task run in the background - */ - Log.Debug("Scheduling batch remote enqueue Task for {Count} files from {Username}", enqueued.Count, username); - - var batchEnqueueTask = Task.Run(async () => - { - /* - 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 - - 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 - - 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. + /* + DANGER ZONE! this record is in the database now; we're on the hook for making sure it ends up + with a State that includes the Completed flag, else it remain "stuck" on the UI + */ + context.SaveChanges(); - 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 - */ - var concurrentRequests = 10; - var maxTimeToWaitForTransferAck = TimeSpan.FromMinutes(1); + /* + create a TaskCompletionSource that we can await for one of the following: - var semaphore = new SemaphoreSlim(initialCount: concurrentRequests, maxCount: concurrentRequests); + 1. the transfer enters the Queued | Remotely state + 2. the transfer enters a state containing Completed + 3. the linked CancellationTokenSource we add to CancellationTokens is cancelled + 4. the 'max wait time' CancellationTokenSource is cancelled + */ + var enqueuedTcs = new TaskCompletionSource(); - Log.Debug("Scheduling Tasks to download {Count} files from {Username}", enqueued.Count, username); + // satisfies condition #3; CancellationTokenSource set cancelled by the user (via API call) + var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + CancellationTokens.TryAdd(transfer.Id, cts); + cts.Token.Register(() => enqueuedTcs.TrySetCanceled()); - var tasks = enqueued.Select(async transfer => - { - Log.Debug("Awaiting download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); - await semaphore.WaitAsync(); + Log.Debug("Scheduling Task for enqueue of {Filename} from {Username}", file.Filename, username); - try + var downloadEnqueueTask = Task.Run(async () => { - Log.Debug("Acquired download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); + Log.Debug("Awaiting download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); + await enqueueSemaphore.WaitAsync(cts.Token); - var enqueuedTcs = new TaskCompletionSource(); - List transitions = []; - TransferStates state = TransferStates.None; - - // 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(() => + 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")); - } - }); + Log.Debug("Acquired download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); - void stateChanged(Transfer transfer) - { - state = transfer.State; - transitions.Add(transfer.State.ToString()); + List transitions = []; + TransferStates state = TransferStates.None; - // _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)) + // satisfies condition #4; remote user doesn't respond after a really long time + using var timeoutCts = new CancellationTokenSource(maxTimeToWaitForEnqueueRequestAck); + timeoutCts.Token.Register(() => { - enqueuedTcs.TrySetResult(transfer); - } + Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit of {Duration} seconds. State transition history: {History}", transfer.Filename, username, maxTimeToWaitForEnqueueRequestAck.TotalSeconds, string.Join(", ", transitions)); + enqueuedTcs.TrySetException(new TimeoutException($"Download failed to enqueue remotely after hard time limit of {maxTimeToWaitForEnqueueRequestAck.TotalSeconds} secs")); + }); - // 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)) + // satisfies conditions #1 and #2 + void stateChanged(Transfer transfer) { - if (transfer.State.HasFlag(TransferStates.Succeeded)) + state = transfer.State; + transitions.Add(transfer.State.ToString()); + + if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely)) { + // satisfies condition #1; transfer is now remotely queued enqueuedTcs.TrySetResult(transfer); } - else + + // satisfies condition #2; transfer advanced to a terminal state before being enqueued remotely (probably failed) + if (transfer.State.HasFlag(TransferStates.Completed)) { - enqueuedTcs.TrySetException(new TransferException(transfer.Exception)); + if (transfer.State.HasFlag(TransferStates.Succeeded)) + { + enqueuedTcs.TrySetResult(transfer); + } + else + { + enqueuedTcs.TrySetException(new TransferException(transfer.Exception)); + } } } - } - Log.Debug("Scheduling Task for download of {Filename} from {Username}", transfer.Filename, transfer.Username); + Log.Debug("Scheduling Task for download of {Filename} from {Username}", transfer.Filename, transfer.Username); - // 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 - var downloadTask = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken)).ContinueWith(task => - { - if (task.IsCompletedSuccessfully) + var downloadTask = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken: cts.Token)).ContinueWith(task => { - Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); - return; - } + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); + return; + } - /* - things that can cause us to arrive here: + Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", transfer.Filename, transfer.Username, task.Exception.Message); + if (!TryFail(transferId, exception: task.Exception)) + { + Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, task.Exception.Message); + } + }, cancellationToken: CancellationToken.None); // end downloadTask.Run(); - * 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); + Log.Debug("Download Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadTask.Status); - try - { - var foundTransfer = Find(t => t.Id == transfer.Id); + Log.Debug("Waiting for download of {Filename} from {Username} to transition into {State}", transfer.Filename, transfer.Username, TransferStates.Queued | TransferStates.Remotely); - if (foundTransfer is not null) - { - foundTransfer.EndedAt ??= DateTime.UtcNow; - foundTransfer.Exception ??= task.Exception.InnerException.Message; + /* + wait for one of the four conditions to be true: - if (!foundTransfer.State.HasFlag(TransferStates.Completed)) - { - foundTransfer.State = TransferStates.Completed | task.Exception.InnerException switch - { - OperationCanceledException => TransferStates.Cancelled, - TimeoutException => TransferStates.TimedOut, - _ => TransferStates.Errored, - }; - } + 1. the transfer enters the Queued | Remotely state + 2. the transfer enters a state containing Completed + 3. the linked CancellationTokenSource we add to CancellationTokens is cancelled + 4. the 'max wait time' CancellationTokenSource is cancelled + */ + await enqueuedTcs.Task; - Update(foundTransfer); - } - } - catch (Exception ex) + Log.Debug("Download of {Filename} from {Username} successfully entered state {State}", transfer.Filename, transfer.Username, state); + } + catch (Exception ex) + { + Log.Error(ex, "Download of {File} from {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); + if (!TryFail(transferId, exception: ex)) { Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message); } - }, cancellationToken); - - if (downloadTask.Status == TaskStatus.Canceled) - { - throw new OperationCanceledException($"The download Task for {transfer.Filename} from {transfer.Username} was cancelled"); } - - if (downloadTask.Status == TaskStatus.Faulted) + finally { - throw new Exception($"The download Task for {transfer.Filename} from {transfer.Username} faulted: {downloadTask.Exception}", downloadTask.Exception); + enqueueSemaphore.Release(); } - - Log.Debug("Download Task status: {Status}", downloadTask.Status); - - Log.Debug("Waiting for download of {Filename} from {Username} to transition into {State}", transfer.Filename, transfer.Username, TransferStates.Queued | TransferStates.Remotely); - - // 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; - - Log.Debug("Download of {Filename} from {Username} successfully entered state {State}", transfer.Filename, transfer.Username, state); - } - catch (Exception ex) + }, cancellationToken: cts.Token).ContinueWith(task => { - Log.Error(ex, "Failed to download {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); - - try + if (task.IsCompletedSuccessfully) { - var foundTransfer = Find(t => t.Id == transfer.Id); - - if (foundTransfer is not null) - { - foundTransfer.EndedAt ??= DateTime.UtcNow; - foundTransfer.Exception ??= ex.Message; - - if (!foundTransfer.State.HasFlag(TransferStates.Completed)) - { - foundTransfer.State = TransferStates.Completed | ex switch - { - OperationCanceledException => TransferStates.Cancelled, - TimeoutException => TransferStates.TimedOut, - _ => TransferStates.Errored, - }; - } - - Update(transfer); - } + Log.Information("Task for enqueue of {Filename} from {Username} completed successfully", file.Filename, username); + return; } - catch (Exception innerEx) + + Log.Error(task.Exception, "Task for enqueue of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, task.Exception.InnerException.Message); + if (!TryFail(transferId, exception: task.Exception)) { - Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); + Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, task.Exception.Message); } - } - finally - { - semaphore.Release(); - Log.Debug("Released download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); - } - }); + }, cancellationToken: CancellationToken.None); // end downloadEnqueueTask.Run(); - Log.Debug("Waiting for all {Count} download Tasks for {Username} to complete", enqueued.Count, username); - await Task.WhenAll(tasks); - }, cancellationToken).ContinueWith(task => - { - if (task.IsCompletedSuccessfully) + Log.Debug("Download enqueue Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadEnqueueTask.Status); + Log.Information("Successfully locally enqueued download of {Filename} from {Username}", file.Filename, username, transfer.Id); + enqueued.Add(transfer); + } + catch (Exception ex) { - Log.Information("Task for batch enqueue of {Count} files from {Username} completed successfully", files.Count(), username); - return; + Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); + TryFail(transferId, exception: ex); + failed.Add(file.Filename); + continue; } + } // end foreach() - Log.Error(task.Exception, "Task for batch enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); - }, cancellationToken: CancellationToken.None); - - if (batchEnqueueTask.Status == TaskStatus.Canceled) - { - throw new OperationCanceledException($"The batch enqueue Task for {enqueued.Count} files from {username} was cancelled"); - } - - if (batchEnqueueTask.Status == TaskStatus.Faulted) - { - throw new Exception($"The batch enqueue Task for {enqueued.Count} files from {username} faulted: {batchEnqueueTask.Exception}", batchEnqueueTask.Exception); - } - - Log.Debug("Batch enqueue Task status: {Status}", batchEnqueueTask.Status); Log.Information("Successfully enqueued {Count} files from {Username}", enqueued.Count, username); - return (enqueued, failed); } catch (Exception ex) @@ -596,7 +508,7 @@ namespace slskd.Transfers.Downloads } finally { - semaphore.Release(); + userSemaphore.Release(); Log.Debug("Released enqueue semaphore for user {Username}", username); } } @@ -775,12 +687,69 @@ namespace slskd.Transfers.Downloads /// A value indicating whether the download was successfully cancelled. public bool TryCancel(Guid id) { + // if the cancellation token is still in the dictionary, calling Cancel() on it _should_ + // cause the transfer operation to fail with an OperationCancelled exception and set the state + // of the transfer to Cancelled. _should_! if (CancellationTokens.TryRemove(id, out var cts)) { cts.Cancel(); return true; } + // if the cancellation token is no longer registered, something went wrong. in an attempt to get back + // to a good state, "manually" set the state of the transfer to cancelled, which should allow the user + // to clear it and try again. we shouldn't manipulate the record directly unless the token couldn't be + // found in the dictionary; we'll create a race condition (maybe that's ok? we can revisit later) + var t = Find(t => t.Id == id); + + if (t is not null) + { + t.EndedAt = DateTime.UtcNow; + t.State = TransferStates.Completed | TransferStates.Cancelled; + t.Exception = new OperationCanceledException().Message; + Update(t); + return true; + } + + // this transfer id didn't have a cancellation token registered, and we couldn't find it in the dictionary + return false; + } + + /// + /// Fails the download matching the specified with thee specified , + /// and sets the final state accordingly. + /// + /// + /// This method is designed to be idempotent, meaning subsequent calls for a given transfer shouldn't change + /// the EndedAt or Exception properties if they have already been set. If the transfer State already includes + /// the terminal Completed flag, it is unchanged. + /// + /// The unique identifier for the download. + /// The exception that caused the failure. + /// A value indicating whether the download was successfully failed. + public bool TryFail(Guid id, Exception exception) + { + var t = Find(t => t.Id == id); + + if (t is not null) + { + t.EndedAt ??= DateTime.UtcNow; + t.Exception ??= exception.Message; + + if (!t.State.HasFlag(TransferStates.Completed)) + { + t.State = TransferStates.Completed | exception switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; + } + + Update(t); + return true; + } + return false; } @@ -828,23 +797,19 @@ namespace slskd.Transfers.Downloads throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); } - /* - from this point forward, any exit from this method MUST result in an update to the Transfer record - in the database that sets EndedAt and ensures that the State property includes the Completed flag - - failure to do so means records will get "stuck" in the database/on the UI + // there _should_ be a cancellation token for this transfer in the dictionary; if so link it with the one we are given + // (which is probably the same one, harmless if so) to make sure we don't get any wires crossed + if (CancellationTokens.TryGetValue(transfer.Id, out var cancellationTokenSource)) + { + cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken).Token; + } - additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot - */ var updateSyncRoot = new SemaphoreSlim(1, 1); try { using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - CancellationTokens.TryAdd(transfer.Id, cts); - var topts = new TransferOptions( stateChanged: (args) => { @@ -870,7 +835,7 @@ namespace slskd.Transfers.Downloads } // todo: broadcast - SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cts.Token); + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); } finally { @@ -887,7 +852,7 @@ namespace slskd.Transfers.Downloads // don't wait for the semaphore; if a previous progress update is still hanging, don't make // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems // but the alternative is to continue to stack slow writes on top of one another - if (updateSyncRoot.Wait(millisecondsTimeout: 0, cts.Token)) + if (updateSyncRoot.Wait(millisecondsTimeout: 0, cancellationToken: cancellationToken)) { try { @@ -937,7 +902,7 @@ namespace slskd.Transfers.Downloads size: transfer.Size, startOffset: 0, token: null, - cancellationToken: cts.Token, + cancellationToken: cancellationToken, options: topts); Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); @@ -1028,16 +993,7 @@ namespace slskd.Transfers.Downloads { Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed; - - transfer.State |= ex switch - { - OperationCanceledException => TransferStates.Cancelled, - TimeoutException => TransferStates.TimedOut, - _ => TransferStates.Errored, - }; + TryFail(transfer.Id, exception: ex); // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); @@ -1048,9 +1004,7 @@ namespace slskd.Transfers.Downloads { Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Errored; + TryFail(transfer.Id, exception: ex); // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); @@ -1059,7 +1013,9 @@ namespace slskd.Transfers.Downloads } finally { - CancellationTokens.TryRemove(transfer.Id, out _); + // this is added in EnqueueAsync() + CancellationTokens.TryRemove(transfer.Id, out var cts); + cts?.Dispose(); } } -- cgit v1.2.3 From e21916a250fd983a5564fff85c62e30986c869b5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Oct 2025 16:08:22 -0500 Subject: remove and dispose cancellation tokens on failure --- src/slskd/Transfers/Downloads/DownloadService.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 10c8c0bc..3c78dae6 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -494,6 +494,12 @@ namespace slskd.Transfers.Downloads Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); TryFail(transferId, exception: ex); failed.Add(file.Filename); + + if (CancellationTokens.TryRemove(transferId, out var cts)) + { + cts.Dispose(); + } + continue; } } // end foreach() -- cgit v1.2.3 From c4a7f71d0b0b9e4bdff33bb9eb6145a1d783cb78 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Oct 2025 17:14:59 -0500 Subject: more refactoring --- src/slskd/Transfers/Downloads/DownloadService.cs | 75 +++++++++++++++++++----- 1 file changed, 60 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 3c78dae6..9b36f5ec 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -139,6 +139,24 @@ namespace slskd.Transfers.Downloads Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); } + /// + /// These tokens give users the ability to cancel transfers via the UI (or API). + /// + /// The lifecycle is: + /// + /// 1. in EnqueueAsync(), just before transfer records are added to the database, these CTS are created and + /// added to the dictionary + /// 2. in EnqueueAsync(), if there was an error or any condition which caused the transfer to not proceed was met, + /// the CTS is removed from the dictionary and disposed + /// 3. in DownloadAsync(), in the finally block after all post-download logic has been executed, the CTS + /// is removed and disposed. + /// + /// The CTS should be in the dictionary the entire time the transfer is "in flight", from the first moment it + /// comes into being (via database insert) until the eventual download process has completed or failed. + /// + /// Every cancellable operation in this flow needs to use this CTS token either directly or by linking it with another, + /// or we risk transfers getting stuck with no way for users to get rid of them. + /// private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } @@ -287,7 +305,25 @@ namespace slskd.Transfers.Downloads .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) .ToList(); - var concurrentEnqueueRequests = 15; // average album length, somewhat arbitrarily chosen + /* + determine how many concurrent enqueue requests we want to send to the remote client. + + sending a ton of them can bog the client down and fail transfers due to resource contention on both sides, + but both clients should be able to handle momentary 'bursts'. + + if the request contains 30 files or fewer, send all of the requests at the same time. the average number + of tracks in a single album is 15, so this is 2x as many as most enqueue requests will need. + + if that number is more than 30, send only 5 at a time; transfers will be starting as we are still + enqueueing files, and this raises the risk of errors considerably. + */ + var concurrentEnqueueRequests = 5; + + if (files.Count() <= 30) + { + concurrentEnqueueRequests = files.Count(); + } + var maxTimeToWaitForEnqueueRequestAck = TimeSpan.FromMinutes(3); var enqueueSemaphore = new SemaphoreSlim(initialCount: concurrentEnqueueRequests, maxCount: concurrentEnqueueRequests); @@ -356,12 +392,6 @@ namespace slskd.Transfers.Downloads Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", file.Filename, username, record.Id); } - /* - DANGER ZONE! this record is in the database now; we're on the hook for making sure it ends up - with a State that includes the Completed flag, else it remain "stuck" on the UI - */ - context.SaveChanges(); - /* create a TaskCompletionSource that we can await for one of the following: @@ -369,6 +399,9 @@ namespace slskd.Transfers.Downloads 2. the transfer enters a state containing Completed 3. the linked CancellationTokenSource we add to CancellationTokens is cancelled 4. the 'max wait time' CancellationTokenSource is cancelled + + add this to the dictionary before inserting the record, so we are guaranteed to have it + in the right place once the transfer hits the UI */ var enqueuedTcs = new TaskCompletionSource(); @@ -377,6 +410,12 @@ namespace slskd.Transfers.Downloads CancellationTokens.TryAdd(transfer.Id, cts); cts.Token.Register(() => enqueuedTcs.TrySetCanceled()); + /* + DANGER ZONE! this record is in the database now; we're on the hook for making sure it ends up + with a State that includes the Completed flag, else it remain "stuck" on the UI + */ + context.SaveChanges(); + Log.Debug("Scheduling Task for enqueue of {Filename} from {Username}", file.Filename, username); var downloadEnqueueTask = Task.Run(async () => @@ -702,13 +741,18 @@ namespace slskd.Transfers.Downloads return true; } - // if the cancellation token is no longer registered, something went wrong. in an attempt to get back - // to a good state, "manually" set the state of the transfer to cancelled, which should allow the user - // to clear it and try again. we shouldn't manipulate the record directly unless the token couldn't be - // found in the dictionary; we'll create a race condition (maybe that's ok? we can revisit later) + /* + if the cancellation token couldn't be found in the dictionary, either: + + 1. the transfer completed already + 2. something went wrong and the record is 'stuck' + + see if we can find the record, and if it's *NOT* completed, cancel it. otherwise, + leave it alone. + */ var t = Find(t => t.Id == id); - if (t is not null) + if (t is not null && !t.State.HasFlag(TransferStates.Completed)) { t.EndedAt = DateTime.UtcNow; t.State = TransferStates.Completed | TransferStates.Cancelled; @@ -1019,9 +1063,10 @@ namespace slskd.Transfers.Downloads } finally { - // this is added in EnqueueAsync() - CancellationTokens.TryRemove(transfer.Id, out var cts); - cts?.Dispose(); + if (CancellationTokens.TryRemove(transfer.Id, out var cts)) + { + cts?.Dispose(); + } } } -- cgit v1.2.3 From 227596c9e2575f5a9c48310a5343fa83243334c8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Oct 2025 17:24:54 -0500 Subject: Update src/slskd/Transfers/Downloads/DownloadService.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9b36f5ec..6b27f691 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -766,7 +766,7 @@ namespace slskd.Transfers.Downloads } /// - /// Fails the download matching the specified with thee specified , + /// Fails the download matching the specified with the specified , /// and sets the final state accordingly. /// /// -- cgit v1.2.3 From 3f45b49277f440a671d9b736a020a921cb778620 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Oct 2025 17:34:24 -0500 Subject: feedback --- src/slskd/Transfers/Downloads/DownloadService.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9b36f5ec..f09b3c13 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -849,10 +849,9 @@ namespace slskd.Transfers.Downloads // there _should_ be a cancellation token for this transfer in the dictionary; if so link it with the one we are given // (which is probably the same one, harmless if so) to make sure we don't get any wires crossed - if (CancellationTokens.TryGetValue(transfer.Id, out var cancellationTokenSource)) - { - cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken).Token; - } + CancellationTokens.TryGetValue(transfer.Id, out var cancellationTokenSource); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cancellationTokenSource?.Token ?? CancellationToken.None); + cancellationToken = cts.Token; var updateSyncRoot = new SemaphoreSlim(1, 1); @@ -958,7 +957,7 @@ namespace slskd.Transfers.Downloads Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we - // flushe any pending update, _probably_ pushing the state of the transfer back to InProgress + // flush any pending update, _probably_ pushing the state of the transfer back to InProgress rateLimiter.Dispose(); // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state @@ -1063,9 +1062,9 @@ namespace slskd.Transfers.Downloads } finally { - if (CancellationTokens.TryRemove(transfer.Id, out var cts)) + if (CancellationTokens.TryRemove(transfer.Id, out var storedCancellationTokenSource)) { - cts?.Dispose(); + storedCancellationTokenSource?.Dispose(); } } } @@ -1096,7 +1095,7 @@ namespace slskd.Transfers.Downloads { EnqueueSemaphores.TryRemove(kvp.Key, out var removed); removed.Dispose(); - Log.Debug($"Cleaned up enqueue semaphore for {kvp.Key}"); + Log.Debug("Cleaned up enqueue semaphore for {Key}", kvp.Key); } } } -- cgit v1.2.3 From 834eb6473cb97d139b23503a1607bc32d6296a4c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Oct 2025 17:50:21 -0500 Subject: optimizations --- src/slskd/Transfers/Downloads/DownloadService.cs | 32 +++++++++++++----------- 1 file changed, 18 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index fce4b2ce..cde2c403 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -223,19 +223,21 @@ namespace slskd.Transfers.Downloads throw new ArgumentException("Username is required", nameof(username)); } - if (!files.Any()) + var fileList = files.ToList(); + + if (fileList.Count == 0) { throw new ArgumentException("At least one file is required", nameof(files)); } - if (files.Count() != files.Distinct().Count()) + if (fileList.Count != fileList.Distinct().Count()) { throw new ArgumentException("Two or more files in request are duplicated", nameof(files)); } IPEndPoint endpoint; - Log.Information("Requested enqueue of {Count} files from user {Username}", files.Count(), username); + Log.Information("Requested enqueue of {Count} files from user {Username}", fileList.Count, username); // get the user's ip and port. this will throw if they are offline. try @@ -244,7 +246,7 @@ namespace slskd.Transfers.Downloads } catch (Exception ex) { - Log.Error(ex, "Failed to enqueue {Count} files from {Username}: {Message}", files.Count(), username, ex.Message); + Log.Error(ex, "Failed to enqueue {Count} files from {Username}: {Message}", fileList.Count, username, ex.Message); throw; } @@ -303,7 +305,7 @@ namespace slskd.Transfers.Downloads var existingInProgressRecords = existingRecords .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) - .ToList(); + .ToDictionary(t => t.Filename, t => t); /* determine how many concurrent enqueue requests we want to send to the remote client. @@ -319,9 +321,9 @@ namespace slskd.Transfers.Downloads */ var concurrentEnqueueRequests = 5; - if (files.Count() <= 30) + if (fileList.Count <= 30) { - concurrentEnqueueRequests = files.Count(); + concurrentEnqueueRequests = fileList.Count; } var maxTimeToWaitForEnqueueRequestAck = TimeSpan.FromMinutes(3); @@ -336,7 +338,7 @@ namespace slskd.Transfers.Downloads if we fail to enqueue a file, we must call TryFail() to ensure that if a record was inserted, it is given a final disposition that will keep it from getting 'stuck' */ - foreach (var file in files) + foreach (var file in fileList) { cancellationToken.ThrowIfCancellationRequested(); Guid transferId = Guid.NewGuid(); @@ -352,7 +354,7 @@ namespace slskd.Transfers.Downloads 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 */ - var existingInProgressRecord = existingInProgressRecords.FirstOrDefault(t => t.Filename == file.Filename); + existingInProgressRecords.TryGetValue(file.Filename, out var existingInProgressRecord); if (existingInProgressRecord is not null || Client.Downloads.Any(u => u.Username == username && u.Filename == file.Filename)) { @@ -474,10 +476,11 @@ namespace slskd.Transfers.Downloads return; } - Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", transfer.Filename, transfer.Username, task.Exception.Message); + Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, task.Exception.InnerException?.Message ?? task.Exception.Message); + if (!TryFail(transferId, exception: task.Exception)) { - Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, task.Exception.Message); + Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, task.Exception.Message); } }, cancellationToken: CancellationToken.None); // end downloadTask.Run(); @@ -517,7 +520,8 @@ namespace slskd.Transfers.Downloads return; } - Log.Error(task.Exception, "Task for enqueue of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, task.Exception.InnerException.Message); + Log.Error(task.Exception, "Task for enqueue of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, task.Exception.InnerException?.Message ?? task.Exception.Message); + if (!TryFail(transferId, exception: task.Exception)) { Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, task.Exception.Message); @@ -525,7 +529,7 @@ namespace slskd.Transfers.Downloads }, cancellationToken: CancellationToken.None); // end downloadEnqueueTask.Run(); Log.Debug("Download enqueue Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadEnqueueTask.Status); - Log.Information("Successfully locally enqueued download of {Filename} from {Username}", file.Filename, username, transfer.Id); + Log.Information("Successfully locally enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transfer.Id); enqueued.Add(transfer); } catch (Exception ex) @@ -548,7 +552,7 @@ namespace slskd.Transfers.Downloads } catch (Exception ex) { - Log.Error(ex, "Failed to enqueue one or more of {Count} files from {Username}: {Message}", files.Count(), username, ex.Message); + Log.Error(ex, "Failed to enqueue one or more of {Count} files from {Username}: {Message}", fileList.Count, username, ex.Message); throw; } finally -- cgit v1.2.3 From 47bf4c909febb5c7e3d19c29dee4810af6ed9238 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 2 Nov 2025 11:41:45 -0600 Subject: bump Soulseek.NET to 8.5.0 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 29d362ef..63dd6937 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 b98a3d04d543ac7d9b108c640cfeb7c7956ffeda Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 2 Nov 2025 17:41:50 -0600 Subject: filter existing records by filename --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index cde2c403..9d0a8ed9 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -387,7 +387,7 @@ namespace slskd.Transfers.Downloads Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id); - foreach (var record in existingRecords.Where(t => !t.Removed)) + foreach (var record in existingRecords.Where(t => t.Filename == file.Filename && !t.Removed)) { record.Removed = true; context.Update(record); -- cgit v1.2.3 From 0dbcf34423aaf73730700cb1d31e140a6f2cc38a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 2 Nov 2025 18:41:06 -0600 Subject: make check of index case insensitive --- src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs index 9b3f14a8..8ae13734 100644 --- a/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs @@ -41,8 +41,8 @@ public class Z07062025_TransferIndexesMigration : IMigration var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); var txfers = idxes["Transfers"]; - var directionExists = txfers.Any(c => c.Name == "IDX_Transfers_Direction"); - var stateExists = txfers.Any(c => c.Name == "IDX_Transfers_State"); + var directionExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Direction", StringComparison.OrdinalIgnoreCase)); + var stateExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_State", StringComparison.OrdinalIgnoreCase)); if (directionExists && stateExists) { -- cgit v1.2.3 From 51dcd376806bda6287fd42cafbdd47810b6420de Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 3 Nov 2025 17:51:46 -0600 Subject: increase concurrent download requests to 2, return enqueued/failed response --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index f38c4b87..6be11b2d 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -53,7 +53,7 @@ namespace slskd.Transfers.API OptionsSnapshot = optionsSnapshot; } - private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(1, 1); + private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(2, 2); private ITransferService Transfers { get; } private IOptionsSnapshot OptionsSnapshot { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); @@ -226,8 +226,9 @@ namespace slskd.Transfers.API try { - await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)), cancellationToken); - return StatusCode(201); + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)), cancellationToken); + + return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); } catch (Exception ex) { -- cgit v1.2.3 From 1326f1f09cc6e7541681a9b523c549e5a7a73190 Mon Sep 17 00:00:00 2001 From: tommytz Date: Sun, 9 Nov 2025 15:43:47 +1300 Subject: system menu scrolls on overflow x --- src/web/src/components/System/System.css | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css index a3a2c83a..bd9a6f99 100644 --- a/src/web/src/components/System/System.css +++ b/src/web/src/components/System/System.css @@ -8,6 +8,10 @@ margin-bottom: 16px; } +.system .menu.tabular { + overflow: auto hidden; +} + .logs-table, .events-table { font-size: smaller; } -- cgit v1.2.3 From efe4164f73e9c13fdaf099b41a9230b4d87960d9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 11 Nov 2025 19:30:04 -0600 Subject: add SQLite flags --- src/slskd/Core/Options.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 38416ca2..a569841f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -461,6 +461,22 @@ namespace slskd [EnvironmentVariable("OPTIMISTIC_RELAY_FILE_INFO")] [Description("use uploaded relay shares as source of truth for file existence and size")] public bool OptimisticRelayFileInfo { get; init; } = false; + + /// + /// Gets a value indicating whether SQLite cache sharing should be disabled (set to Private). + /// + [Argument(default, "no-sqlite-cache-sharing")] + [EnvironmentVariable("NO_SQLITE_CACHE_SHARING")] + [Description("disable SQLite cache sharing")] + public bool NoSqliteCacheSharing { get; init; } = false; + + /// + /// Gets a value indicating whether SQLite pooling should be disabled. + /// + [Argument(default, "no-sqlite-pooling")] + [EnvironmentVariable("NO_SQLITE_POOLING")] + [Description("disable SQLite pooling")] + public bool NoSqlitePooling { get; init; } = false; } /// -- cgit v1.2.3 From 4ef3ae10584deca3c08ab34be7645d66935b91e1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 11 Nov 2025 19:30:18 -0600 Subject: use SQLite flags --- src/slskd/Program.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index bf0428d7..742ee51e 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -610,9 +610,12 @@ namespace slskd var connectionStringDictionary = new ConnectionStringDictionary(Database.List .Select(database => { + var caching = OptionsAtStartup.Flags.NoSqliteCacheSharing ? "Private" : "Shared"; + var pooling = OptionsAtStartup.Flags.NoSqlitePooling ? "False" : "True"; // don't invert and ToString this it is confusing + var connStr = OptionsAtStartup.Flags.Volatile - ? $"Data Source=file:{database}?mode=memory;Cache=shared;Pooling=True;" - : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Cache=shared;Pooling=True;"; + ? $"Data Source=file:{database}?mode=memory;Cache={caching};Pooling={pooling};" + : $"Data Source={Path.Combine(DataDirectory, $"{database}.db")};Cache={caching};Pooling={pooling}"; return new KeyValuePair(database, connStr); }) -- cgit v1.2.3 From 276857f172849f934ffce57194c070f560ff89be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Nov 2025 15:27:30 -0600 Subject: create and set pragmas for databases during initialization --- src/slskd/Program.cs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 742ee51e..b59fca83 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1216,11 +1216,48 @@ namespace slskd } }); + /* + instantiate the DbContext and make sure it is created + */ using var ctx = services .BuildServiceProvider() .GetRequiredService>() .CreateDbContext(); + Log.Debug("Ensuring {Contex} is created", typeof(T).Name); + ctx.Database.EnsureCreated(); + + /* + set (and validate) our desired PRAGMAs + */ + ctx.Database.OpenConnection(); + var conn = ctx.Database.GetDbConnection(); + + Log.Debug("Setting PRAGMAs for {Contex}", typeof(T).Name); + using var initCommand = conn.CreateCommand(); + initCommand.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=1; PRAGMA optimize;"; + initCommand.ExecuteNonQuery(); + + using var journalCmd = conn.CreateCommand(); + journalCmd.CommandText = "PRAGMA journal_mode;"; + var journalMode = journalCmd.ExecuteScalar()?.ToString(); + + if (!journalMode.Equals("WAL", StringComparison.OrdinalIgnoreCase)) + { + Log.Warning("Failed to set database {Type} journal_mode PRAGMA to WAL; performance may be reduced", typeof(T).Name); + } + + using var syncCmd = conn.CreateCommand(); + syncCmd.CommandText = "PRAGMA synchronous;"; + var sync = syncCmd.ExecuteScalar()?.ToString(); + + if (!sync.Equals("1", StringComparison.OrdinalIgnoreCase)) + { + Log.Warning("Failed to set database {Type} synchronous PRAGMA to 1; performance may be reduced", typeof(T).Name); + } + + Log.Debug("PRAGMAs for {Context}: journal_mode={JournalMode}, synchronous={Synchronous}", typeof(T).Name, journalMode, sync); + return services; } catch (Exception ex) -- cgit v1.2.3 From 30889200a22de1364ffdf1824fa209ec4144ef1b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Nov 2025 15:28:04 -0600 Subject: remove redundant database creation --- src/slskd/Events/EventsDbContext.cs | 1 - src/slskd/Messaging/MessagingDbContext.cs | 1 - src/slskd/Search/SearchDbContext.cs | 1 - src/slskd/Transfers/TransfersDbContext.cs | 1 - 4 files changed, 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Events/EventsDbContext.cs b/src/slskd/Events/EventsDbContext.cs index a86f5d1c..8b45a803 100644 --- a/src/slskd/Events/EventsDbContext.cs +++ b/src/slskd/Events/EventsDbContext.cs @@ -25,7 +25,6 @@ public class EventsDbContext : DbContext public EventsDbContext(DbContextOptions options) : base(options) { - Database.EnsureCreated(); } public DbSet Events { get; set; } diff --git a/src/slskd/Messaging/MessagingDbContext.cs b/src/slskd/Messaging/MessagingDbContext.cs index 5acb94ae..c6352c6e 100644 --- a/src/slskd/Messaging/MessagingDbContext.cs +++ b/src/slskd/Messaging/MessagingDbContext.cs @@ -25,7 +25,6 @@ namespace slskd.Messaging public MessagingDbContext(DbContextOptions options) : base(options) { - Database.EnsureCreated(); } public DbSet Conversations { get; set; } diff --git a/src/slskd/Search/SearchDbContext.cs b/src/slskd/Search/SearchDbContext.cs index bc6ee147..1d710e42 100644 --- a/src/slskd/Search/SearchDbContext.cs +++ b/src/slskd/Search/SearchDbContext.cs @@ -25,7 +25,6 @@ namespace slskd.Search public SearchDbContext(DbContextOptions options) : base(options) { - Database.EnsureCreated(); } public DbSet Searches { get; set; } diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index ea138bcd..eac4935b 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -26,7 +26,6 @@ namespace slskd.Transfers public TransfersDbContext(DbContextOptions options) : base(options) { - Database.EnsureCreated(); } public DbSet Transfers { get; set; } -- cgit v1.2.3 From 83a64887d3ef6fea35e4752ebcf80f10a4a6eaca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Nov 2025 15:28:24 -0600 Subject: set synchronous pragma for shares to off --- src/slskd/Shares/SqliteShareRepository.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index f457adba..711bb21e 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -157,7 +157,9 @@ namespace slskd.Shares { using var conn = GetConnection(); - conn.ExecuteNonQuery("PRAGMA journal_mode=WAL"); + // warning: with synchronous=0, an operating system crash can leave the database corrupted. + // if this occurs we should generate a new one, so this is _probably_ ok + conn.ExecuteNonQuery("PRAGMA journal_mode=WAL; PRAGMA synchronous=0;"); if (discardExisting) { -- cgit v1.2.3 From 4e826f74bfb40a8741c78b2a41d4afdf9a34699c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Nov 2025 15:46:57 -0600 Subject: add note about synchronous --- src/slskd/Program.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index b59fca83..639d3a88 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1229,6 +1229,10 @@ namespace slskd /* set (and validate) our desired PRAGMAs + + note: synchronous mode wants to default to 2, and setting it here may not actually do anything + an alternative would be to set it at the start of each new connection, but i'm unsure if that + would have the intended effect. revisit later. */ ctx.Database.OpenConnection(); var conn = ctx.Database.GetDbConnection(); -- cgit v1.2.3 From 70f16315cf407bdaa5487e9b818acd98704714cf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Nov 2025 18:34:28 -0600 Subject: use an interceptor to set synchronous pragma for each connection --- src/slskd/Core/Data/SqlitePragmaInterceptor.cs | 55 ++++++++++++++++++++++++++ src/slskd/Program.cs | 5 +-- 2 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 src/slskd/Core/Data/SqlitePragmaInterceptor.cs (limited to 'src') diff --git a/src/slskd/Core/Data/SqlitePragmaInterceptor.cs b/src/slskd/Core/Data/SqlitePragmaInterceptor.cs new file mode 100644 index 00000000..b32982b1 --- /dev/null +++ b/src/slskd/Core/Data/SqlitePragmaInterceptor.cs @@ -0,0 +1,55 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd +{ + using System.Data.Common; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Data.Sqlite; + using Microsoft.EntityFrameworkCore.Diagnostics; + + /// + /// Intercepts SQLite database connections to set PRAGMAs immediately after opening. + /// + public class SqliteConnectionOpenedInterceptor : DbConnectionInterceptor + { + public override void ConnectionOpened(DbConnection connection, ConnectionEndEventData eventData) + { + if (connection is SqliteConnection) + { + using var cmd = connection.CreateCommand(); + cmd.CommandText = "PRAGMA synchronous=1;"; + cmd.ExecuteNonQuery(); + } + + base.ConnectionOpened(connection, eventData); + } + + public override async Task ConnectionOpenedAsync(DbConnection connection, ConnectionEndEventData eventData, CancellationToken cancellationToken = default) + { + if (connection is SqliteConnection) + { + using var cmd = connection.CreateCommand(); + cmd.CommandText = "PRAGMA synchronous=1;"; + await cmd.ExecuteNonQueryAsync(cancellationToken); + } + + await base.ConnectionOpenedAsync(connection, eventData, cancellationToken); + } + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 639d3a88..ee9e2d0c 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1209,6 +1209,7 @@ namespace slskd services.AddDbContextFactory(options => { options.UseSqlite(connectionString); + options.AddInterceptors(new SqliteConnectionOpenedInterceptor()); if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL) { @@ -1230,9 +1231,7 @@ namespace slskd /* set (and validate) our desired PRAGMAs - note: synchronous mode wants to default to 2, and setting it here may not actually do anything - an alternative would be to set it at the start of each new connection, but i'm unsure if that - would have the intended effect. revisit later. + synchronous mode is also set upon every connection via SqliteConnectionOpenedInterceptor. */ ctx.Database.OpenConnection(); var conn = ctx.Database.GetDbConnection(); -- cgit v1.2.3 From e763715bd89cbf8c10537fc72905d4358caf8215 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 16 Nov 2025 18:37:55 -0600 Subject: remove file validation for unix sockets --- src/slskd/Core/Options.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index a569841f..61e2878c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1837,7 +1837,6 @@ namespace slskd [Argument(default, "http-socket")] [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] - [FileDoesNotExist] [AbsoluteFilePath] [RequiresRestart] public string Socket { get; init; } -- cgit v1.2.3 From d95a79503269abe77b4889a68a801fcebcb45b02 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 17 Nov 2025 20:50:42 +0000 Subject: Bump js-yaml from 3.14.1 to 3.14.2 in /src/web Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 3.14.1 to 3.14.2. - [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md) - [Commits](https://github.com/nodeca/js-yaml/compare/3.14.1...3.14.2) --- updated-dependencies: - dependency-name: js-yaml dependency-version: 3.14.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 7d0f2427..df643828 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -3424,10 +3424,11 @@ } }, "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "version": "3.14.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", + "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", "dev": true, + "license": "MIT", "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" @@ -13942,10 +13943,11 @@ } }, "node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", "dev": true, + "license": "MIT", "dependencies": { "argparse": "^2.0.1" }, @@ -19412,10 +19414,11 @@ } }, "node_modules/svgo/node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", + "version": "3.14.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", + "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", "dev": true, + "license": "MIT", "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" -- cgit v1.2.3 From 277fed8cdd5187769479eed60754b300b96761eb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Nov 2025 17:33:00 -0600 Subject: add flag to enable logging of unobserved exceptions --- config/slskd.example.yml | 1 + src/slskd/Core/Options.cs | 9 +++++++++ src/slskd/Program.cs | 15 +++++++++------ 3 files changed, 19 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 419c0c9f..a0ca4f3f 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -13,6 +13,7 @@ # force_migrations: false # no_version_check: false # log_sql: false +# log_unobserved_exceptions: false # experimental: false # volatile: false # case_sensitive_reg_ex: false diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 61e2878c..ec94afcb 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -417,6 +417,15 @@ namespace slskd [RequiresRestart] public bool LogSQL { get; init; } = false; + /// + /// Gets a value indicating whether to log unobserved Exceptions. + /// + [Argument(default, "log-unobserved-exceptions")] + [EnvironmentVariable("LOG_UNOBSERVED_EXCEPTIONS")] + [Description("log unobserved exceptions (caution: verbose)")] + [RequiresRestart] + public bool LogUnobservedExceptions { get; init; } = false; + /// /// Gets a value indicating whether the application should run in experimental mode. /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index ee9e2d0c..07d08fca 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1143,12 +1143,15 @@ namespace slskd })) .CreateLogger(); - // // occurs when a faulted task's unobserved exception is about to trigger exception escalation policy, which, by default, would terminate the process. - // TaskScheduler.UnobservedTaskException += (sender, e) => - // { - // Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message); - // e.SetObserved(); - // }; + if (OptionsAtStartup.Flags.LogUnobservedExceptions) + { + // log Exceptions raised on fired-and-forgotten tasks, which adds very little value but might help debug someday + TaskScheduler.UnobservedTaskException += (sender, e) => + { + Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message); + e.SetObserved(); + }; + } AppDomain.CurrentDomain.UnhandledException += (sender, e) => { -- cgit v1.2.3 From 99207f0957f4597a36e56483560c67dc68f4d00a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 22 Nov 2025 17:40:26 -0600 Subject: fix build warnings --- src/slskd/Events/Types/Events.cs | 1 + src/slskd/Telemetry/API/TelemetryController.cs | 2 +- src/slskd/Telemetry/TelemetryService.cs | 2 +- src/slskd/Telemetry/Types/PrometheusMetric.cs | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs index 6e99b800..577e41e3 100644 --- a/src/slskd/Events/Types/Events.cs +++ b/src/slskd/Events/Types/Events.cs @@ -28,6 +28,7 @@ public enum EventType DownloadFileComplete = 2, DownloadDirectoryComplete = 3, UploadFileComplete = 4, + // UploadDirectoryComplete = 5, PrivateMessageReceived = 6, RoomMessageReceived = 7, diff --git a/src/slskd/Telemetry/API/TelemetryController.cs b/src/slskd/Telemetry/API/TelemetryController.cs index 2207ac8c..d5c44c1a 100644 --- a/src/slskd/Telemetry/API/TelemetryController.cs +++ b/src/slskd/Telemetry/API/TelemetryController.cs @@ -57,7 +57,7 @@ public class TelemetryController : ControllerBase /// * node_filesystem_avail_bytes = how much space is left on the system /// * node_network = info about network adapters on the system /// Other - /// * process_start_time_seconds = unix timestamp of start time + /// * process_start_time_seconds = unix timestamp of start time. /// private List KpiRegexes { get; } = new List { diff --git a/src/slskd/Telemetry/TelemetryService.cs b/src/slskd/Telemetry/TelemetryService.cs index c3d66196..1c124610 100644 --- a/src/slskd/Telemetry/TelemetryService.cs +++ b/src/slskd/Telemetry/TelemetryService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify diff --git a/src/slskd/Telemetry/Types/PrometheusMetric.cs b/src/slskd/Telemetry/Types/PrometheusMetric.cs index 53b8dc10..93ca6422 100644 --- a/src/slskd/Telemetry/Types/PrometheusMetric.cs +++ b/src/slskd/Telemetry/Types/PrometheusMetric.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify -- cgit v1.2.3