From ce33585c58a35d9616fa77204c82cd02fc27c553 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Oct 2025 17:50:26 -0500 Subject: get rid of the confusing 't' --- src/slskd/Transfers/Uploads/UploadService.cs | 68 +++++++++++++++------------- 1 file changed, 37 insertions(+), 31 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 6db9f6a5..ee6185cc 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -69,7 +69,7 @@ namespace slskd.Transfers.Uploads /// /// Uploads the specified enqueued to the requesting user. /// - /// The transfer to upload. + /// The Transfer to upload. /// The operation context. /// Thrown if the specified Transfer is null. /// Thrown if the specified Transfer ID can't be found in the database. @@ -211,7 +211,7 @@ namespace slskd.Transfers.Uploads /// /// Uploads the specified enqueued to the requesting user. /// - /// The transfer to upload. + /// The Transfer to upload. /// The operation context. /// Thrown if the specified Transfer is null. /// Thrown if the specified Transfer ID can't be found in the database. @@ -228,7 +228,7 @@ namespace slskd.Transfers.Uploads return null; } - Transfer t = transfer; + Log.Debug("Acquired lock {LockName}", lockName); /* fetch an updated copy of the transfer record from the database; now that we are locked, we *should* @@ -237,12 +237,12 @@ namespace slskd.Transfers.Uploads we're not using DbContext and tracked changes here because we don't want to hold a connection open for the duration of the upload */ - t = Find(t => t.Id == transfer.Id) + transfer = Find(t => t.Id == transfer.Id) ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); - if (t.State != (TransferStates.Queued | TransferStates.Locally)) + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) { - throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {t.State}"); + throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); } /* @@ -250,7 +250,7 @@ namespace slskd.Transfers.Uploads check that list to see if there's already an instance of this upload in it, just in case we've gotten out of sync somehow */ - if (Client.Uploads.Any(u => u.Username == t.Username && u.Filename == t.Filename)) + if (Client.Uploads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) { throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered"); } @@ -259,14 +259,14 @@ namespace slskd.Transfers.Uploads // statistics. this is so that we can accurately determine their effective group. try { - if (!Users.IsWatched(t.Username)) + if (!Users.IsWatched(transfer.Username)) { - await Users.WatchAsync(t.Username); + await Users.WatchAsync(transfer.Username); } } catch (Exception ex) { - Log.Warning(ex, "Failed to watch user {Username}", t.Username); + Log.Warning(ex, "Failed to watch user {Username}", transfer.Username); } var cts = new CancellationTokenSource(); @@ -300,25 +300,24 @@ namespace slskd.Transfers.Uploads */ try { - Log.Debug("Acquired lock {LockName}", lockName); - Log.Information("Initializing upload {Filename} to {Username}", t.Filename, t.Username); + Log.Information("Initializing upload of {Filename} to {Username}", transfer.Filename, transfer.Username); // locate the file on disk. we checked this once already when enqueueing, but it may have moved since // can throw NotFoundException - (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: t.Filename); + (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: transfer.Filename); using var rateLimiter = new RateLimiter(250, flushOnDispose: true); var topts = new TransferOptions( stateChanged: (args) => { - Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, t.Username, args.PreviousState, args.Transfer.State); + Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, transfer.Username, args.PreviousState, args.Transfer.State); // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions; // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup if (Application.IsShuttingDown) { - Log.Debug("Upload update of {Filename} to {Username} not persisted; app is shutting down", t.Filename, t.Username); + Log.Debug("Upload update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); return; } @@ -367,10 +366,10 @@ namespace slskd.Transfers.Uploads slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); // register the cancellation token - CancellationTokens.TryAdd(t.Id, cts); + CancellationTokens.TryAdd(transfer.Id, cts); // add the transfer to the UploadQueue so that it can become eligible for selection - Queue.Enqueue(t.Username, t.Filename); + Queue.Enqueue(transfer.Username, transfer.Filename); transfer.EnqueuedAt = DateTime.UtcNow; SynchronizedUpdate(transfer); @@ -379,8 +378,8 @@ namespace slskd.Transfers.Uploads if (host == Program.LocalHostName) { completedTransfer = await Client.UploadAsync( - username: t.Username, - remoteFilename: t.Filename, + username: transfer.Username, + remoteFilename: transfer.Filename, size: localFileLength, inputStreamFactory: (startOffset) => { @@ -398,14 +397,14 @@ namespace slskd.Transfers.Uploads else { completedTransfer = await Client.UploadAsync( - username: t.Username, - remoteFilename: t.Filename, + username: transfer.Username, + remoteFilename: transfer.Filename, size: localFileLength, - inputStreamFactory: (startOffset) => Relay.GetFileStreamAsync(agentName: host, filename: t.Filename, startOffset, id: t.Id), + inputStreamFactory: (startOffset) => Relay.GetFileStreamAsync(agentName: host, filename: transfer.Filename, startOffset, id: transfer.Id), options: topts, cancellationToken: cts.Token); - Relay.TryCloseFileStream(host, id: t.Id); + Relay.TryCloseFileStream(host, id: transfer.Id); } // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we @@ -423,7 +422,7 @@ namespace slskd.Transfers.Uploads { Timestamp = transfer.EndedAt.Value, LocalFilename = localFilename, - RemoteFilename = t.Filename, + RemoteFilename = transfer.Filename, Transfer = transfer, }); @@ -439,11 +438,18 @@ namespace slskd.Transfers.Uploads throw; } - catch (OperationCanceledException ex) + catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) { transfer.EndedAt = DateTime.UtcNow; transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Cancelled; + transfer.State = TransferStates.Completed; + + transfer.State |= ex switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; // todo: broadcast SynchronizedUpdate(transfer, cancellable: false); @@ -452,7 +458,7 @@ namespace slskd.Transfers.Uploads } catch (Exception ex) { - Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", t.Filename, t.Username, ex.Message); + Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); transfer.EndedAt = DateTime.UtcNow; transfer.Exception = ex.Message; @@ -469,7 +475,7 @@ namespace slskd.Transfers.Uploads { try { - Relay.TryCloseFileStream(host, id: t.Id); + Relay.TryCloseFileStream(host, id: transfer.Id); } catch { @@ -482,16 +488,16 @@ namespace slskd.Transfers.Uploads Locks.TryRemove(lockName, out _); Log.Debug("Released lock {LockName}", lockName); - CancellationTokens.TryRemove(t.Id, out _); + CancellationTokens.TryRemove(transfer.Id, out _); // if for some reason this logic exits without the slotReleased delegate and Complete() being invoked, // the file will get stuck in the queue and prevent any further uploads to the user. be extra cautious // and ensure it gets removed - Queue.TryComplete(username: t.Username, filename: t.Filename); + Queue.TryComplete(username: transfer.Username, filename: transfer.Filename); } catch (Exception ex) { - Log.Error(ex, "Failed to finalize upload of {Filename} to {Username}: {Message}", t.Filename, t.Username, ex.Message); + Log.Error(ex, "Failed to finalize upload of {Filename} to {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); throw; } } -- cgit v1.2.3 From ef9acb6f51294737546c28cc330563b55f90d1a7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 1 Oct 2025 17:55:27 -0500 Subject: implement DownloadAsync --- src/slskd/Transfers/Downloads/DownloadService.cs | 292 ++++++++++++++++++++++- 1 file changed, 289 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index ef8e84bf..72d762c0 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -59,7 +59,18 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + + /// + /// Downloads the specified enqueued from the remote user. + /// + /// The Transfer to download. + /// The operation context. + /// Thrown if the specified Transfer is null. + /// Thrown if the specified Transfer ID can't be found in the database. + /// Thrown if the specified Transfer is not in the Queued | Locally state. + /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. + Task DownloadAsync(Transfer transfer); /// /// Finds a single download matching the specified . @@ -144,6 +155,7 @@ namespace slskd.Transfers.Downloads private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private EventBus EventBus { get; } + private ConcurrentDictionary Locks { get; } = new(); /// /// Adds the specified . Supersedes any existing record for the same file and username. @@ -171,6 +183,278 @@ namespace slskd.Transfers.Downloads context.SaveChanges(); } + /// + /// Downloads the specified enqueued from the remote user. + /// + /// The Transfer to download. + /// The operation context. + /// Thrown if the specified Transfer is null. + /// Thrown if the specified Transfer ID can't be found in the database. + /// Thrown if the specified Transfer is not in the Queued | Locally state. + /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. + public async Task DownloadAsync(Transfer transfer) + { + var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; + + if (!Locks.TryAdd(lockName, true)) + { + Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); + return null; + } + + Log.Debug("Acquired lock {LockName}", lockName); + + /* + fetch an updated copy of the transfer record from the database; now that we are locked, we *should* + have exclusive access to this record + + we're not using DbContext and tracked changes here because we don't want to hold a connection + open for the duration of the download + */ + transfer = Find(t => t.Id == transfer.Id) + ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + + /* + Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; + check that list to see if there's already an instance of this download in it, just in case we've gotten + out of sync somehow + */ + if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) + { + throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); + } + + var cts = new CancellationTokenSource(); + var syncRoot = new SemaphoreSlim(1, 1); + + void SynchronizedUpdate(Transfer transfer, bool cancellable = true) + { + syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); + + try + { + Update(transfer); + } + finally + { + syncRoot.Release(); + } + } + + /* + from this point forward, any exit from this method MUST result in an update to the Transfer record + in the database that sets EndedAt and ensures that the State property includes the Completed flag + + failure to do so means records will get "stuck" in the database/on the UI + + additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot + */ + try + { + Log.Information("Initializing download of {Filename} from {Username}", transfer.Filename, transfer.Username); + + using var rateLimiter = new RateLimiter(250, flushOnDispose: true); + + var topts = new TransferOptions( + stateChanged: (args) => + { + Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", transfer.Filename, transfer.Username, args.PreviousState, args.Transfer.State); + + // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions; + // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup + if (Application.IsShuttingDown) + { + Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); + return; + } + + transfer = transfer.WithSoulseekTransfer(args.Transfer); + + // we don't know when the download is actually enqueued (remotely) until it switches into that state + // when it is enqueued locally is irrelevant, due to internal throttling etc + if (transfer.EnqueuedAt is null && args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) + { + transfer.EnqueuedAt = DateTime.UtcNow; + } + + // todo: broadcast + SynchronizedUpdate(transfer); + }, + progressUpdated: (args) => rateLimiter.Invoke(() => + { + // don't do anything unless the `transfer` within the outer scope is in the + // InProgress state; this will help prevent out-of-band updates that are sometimes + // being made after the transfer is completed, causing them to appear 'stuck' + if (transfer.State == TransferStates.InProgress) + { + syncRoot.Wait(cts.Token); + + try + { + // check again to see if the state changed while we were waiting to obtain the lock + if (transfer.State == TransferStates.InProgress) + { + // update only the properties that we expect to change between progress updates + // this helps prevent this update from 'stepping' on other updates + transfer.BytesTransferred = args.Transfer.BytesTransferred; + transfer.AverageSpeed = args.Transfer.AverageSpeed; + + using var context = ContextFactory.CreateDbContext(); + + context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + } + } + finally + { + syncRoot.Release(); + } + } + }), + disposeOutputStreamOnCompletion: true); + + // register the cancellation token + CancellationTokens.TryAdd(transfer.Id, cts); + + var completedTransfer = await Client.DownloadAsync( + username: transfer.Username, + remoteFilename: transfer.Filename, + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + options: new CreateFileOptions + { + Access = System.IO.FileAccess.Write, + Mode = System.IO.FileMode.Create, // overwrites file if it exists + Share = System.IO.FileShare.None, // exclusive access for the duration of the download + UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() + : null, + })), + size: transfer.Size, + startOffset: 0, + token: null, + cancellationToken: cts.Token, + options: topts); + + // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we + // flushe any pending update, _probably_ pushing the state of the transfer back to InProgress + rateLimiter.Dispose(); + + // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state + // over the top of the transfer record, then persist it + transfer = transfer.WithSoulseekTransfer(completedTransfer); + + // todo: broadcast to signalr hub + SynchronizedUpdate(transfer, cancellable: false); + + // move the file from incomplete to complete + var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); + + var finalFilename = Files.MoveFile( + sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + destinationDirectory: destinationDirectory, + overwrite: false, + deleteSourceDirectoryIfEmptyAfterMove: true); + + Log.Debug("Moved file to {Destination}", finalFilename); + + // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, + // and the file has been moved from the incomplete directory to the downloads directory + if (OptionsMonitor.CurrentValue.Relay.Enabled) + { + _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); + } + + EventBus.Raise(new DownloadFileCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + LocalFilename = finalFilename, + RemoteFilename = transfer.Filename, + Transfer = transfer, + }); + + // try to figure out if this file is the last of a directory, and if so, raise the associated + // event. this can be tricky because we want to be sure that this is the last file in this specific + // directory, excluding any pending downloads in a subdirectory. + var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); + var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); + var pendingDownloadsInDirectory = Client.Downloads + .Where(t => t.Username == transfer.Username) + .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); + + if (!pendingDownloadsInDirectory.Any()) + { + EventBus.Raise(new DownloadDirectoryCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + Username = transfer.Username, + LocalDirectoryName = destinationDirectory, + RemoteDirectoryName = remoteDirectoryName, + }); + } + + if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) + { + _ = FTP.UploadAsync(finalFilename); + } + + return transfer; + } + catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) + { + transfer.EndedAt = DateTime.UtcNow; + transfer.Exception = ex.Message; + transfer.State = TransferStates.Completed; + + transfer.State |= ex switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; + + // todo: broadcast + SynchronizedUpdate(transfer, cancellable: false); + + throw; + } + catch (Exception ex) + { + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); + + transfer.EndedAt = DateTime.UtcNow; + transfer.Exception = ex.Message; + transfer.State = TransferStates.Completed | TransferStates.Errored; + + // todo: broadcast + SynchronizedUpdate(transfer, cancellable: false); + + throw; + } + finally + { + try + { + Locks.TryRemove(lockName, out _); + Log.Debug("Released lock {LockName}", lockName); + + CancellationTokens.TryRemove(transfer.Id, out _); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to finalize download of {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); + throw; + } + } + } + /// /// Enqueues the requested list of . /// @@ -184,7 +468,7 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - public Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) + public Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) { if (string.IsNullOrEmpty(username)) { @@ -198,7 +482,7 @@ namespace slskd.Transfers.Downloads return EnqueueAsyncInternal(username, files); - async Task EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files) + async Task> EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files) { try { @@ -208,6 +492,7 @@ namespace slskd.Transfers.Downloads await Client.ConnectToUserAsync(username, invalidateCache: false); Log.Debug("Connection for user '{Username}' primed", username); + var transfers = new List(); var thrownExceptions = new List(); foreach (var file in files) @@ -460,6 +745,7 @@ namespace slskd.Transfers.Downloads } Log.Information("Successfully enqueued {Count} file(s) from user {Username}", files.Count(), username); + return transfers; } catch (Exception ex) { -- cgit v1.2.3 From 8e6bb172f5626dc8058b1b40934e1e5b84b01f37 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Oct 2025 19:03:50 -0500 Subject: minor tweaks --- src/slskd/Transfers/Uploads/UploadService.cs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index ee6185cc..8fa08cea 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -511,11 +511,21 @@ namespace slskd.Transfers.Uploads /// The operation context. public async Task EnqueueAsync(string username, string filename) { + if (string.IsNullOrEmpty(username)) + { + throw new ArgumentNullException(nameof(username), "Username is required"); + } + + if (string.IsNullOrEmpty(filename)) + { + throw new ArgumentNullException(nameof(filename), "Filename is required"); + } + var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}"; if (!Locks.TryAdd(lockName, true)) { - Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); + Log.Debug("Ignoring concurrent upload enqueue attempt; lock {LockName} already held", lockName); return null; } @@ -606,7 +616,7 @@ namespace slskd.Transfers.Uploads { record.Removed = true; context.Update(record); - Log.Debug("Marked existing upload record {Filename} to {Username} removed (id: {Id})", filename, username, record.Id); + Log.Debug("Marked existing upload record of {Filename} to {Username} removed (id: {Id})", filename, username, record.Id); } context.SaveChanges(); @@ -700,8 +710,10 @@ namespace slskd.Transfers.Uploads } finally { - Locks.TryRemove(lockName, out _); - Log.Debug("Released lock {LockName}", lockName); + if (Locks.TryRemove(lockName, out _)) + { + Log.Debug("Released lock {LockName}", lockName); + } } } -- cgit v1.2.3 From 5c5318b6f1f3aac1a0eda59090c89ad0dd27ca46 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 2 Oct 2025 19:04:43 -0500 Subject: add singular EnqueueAsync, simplify multiple variant --- src/slskd/Transfers/Downloads/DownloadService.cs | 434 ++++++++++------------- 1 file changed, 179 insertions(+), 255 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 72d762c0..bf501c33 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -61,6 +61,15 @@ namespace slskd.Transfers.Downloads /// Thrown when at least one of the requested files throws. Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + /// + /// Enqueues the specified from the specified . + /// + /// The username of remote user. + /// The remote filename to download. + /// The size of the file. + /// The operation context. + Task EnqueueAsync(string username, string filename, long size); + /// /// Downloads the specified enqueued from the remote user. /// @@ -456,303 +465,218 @@ namespace slskd.Transfers.Downloads } /// - /// Enqueues the requested list of . + /// Enqueues the specified from the specified . /// - /// - /// If one file in the specified collection fails, the rest will continue. An will be - /// thrown after all files are dispositioned if any throws. - /// - /// The username of the remote user. - /// The list of files to enqueue. + /// The username of remote user. + /// The remote filename to download. + /// The size of the file. /// The operation context. - /// Thrown when the username is null or an empty string. - /// Thrown when no files are requested. - /// Thrown when at least one of the requested files throws. - public Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) + public Task EnqueueAsync(string username, string filename, long size) { if (string.IsNullOrEmpty(username)) { - throw new ArgumentException("Username is required", nameof(username)); + throw new ArgumentNullException(nameof(username), "Username is required"); } - if (!files.Any()) + if (string.IsNullOrEmpty(filename)) + { + throw new ArgumentNullException(nameof(filename), "Filename is required"); + } + + if (size <= 0) { - throw new ArgumentException("At least one file is require", nameof(files)); + throw new ArgumentOutOfRangeException(nameof(size), "Size must be greater than zero"); } - return EnqueueAsyncInternal(username, files); + var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}"; - async Task> EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files) + if (!Locks.TryAdd(lockName, true)) { - try - { - Log.Information("Downloading {Count} files from user {Username}", files.Count(), username); + Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} a;ready held", lockName); + return null; + } - Log.Debug("Priming connection for user {Username}", username); - await Client.ConnectToUserAsync(username, invalidateCache: false); - Log.Debug("Connection for user '{Username}' primed", username); + Guid id = Guid.NewGuid(); - var transfers = new List(); - var thrownExceptions = new List(); + try + { + Log.Debug("Acquired lock {LockName}", lockName); - foreach (var file in files) - { - Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username); + Log.Information("Download of {Filename} from {Username} requested", filename, username); - var id = Guid.NewGuid(); + using var context = ContextFactory.CreateDbContext(); - var transfer = new Transfer() - { - Id = id, - Username = username, - Direction = TransferDirection.Download, - Filename = file.Filename, - Size = file.Size, - StartOffset = 0, - RequestedAt = DateTime.UtcNow, - }; - - // persist the transfer to the database so we have a record that it was attempted - AddOrSupersede(transfer); - - var cts = new CancellationTokenSource(); - CancellationTokens.TryAdd(id, cts); - - var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - // this task does the actual work of downloading the file. if the transfer is successfully queued - // remotely, the waitUntilEnqueue completion source is set, which yields execution to below so we can - // return and let the caller know. - var downloadTask = Task.Run(async () => - { - using var rateLimiter = new RateLimiter(250, flushOnDispose: true); - var syncRoot = new SemaphoreSlim(1, 1); + /* + first, get all past downloads from this user for this filename + */ + var existingRecords = context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => t.Username == username) + .Where(t => t.Filename == filename) + .AsNoTracking() + .ToList(); - void SynchronizedUpdate(Transfer transfer, bool cancellable = true) - { - syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); + var existingInProgressRecords = existingRecords + .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) + .ToList(); - try - { - Update(transfer); - } - finally - { - syncRoot.Release(); - } - } + /* + if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already + an existing transfer record covering this file, and we're already enqueued. nothing more to do! + */ + if (existingInProgressRecords.Count != 0) + { + Log.Information("Download of {Filename} from {Username} is already queued or is in progress (ids: {Ids})", filename, username, string.Join(", ", existingInProgressRecords.Select(t => t.Id))); + return null; + } - try - { - var topts = new TransferOptions( - disposeOutputStreamOnCompletion: true, - stateChanged: (args) => - { - Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, args.PreviousState, args.Transfer.State); - - if (Application.IsShuttingDown) - { - Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", file.Filename, username); - return; - } - - transfer = transfer.WithSoulseekTransfer(args.Transfer); - - if ((args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) || args.Transfer.State == TransferStates.Initializing) - { - transfer.EnqueuedAt = DateTime.UtcNow; - waitUntilEnqueue.TrySetResult(true); - } - - SynchronizedUpdate(transfer); - }, - progressUpdated: (args) => rateLimiter.Invoke(() => - { - // don't do anything unless the `transfer` within the outer scope is in the - // InProgress state; this will help prevent out-of-band updates that are sometimes - // being made after the transfer is completed, causing them to appear 'stuck' - if (transfer.State == TransferStates.InProgress) - { - syncRoot.Wait(cts.Token); - - try - { - // check again to see if the state changed while we were waiting to obtain the lock - if (transfer.State == TransferStates.InProgress) - { - // update only the properties that we expect to change between progress updates - // this helps prevent this update from 'stepping' on other updates - transfer.BytesTransferred = args.Transfer.BytesTransferred; - transfer.AverageSpeed = args.Transfer.AverageSpeed; - - using var context = ContextFactory.CreateDbContext(); - - context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter - .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); - } - } - finally - { - syncRoot.Release(); - } - } - })); - - var completedTransfer = await Client.DownloadAsync( - username: username, - remoteFilename: file.Filename, - outputStreamFactory: () => Task.FromResult( - Files.CreateFile( - filename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - options: new CreateFileOptions - { - Access = System.IO.FileAccess.Write, - Mode = System.IO.FileMode.Create, // overwrites file if it exists - Share = System.IO.FileShare.None, // exclusive access for the duration of the download - UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) - ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() - : null, - })), - size: file.Size, - startOffset: 0, - token: null, - cancellationToken: cts.Token, - options: topts); - - // explicitly dispose the rate limiter to prevent updates from it - // beyond this point, which may overwrite the final state - rateLimiter.Dispose(); - - transfer = transfer.WithSoulseekTransfer(completedTransfer); - - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); - - var destinationDirectory = System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); - - var finalFilename = Files.MoveFile( - sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - destinationDirectory: destinationDirectory, - overwrite: false, - deleteSourceDirectoryIfEmptyAfterMove: true); - - Log.Debug("Moved file to {Destination}", finalFilename); - - // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, - // and the file has been moved from the incomplete directory to the downloads directory - if (OptionsMonitor.CurrentValue.Relay.Enabled) - { - _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); - } + /* + check the tracked download dictionary in Soulseek.NET to see if it knows about this already + it shouldn't, if the slskd database doesn't. but things could get desynced + */ + if (Client.Downloads.Any(u => u.Username == username && u.Filename == filename)) + { + throw new DuplicateTransferException("A duplicate download of the same file from the same user is already registered"); + } - EventBus.Raise(new DownloadFileCompleteEvent - { - Timestamp = transfer.EndedAt.Value, - LocalFilename = finalFilename, - RemoteFilename = transfer.Filename, - Transfer = transfer, - }); - - // try to figure out if this file is the last of a directory, and if so, raise the associated - // event. this can be tricky because we want to be sure that this is the last file in this specific - // directory, excluding any pending downloads in a subdirectory. - var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); - var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); - var pendingDownloadsInDirectory = Client.Downloads - .Where(t => t.Username == transfer.Username) - .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); - - if (!pendingDownloadsInDirectory.Any()) - { - EventBus.Raise(new DownloadDirectoryCompleteEvent - { - Timestamp = transfer.EndedAt.Value, - Username = transfer.Username, - LocalDirectoryName = destinationDirectory, - RemoteDirectoryName = remoteDirectoryName, - }); - } + /* + we're cleared to enqueue! create a new transfer record, and automatically mark any existing records + we found as 'removed' to clean up the UI + */ + var transfer = new Transfer() + { + Id = id, + Username = username, + Direction = TransferDirection.Download, + Filename = filename, // important! use the remote filename + Size = size, + StartOffset = 0, // todo: maybe implement resumeable downloads? + RequestedAt = DateTime.UtcNow, + State = TransferStates.Queued | TransferStates.Locally, + }; - if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) - { - _ = FTP.UploadAsync(finalFilename); - } - } - catch (OperationCanceledException ex) - { - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Cancelled; + context.Add(transfer); - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); + foreach (var record in existingRecords.Where(t => !t.Removed)) + { + record.Removed = true; + context.Update(record); + Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", filename, username, record.Id); + } - throw; - } - catch (Exception ex) - { - Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", file.Filename, username, ex.Message); + context.SaveChanges(); - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Errored; + Log.Information("Successfully enqueued download of {Filename} from {Username} (id: {Id})", filename, username, id); - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); + /* + schedule the download immediately - throw; - } - finally - { - CancellationTokens.TryRemove(id, out _); - } - }); + Task.Run can fail due to thread pool exhaustion or OOM, and this *SHOULD* throw up the chain and + fail the enqueue request + */ + _ = Task.Run(() => DownloadAsync(transfer)).ContinueWith(task => + { + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for download of {Filename} from {Username} completed successfully", filename, username); + return; + } - // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or - // the downloadTask throws due to an error prior to successfully queueing. - var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask); + /* + things that can cause us to arrive here: - // if the download task completed first it is a very good indication that it threw an exception or was - // otherwise not successful. try to figure out why and update everything to reflect the failure, but - // continue processing the batch - if (task == downloadTask) - { - Exception ex = downloadTask.Exception; + * transfer record deleted somehow + * transfer record updated so that it's no longer in Queued | Locally + * Soulseek.NET already tracking an identical download (slskd <> Soulseek.NET desync) + */ + Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", filename, username, task.Exception.Message); - // todo: figure out why this needs to be unwrapped just for this one case. is this always an aggregate? - if (ex is AggregateException aggEx) - { - var rejected = aggEx.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); - if (rejected.Any()) - { - ex = rejected.First(); - } - } + try + { + var transfer = Find(t => t.Id == id); - Log.Error("Failed to download {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); - thrownExceptions.Add(ex); - } - else + if (transfer is not null) { - Log.Debug("Successfully enqueued {Filename} from user {Username}", file.Filename, username); + transfer.EndedAt ??= DateTime.UtcNow; + transfer.Exception ??= task.Exception.Message; + transfer.State = TransferStates.Completed | transfer.State; + + Update(transfer); } } - - if (thrownExceptions.Any()) + catch (Exception ex) { - throw new AggregateException(thrownExceptions); + Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", id, ex.Message); + throw; } + }); + + return Task.FromResult(transfer); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", filename, username, ex.Message); + + try + { + var transfer = Find(t => t.Id == id); - Log.Information("Successfully enqueued {Count} file(s) from user {Username}", files.Count(), username); - return transfers; + if (transfer is not null) + { + transfer.EndedAt ??= DateTime.UtcNow; + transfer.Exception ??= ex.Message; + transfer.State = TransferStates.Completed | transfer.State; + + Update(transfer); + } } - catch (Exception ex) + catch (Exception innerEx) { - Log.Error(ex, "Failed to download one or more files from user {Username}: {Message}", username, ex.Message); + Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", id, innerEx.Message); throw; } + + throw; } + finally + { + if (Locks.TryRemove(lockName, out _)) + { + Log.Debug("Released lock {LockName}", lockName); + } + } + } + + /// + /// Enqueues the requested list of . + /// + /// + /// If one file in the specified collection fails, the rest will continue. An will be + /// thrown after all files are dispositioned if any throws. + /// + /// The username of the remote user. + /// The list of files to enqueue. + /// The operation context. + /// Thrown when the username is null or an empty string. + /// Thrown when no files are requested. + /// Thrown when at least one of the requested files throws. + public async Task> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) + { + if (string.IsNullOrEmpty(username)) + { + throw new ArgumentException("Username is required", nameof(username)); + } + + if (!files.Any()) + { + throw new ArgumentException("At least one file is required", nameof(files)); + } + + var tasks = files.Select(file => EnqueueAsync(username, file.Filename, file.Size)); + + var transfers = await Task.WhenAll(tasks); + + return transfers.ToList(); } /// -- cgit v1.2.3 From efcc4bc19ec53b464304d1afa9eeb2d4c181c9c3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 3 Oct 2025 19:07:27 -0500 Subject: Update src/slskd/Transfers/Downloads/DownloadService.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bf501c33..3a8e52e9 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -492,7 +492,7 @@ namespace slskd.Transfers.Downloads if (!Locks.TryAdd(lockName, true)) { - Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} a;ready held", lockName); + Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName); return null; } -- cgit v1.2.3 From c8e43f739b967470900072530ca7138c3b18b106 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 4 Oct 2025 17:58:00 -0500 Subject: move checks inside try/catch --- src/slskd/Transfers/Downloads/DownloadService.cs | 50 +++++++-------- src/slskd/Transfers/Uploads/UploadService.cs | 78 ++++++++++++------------ 2 files changed, 64 insertions(+), 64 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bf501c33..eafbf388 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -213,31 +213,6 @@ namespace slskd.Transfers.Downloads Log.Debug("Acquired lock {LockName}", lockName); - /* - fetch an updated copy of the transfer record from the database; now that we are locked, we *should* - have exclusive access to this record - - we're not using DbContext and tracked changes here because we don't want to hold a connection - open for the duration of the download - */ - transfer = Find(t => t.Id == transfer.Id) - ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); - - if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) - { - throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); - } - - /* - Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; - check that list to see if there's already an instance of this download in it, just in case we've gotten - out of sync somehow - */ - if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) - { - throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); - } - var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); @@ -265,6 +240,31 @@ namespace slskd.Transfers.Downloads */ try { + /* + fetch an updated copy of the transfer record from the database; now that we are locked, we *should* + have exclusive access to this record + + we're not using DbContext and tracked changes here because we don't want to hold a connection + open for the duration of the download + */ + transfer = Find(t => t.Id == transfer.Id) + ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + + /* + Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; + check that list to see if there's already an instance of this download in it, just in case we've gotten + out of sync somehow + */ + if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) + { + throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); + } + Log.Information("Initializing download of {Filename} from {Username}", transfer.Filename, transfer.Username); using var rateLimiter = new RateLimiter(250, flushOnDispose: true); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 8fa08cea..bd167a57 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -230,45 +230,6 @@ namespace slskd.Transfers.Uploads Log.Debug("Acquired lock {LockName}", lockName); - /* - fetch an updated copy of the transfer record from the database; now that we are locked, we *should* - have exclusive access to this record - - we're not using DbContext and tracked changes here because we don't want to hold a connection - open for the duration of the upload - */ - transfer = Find(t => t.Id == transfer.Id) - ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); - - if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) - { - throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); - } - - /* - Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; - check that list to see if there's already an instance of this upload in it, just in case we've gotten - out of sync somehow - */ - if (Client.Uploads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) - { - throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered"); - } - - // users with uploads must be watched so that we can keep informed of their online status, privileges, and - // statistics. this is so that we can accurately determine their effective group. - try - { - if (!Users.IsWatched(transfer.Username)) - { - await Users.WatchAsync(transfer.Username); - } - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to watch user {Username}", transfer.Username); - } - var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); @@ -300,6 +261,45 @@ namespace slskd.Transfers.Uploads */ try { + /* + fetch an updated copy of the transfer record from the database; now that we are locked, we *should* + have exclusive access to this record + + we're not using DbContext and tracked changes here because we don't want to hold a connection + open for the duration of the upload + */ + transfer = Find(t => t.Id == transfer.Id) + ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + + /* + Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; + check that list to see if there's already an instance of this upload in it, just in case we've gotten + out of sync somehow + */ + if (Client.Uploads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) + { + throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered"); + } + + // users with uploads must be watched so that we can keep informed of their online status, privileges, and + // statistics. this is so that we can accurately determine their effective group. + try + { + if (!Users.IsWatched(transfer.Username)) + { + await Users.WatchAsync(transfer.Username); + } + } + catch (Exception ex) + { + Log.Warning(ex, "Failed to watch user {Username}", transfer.Username); + } + Log.Information("Initializing upload of {Filename} to {Username}", transfer.Filename, transfer.Username); // locate the file on disk. we checked this once already when enqueueing, but it may have moved since -- cgit v1.2.3 From 845f6406c079d082e4ea9683b3c1966698967c90 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 4 Oct 2025 17:59:22 -0500 Subject: delay lock acquisition --- src/slskd/Transfers/Downloads/DownloadService.cs | 20 ++++++++++---------- src/slskd/Transfers/Uploads/UploadService.cs | 19 ++++++++++--------- 2 files changed, 20 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index eafbf388..be9278b2 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -203,16 +203,6 @@ namespace slskd.Transfers.Downloads /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. public async Task DownloadAsync(Transfer transfer) { - var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; - - if (!Locks.TryAdd(lockName, true)) - { - Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); - return null; - } - - Log.Debug("Acquired lock {LockName}", lockName); - var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); @@ -230,6 +220,14 @@ namespace slskd.Transfers.Downloads } } + var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; + + if (!Locks.TryAdd(lockName, true)) + { + Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); + return null; + } + /* from this point forward, any exit from this method MUST result in an update to the Transfer record in the database that sets EndedAt and ensures that the State property includes the Completed flag @@ -240,6 +238,8 @@ namespace slskd.Transfers.Downloads */ try { + Log.Debug("Acquired lock {LockName}", lockName); + /* fetch an updated copy of the transfer record from the database; now that we are locked, we *should* have exclusive access to this record diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index bd167a57..89700eba 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -220,15 +220,6 @@ namespace slskd.Transfers.Uploads /// Thrown if the specified file can't be found on disk. public async Task UploadAsync(Transfer transfer) { - var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}"; - - if (!Locks.TryAdd(lockName, true)) - { - Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); - return null; - } - - Log.Debug("Acquired lock {LockName}", lockName); var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); @@ -251,6 +242,14 @@ namespace slskd.Transfers.Uploads string localFilename = default; long localFileLength = default; + var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}"; + + if (!Locks.TryAdd(lockName, true)) + { + Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); + return null; + } + /* from this point forward, any exit from this method MUST result in an update to the Transfer record in the database that sets EndedAt and ensures that the State property includes the Completed flag @@ -261,6 +260,8 @@ namespace slskd.Transfers.Uploads */ try { + Log.Debug("Acquired lock {LockName}", lockName); + /* fetch an updated copy of the transfer record from the database; now that we are locked, we *should* have exclusive access to this record -- cgit v1.2.3