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 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