diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-10-02 19:04:43 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-10-02 19:04:43 -0500 |
| commit | 5c5318b6f1f3aac1a0eda59090c89ad0dd27ca46 (patch) | |
| tree | 3d523048e83260d2132b34818e3d64e742a5afd6 /src | |
| parent | 8e6bb172f5626dc8058b1b40934e1e5b84b01f37 (diff) | |
| download | slskd-5c5318b6f1f3aac1a0eda59090c89ad0dd27ca46.tar.gz | |
add singular EnqueueAsync, simplify multiple variant
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 434 |
1 files changed, 179 insertions, 255 deletions
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 @@ -62,6 +62,15 @@ namespace slskd.Transfers.Downloads Task<List<Transfer>> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); /// <summary> + /// Enqueues the specified <paramref name="filename"/> from the specified <paramref name="username"/>. + /// </summary> + /// <param name="username">The username of remote user.</param> + /// <param name="filename">The remote filename to download.</param> + /// <param name="size">The size of the file.</param> + /// <returns>The operation context.</returns> + Task<Transfer> EnqueueAsync(string username, string filename, long size); + + /// <summary> /// Downloads the specified enqueued <paramref name="transfer"/> from the remote user. /// </summary> /// <param name="transfer">The Transfer to download.</param> @@ -456,303 +465,218 @@ namespace slskd.Transfers.Downloads } /// <summary> - /// Enqueues the requested list of <paramref name="files"/>. + /// Enqueues the specified <paramref name="filename"/> from the specified <paramref name="username"/>. /// </summary> - /// <remarks> - /// If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be - /// thrown after all files are dispositioned if any throws. - /// </remarks> - /// <param name="username">The username of the remote user.</param> - /// <param name="files">The list of files to enqueue.</param> + /// <param name="username">The username of remote user.</param> + /// <param name="filename">The remote filename to download.</param> + /// <param name="size">The size of the file.</param> /// <returns>The operation context.</returns> - /// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception> - /// <exception cref="ArgumentException">Thrown when no files are requested.</exception> - /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception> - public Task<List<Transfer>> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) + public Task<Transfer> 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<List<Transfer>> 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<Transfer>(); - var thrownExceptions = new List<Exception>(); + 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<bool>(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<Exception>(); - 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); + } + } + } + + /// <summary> + /// Enqueues the requested list of <paramref name="files"/>. + /// </summary> + /// <remarks> + /// If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be + /// thrown after all files are dispositioned if any throws. + /// </remarks> + /// <param name="username">The username of the remote user.</param> + /// <param name="files">The list of files to enqueue.</param> + /// <returns>The operation context.</returns> + /// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception> + /// <exception cref="ArgumentException">Thrown when no files are requested.</exception> + /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception> + public async Task<List<Transfer>> 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(); } /// <summary> |
