diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 704 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 167 |
2 files changed, 550 insertions, 321 deletions
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index ef8e84bf..bd271a89 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -59,7 +59,27 @@ namespace slskd.Transfers.Downloads /// <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> - Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + 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> + /// <returns>The operation context.</returns> + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> + /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception> + /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception> + /// <exception cref="DuplicateTransferException">Thrown if a download matching the username and filename is already tracked by Soulseek.NET.</exception> + Task<Transfer> DownloadAsync(Transfer transfer); /// <summary> /// Finds a single download matching the specified <paramref name="expression"/>. @@ -144,6 +164,7 @@ namespace slskd.Transfers.Downloads private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } private EventBus EventBus { get; } + private ConcurrentDictionary<string, bool> Locks { get; } = new(); /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. @@ -172,301 +193,490 @@ namespace slskd.Transfers.Downloads } /// <summary> - /// Enqueues the requested list of <paramref name="files"/>. + /// Downloads the specified enqueued <paramref name="transfer"/> from the remote user. /// </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="transfer">The Transfer to download.</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 EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) + /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> + /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception> + /// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception> + /// <exception cref="DuplicateTransferException">Thrown if a download matching the username and filename is already tracked by Soulseek.NET.</exception> + public async Task<Transfer> DownloadAsync(Transfer transfer) { - if (string.IsNullOrEmpty(username)) + var cts = new CancellationTokenSource(); + var syncRoot = new SemaphoreSlim(1, 1); + + void SynchronizedUpdate(Transfer transfer, bool cancellable = true) { - throw new ArgumentException("Username is required", nameof(username)); + syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); + + try + { + Update(transfer); + } + finally + { + syncRoot.Release(); + } } - if (!files.Any()) + var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; + + if (!Locks.TryAdd(lockName, true)) { - throw new ArgumentException("At least one file is require", nameof(files)); + Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); + return null; } - return EnqueueAsyncInternal(username, 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 - async Task EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files) + 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 { - 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 + + 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)) { - Log.Information("Downloading {Count} files from user {Username}", files.Count(), username); + throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } - Log.Debug("Priming connection for user {Username}", username); - await Client.ConnectToUserAsync(username, invalidateCache: false); - Log.Debug("Connection for user '{Username}' primed", username); + /* + 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 thrownExceptions = new List<Exception>(); + Log.Information("Initializing download of {Filename} from {Username}", transfer.Filename, transfer.Username); - foreach (var file in files) - { - Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username); + using var rateLimiter = new RateLimiter(250, flushOnDispose: true); - var id = Guid.NewGuid(); + 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); - 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 () => + // 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) { - using var rateLimiter = new RateLimiter(250, flushOnDispose: true); - var syncRoot = new SemaphoreSlim(1, 1); + Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); + return; + } - void SynchronizedUpdate(Transfer transfer, bool cancellable = true) - { - syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); + transfer = transfer.WithSoulseekTransfer(args.Transfer); - try - { - Update(transfer); - } - finally - { - syncRoot.Release(); - } - } + // 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 { - 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) + // check again to see if the state changed while we were waiting to obtain the lock + if (transfer.State == TransferStates.InProgress) { - _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); - } + // 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; - 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, - }); - } + using var context = ContextFactory.CreateDbContext(); - if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) - { - _ = FTP.UploadAsync(finalFilename); + context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); } } - catch (OperationCanceledException ex) + finally { - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Cancelled; - - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); - - throw; + syncRoot.Release(); } - catch (Exception ex) + } + }), + 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 { - Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", file.Filename, username, ex.Message); + 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); + } - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Errored; + 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, + }); + } - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); + if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) + { + _ = FTP.UploadAsync(finalFilename); + } - throw; - } - finally - { - CancellationTokens.TryRemove(id, out _); - } - }); + return transfer; + } + catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) + { + transfer.EndedAt = DateTime.UtcNow; + transfer.Exception = ex.Message; + transfer.State = TransferStates.Completed; - // 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); + transfer.State |= ex switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; - // 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; + // todo: broadcast + SynchronizedUpdate(transfer, cancellable: false); - // 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(); - } - } + throw; + } + catch (Exception ex) + { + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - Log.Error("Failed to download {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); - thrownExceptions.Add(ex); - } - else + 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; + } + } + } + + /// <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> + public Task<Transfer> EnqueueAsync(string username, string filename, long size) + { + if (string.IsNullOrEmpty(username)) + { + throw new ArgumentNullException(nameof(username), "Username is required"); + } + + if (string.IsNullOrEmpty(filename)) + { + throw new ArgumentNullException(nameof(filename), "Filename is required"); + } + + if (size <= 0) + { + throw new ArgumentOutOfRangeException(nameof(size), "Size must be greater than zero"); + } + + var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}"; + + if (!Locks.TryAdd(lockName, true)) + { + Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName); + return null; + } + + Guid id = Guid.NewGuid(); + + try + { + Log.Debug("Acquired lock {LockName}", lockName); + + Log.Information("Download of {Filename} from {Username} requested", filename, username); + + using var context = ContextFactory.CreateDbContext(); + + /* + first, get all past downloads from this user for this filename + */ + var existingRecords = context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => t.Username == username) + .Where(t => t.Filename == filename) + .AsNoTracking() + .ToList(); + + var existingInProgressRecords = existingRecords + .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) + .ToList(); + + /* + if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already + an existing transfer record covering this file, and we're already enqueued. nothing more to do! + */ + if (existingInProgressRecords.Count != 0) + { + Log.Information("Download of {Filename} from {Username} is already queued or is in progress (ids: {Ids})", filename, username, string.Join(", ", existingInProgressRecords.Select(t => t.Id))); + return null; + } + + /* + check the tracked download dictionary in Soulseek.NET to see if it knows about this already + it shouldn't, if the slskd database doesn't. but things could get desynced + */ + if (Client.Downloads.Any(u => u.Username == username && u.Filename == filename)) + { + throw new DuplicateTransferException("A duplicate download of the same file from the same user is already registered"); + } + + /* + we're cleared to enqueue! create a new transfer record, and automatically mark any existing records + we found as 'removed' to clean up the UI + */ + var transfer = new Transfer() + { + Id = id, + Username = username, + Direction = TransferDirection.Download, + Filename = filename, // important! use the remote filename + Size = size, + StartOffset = 0, // todo: maybe implement resumeable downloads? + RequestedAt = DateTime.UtcNow, + State = TransferStates.Queued | TransferStates.Locally, + }; + + context.Add(transfer); + + foreach (var record in existingRecords.Where(t => !t.Removed)) + { + record.Removed = true; + context.Update(record); + Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", filename, username, record.Id); + } + + context.SaveChanges(); + + Log.Information("Successfully enqueued download of {Filename} from {Username} (id: {Id})", filename, username, id); + + /* + schedule the download immediately + + 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; + } + + /* + things that can cause us to arrive here: + + * transfer record deleted somehow + * transfer record updated so that it's no longer in Queued | Locally + * Soulseek.NET already tracking an identical download (slskd <> Soulseek.NET desync) + */ + Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", filename, username, task.Exception.Message); + + try + { + var transfer = Find(t => t.Id == id); + + if (transfer is not null) { - 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); + + if (transfer is not null) + { + transfer.EndedAt ??= DateTime.UtcNow; + transfer.Exception ??= ex.Message; + transfer.State = TransferStates.Completed | transfer.State; - Log.Information("Successfully enqueued {Count} file(s) from user {Username}", files.Count(), username); + 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> diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 6db9f6a5..89700eba 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -69,7 +69,7 @@ namespace slskd.Transfers.Uploads /// <summary> /// Uploads the specified enqueued <paramref name="transfer"/> to the requesting user. /// </summary> - /// <param name="transfer">The transfer to upload.</param> + /// <param name="transfer">The Transfer to upload.</param> /// <returns>The operation context.</returns> /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception> @@ -211,7 +211,7 @@ namespace slskd.Transfers.Uploads /// <summary> /// Uploads the specified enqueued <paramref name="transfer"/> to the requesting user. /// </summary> - /// <param name="transfer">The transfer to upload.</param> + /// <param name="transfer">The Transfer to upload.</param> /// <returns>The operation context.</returns> /// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception> /// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception> @@ -220,54 +220,6 @@ namespace slskd.Transfers.Uploads /// <exception cref="NotFoundException">Thrown if the specified file can't be found on disk.</exception> public async Task<Transfer> 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; - } - - Transfer t = transfer; - - /* - 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 - */ - t = Find(t => t.Id == transfer.Id) - ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); - - if (t.State != (TransferStates.Queued | TransferStates.Locally)) - { - throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {t.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 == t.Username && u.Filename == t.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(t.Username)) - { - await Users.WatchAsync(t.Username); - } - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to watch user {Username}", t.Username); - } var cts = new CancellationTokenSource(); var syncRoot = new SemaphoreSlim(1, 1); @@ -290,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 @@ -301,24 +261,64 @@ namespace slskd.Transfers.Uploads try { Log.Debug("Acquired lock {LockName}", lockName); - Log.Information("Initializing upload {Filename} to {Username}", t.Filename, t.Username); + + /* + 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 // 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 +367,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 +379,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 +398,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 +423,7 @@ namespace slskd.Transfers.Uploads { Timestamp = transfer.EndedAt.Value, LocalFilename = localFilename, - RemoteFilename = t.Filename, + RemoteFilename = transfer.Filename, Transfer = transfer, }); @@ -439,11 +439,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 +459,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 +476,7 @@ namespace slskd.Transfers.Uploads { try { - Relay.TryCloseFileStream(host, id: t.Id); + Relay.TryCloseFileStream(host, id: transfer.Id); } catch { @@ -482,16 +489,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; } } @@ -505,11 +512,21 @@ namespace slskd.Transfers.Uploads /// <returns>The operation context.</returns> public async Task<Transfer> 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; } @@ -600,7 +617,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(); @@ -694,8 +711,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); + } } } |
