From 2827f5359acf37b3730c8ba34571d462cd484ce7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 20 Oct 2025 20:24:35 -0500 Subject: make DownloadAsync private --- src/slskd/Transfers/Downloads/DownloadService.cs | 1237 +++++++++++----------- 1 file changed, 613 insertions(+), 624 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 46809912..29ae1e34 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -175,487 +175,179 @@ namespace slskd.Transfers.Downloads } /// - /// Downloads the specified enqueued from the remote user. + /// Enqueues the requested list of . /// - /// The Transfer to download. - /// An optional delegate to invoke the transfer state changes. + /// The username of the remote user. + /// The list of files to enqueue. /// The token to monitor for cancellation. /// The operation context. - /// Thrown if the specified Transfer is null. - /// Thrown if the specified Transfer ID can't be found in the database. - /// Thrown if the specified Transfer is not in the Queued | Locally state. - /// Thrown if a download matching the username and filename is already tracked by Soulseek.NET. - public async Task DownloadAsync(Transfer transfer, Action stateChanged = null, CancellationToken cancellationToken = default) + /// Thrown when the username is null or an empty string. + /// Thrown when no files are requested. + /// Thrown when at least one of the requested files throws. + public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) { - if (transfer is null) + if (string.IsNullOrEmpty(username)) { - throw new ArgumentNullException(nameof(transfer), "A valid, enqueued Transfer is required"); + throw new ArgumentException("Username is required", nameof(username)); } - if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + if (!files.Any()) { - throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + throw new ArgumentException("At least one file is required", nameof(files)); } - var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - var syncRoot = new SemaphoreSlim(1, 1); + if (files.Count() != files.Distinct().Count()) + { + throw new ArgumentException("Two or more files in request are duplicated", nameof(files)); + } - var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; + IPEndPoint endpoint; - if (!Locks.TryAdd(lockName, true)) + Log.Information("Requested enqueue of {Count} files from user {Username}", files.Count(), username); + + try { - Log.Debug("Download attempt failed; lock {LockName} already held", lockName); - throw new DuplicateTransferException("A duplicate download of the same file to the same user is already in progress"); + // get the user's ip and port. this will throw if they are offline. + endpoint = await Client.GetUserEndPointAsync(username, cancellationToken); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue {Count} files from {Username}: {Message}", files.Count(), username, ex.Message); + throw; } - /* - 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 + // prime the cache for this user, to 1) make sure we can connect, and 2) avoid needing to race for it in the loop + try + { + Log.Debug("Priming message connection to {Username}", username); + await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message); + throw; + } - failure to do so means records will get "stuck" in the database/on the UI + List acquiredLocks = []; + List enqueued = []; + List failed = []; - additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot - */ try { - Log.Debug("Acquired lock {LockName}", lockName); + using var context = ContextFactory.CreateDbContext(); /* - fetch an updated copy of the transfer record from the database; now that we are locked, we *should* - have exclusive access to this record - - we're not using DbContext and tracked changes here because we don't want to hold a connection - open for the duration of the download + get all past downloads from this user for this filename */ - transfer = Find(t => t.Id == transfer.Id) - ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + var existingRecords = context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => t.Username == username) + .AsNoTracking() + .ToList(); - if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) - { - throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); - } + var existingInProgressRecords = existingRecords + .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) + .ToList(); /* - Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; - check that list to see if there's already an instance of this download in it, just in case we've gotten - out of sync somehow + first, check inputs and do an _exhaustive_ check for all of the files provided, separating files out + into good/bad + + acquire locks for each, and track them so we can release them later (in the finally block) */ - if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) + foreach (var file in files) { - throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); - } + cancellationToken.ThrowIfCancellationRequested(); - using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); + var transfer = new Transfer() + { + Id = Guid.NewGuid(), + Username = username, + Direction = TransferDirection.Download, + Filename = file.Filename, // important! use the remote filename + Size = file.Size, + StartOffset = 0, // todo: maybe implement resumeable downloads? + RequestedAt = DateTime.UtcNow, + State = TransferStates.Queued | TransferStates.Locally, + }; - var topts = new TransferOptions( - stateChanged: (args) => + var lockName = $"{nameof(EnqueueAsync)}:{username}:{file.Filename}"; + + if (!Locks.TryAdd(lockName, true)) { - try - { - Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", transfer.Filename, transfer.Username, args.PreviousState, args.Transfer.State); + Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName); + transfer.Exception = "A download for this file from this user is already underway"; + transfer.State = TransferStates.Aborted | TransferStates.Completed; + failed.Add(transfer); + continue; + } - // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions; - // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup - if (Application.IsShuttingDown) - { - Log.Debug("Download update of {Filename} from {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); - return; - } + try + { + acquiredLocks.Add(lockName); + Log.Debug("Acquired lock {LockName}", lockName); - transfer = transfer.WithSoulseekTransfer(args.Transfer); + Log.Debug("Checking whether download of {Filename} from {Username} is already in progress", file.Filename, username); - // we don't know when the download is actually enqueued (remotely) until it switches into that state - // when it is enqueued locally is irrelevant, due to internal throttling etc - if (args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) - { - transfer.EnqueuedAt ??= DateTime.UtcNow; - } + /* + if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already + an existing transfer record covering this file, and we're already enqueued. nothing more to do! - // todo: broadcast - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); - } - finally + check the tracked download dictionary in Soulseek.NET to see if it knows about this already + it shouldn't, if the slskd database doesn't. but things could get desynced + */ + if (existingInProgressRecords.Count != 0 || Client.Downloads.Any(u => u.Username == username && u.Filename == file.Filename)) { - stateChanged?.Invoke(transfer); + Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName); + transfer.Exception = "A download for this file from this user is already underway"; + transfer.State = TransferStates.Aborted | TransferStates.Completed; + failed.Add(transfer); + continue; } - }, - progressUpdated: (args) => rateLimiter.Invoke(() => - { - // don't do anything unless the `transfer` within the outer scope is in the - // InProgress state; this will help prevent out-of-band updates that are sometimes - // being made after the transfer is completed, causing them to appear 'stuck' - if (transfer.State == TransferStates.InProgress) - { - // don't wait for the semaphore; if a previous progress update is still hanging, don't make - // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems - // but the alternative is to continue to stack slow writes on top of one another - if (syncRoot.Wait(millisecondsTimeout: 0, cts.Token)) - { - try - { - // update only the properties that we expect to change between progress updates - // this helps prevent this update from 'stepping' on other updates - transfer.BytesTransferred = args.Transfer.BytesTransferred; - transfer.AverageSpeed = args.Transfer.AverageSpeed; - using var context = ContextFactory.CreateDbContext(); + /* + we've passed 3 different checks to ensure that this file is not already being downloaded, so + add it to the database and remove any existing (past) records of it from the UI + */ + context.Add(transfer); + Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id); - context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter - .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); - } - finally - { - syncRoot.Release(); - } - } - else - { - Log.Debug("Skipped progress update of {Filename} from {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size); - } + foreach (var record in existingRecords.Where(t => !t.Removed)) + { + record.Removed = true; + context.Update(record); + Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", file.Filename, username, record.Id); } - }), - disposeOutputStreamOnCompletion: true); - - // register the cancellation token - CancellationTokens.TryAdd(transfer.Id, cts); - System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) - ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() - : null; + enqueued.Add(transfer); - Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); + Log.Information("Successfully locally enqueued download of {Filename} from {Username}", file.Filename, username, transfer.Id); + } + catch (Exception ex) + { + // note: there's nothing to cancel or download yet, so any failure to execute the above is an error + Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); + transfer.Exception = ex.Message; + transfer.State = TransferStates.Errored | TransferStates.Completed; + failed.Add(transfer); + continue; + } + } - var completedTransfer = await Client.DownloadAsync( - username: transfer.Username, - remoteFilename: transfer.Filename, - outputStreamFactory: () => Task.FromResult( - Files.CreateFile( - filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - options: new CreateFileOptions - { - Access = System.IO.FileAccess.Write, - Mode = System.IO.FileMode.Create, // overwrites file if it exists - Share = System.IO.FileShare.None, // exclusive access for the duration of the download - UnixCreateMode = unixFileMode, - })), - size: transfer.Size, - startOffset: 0, - token: null, - cancellationToken: cts.Token, - options: topts); + var recordsCreated = context.SaveChanges(); - Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); + if (enqueued.Count == 0) + { + Log.Warning("None of the {Count} requested files from {Username} could be enqueued as they are already in progress", files.Count(), username); + return (enqueued, failed); + } - // 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(); + /* + the files are all now in the database in the Queued | Locally state. - // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state - // over the top of the transfer record, then persist it - transfer = transfer.WithSoulseekTransfer(completedTransfer); - - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - - Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); - - // move the file from incomplete to complete - var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); - - var finalFilename = Files.MoveFile( - sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - destinationDirectory: destinationDirectory, - unixFileMode: unixFileMode, - overwrite: false, - deleteSourceDirectoryIfEmptyAfterMove: true); - - Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); - - if (OptionsMonitor.CurrentValue.Relay.Enabled) - { - _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); - } - - try - { - // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, - // and the file has been moved from the incomplete directory to the downloads directory - Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username); - - EventBus.Raise(new DownloadFileCompleteEvent - { - Timestamp = transfer.EndedAt.Value, - LocalFilename = finalFilename, - RemoteFilename = transfer.Filename, - Transfer = transfer, - }); - - // try to figure out if this file is the last of a directory, and if so, raise the associated - // event. this can be tricky because we want to be sure that this is the last file in this specific - // directory, excluding any pending downloads in a subdirectory. - var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); - var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); - var pendingDownloadsInDirectory = Client.Downloads - .Where(t => t.Username == transfer.Username) - .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); - - if (!pendingDownloadsInDirectory.Any()) - { - EventBus.Raise(new DownloadDirectoryCompleteEvent - { - Timestamp = transfer.EndedAt.Value, - Username = transfer.Username, - LocalDirectoryName = destinationDirectory, - RemoteDirectoryName = remoteDirectoryName, - }); - } - - if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) - { - _ = FTP.UploadAsync(finalFilename); - } - - Log.Debug("Completed post-download logic for {Filename} from {Username} successfully", transfer.Filename, transfer.Username); - } - catch (Exception ex) - { - // log, but don't throw. the file ended up in the download folder and is complete; if we throw it looks like it didn't complete - // todo: add a visual indicator/new state for Transfers that indicate this state. or move all of this logic out and handle it via events - Log.Error(ex, "Failed to run post-download processes for {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); - } - - Log.Information("Download of {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); - - return transfer; - } - catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) - { - Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed; - - transfer.State |= ex switch - { - OperationCanceledException => TransferStates.Cancelled, - TimeoutException => TransferStates.TimedOut, - _ => TransferStates.Errored, - }; - - // todo: broadcast - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - - throw; - } - catch (Exception ex) - { - Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); - - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Errored; - - // todo: broadcast - SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - - throw; - } - finally - { - Log.Debug("Finalizing download of {Filename} from {Username}", transfer.Filename, transfer.Username); - - try - { - Locks.TryRemove(lockName, out _); - Log.Debug("Released lock {LockName}", lockName); - - CancellationTokens.TryRemove(transfer.Id, out _); - - Log.Debug("Finalization of download of {Filename} from {Username} completed", transfer.Filename, transfer.Username); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to finalize download of {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); - } - } - } - - /// - /// Enqueues the requested list of . - /// - /// The username of the remote user. - /// The list of files to enqueue. - /// The token to monitor for cancellation. - /// The operation context. - /// Thrown when the username is null or an empty string. - /// Thrown when no files are requested. - /// Thrown when at least one of the requested files throws. - public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) - { - if (string.IsNullOrEmpty(username)) - { - throw new ArgumentException("Username is required", nameof(username)); - } - - if (!files.Any()) - { - throw new ArgumentException("At least one file is required", nameof(files)); - } - - if (files.Count() != files.Distinct().Count()) - { - throw new ArgumentException("Two or more files in request are duplicated", nameof(files)); - } - - IPEndPoint endpoint; - - Log.Information("Requested enqueue of {Count} files from user {Username}", files.Count(), username); - - try - { - // get the user's ip and port. this will throw if they are offline. - endpoint = await Client.GetUserEndPointAsync(username, cancellationToken); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to enqueue {Count} files from {Username}: {Message}", files.Count(), username, ex.Message); - throw; - } - - // prime the cache for this user, to 1) make sure we can connect, and 2) avoid needing to race for it in the loop - try - { - Log.Debug("Priming message connection to {Username}", username); - await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message); - throw; - } - - List acquiredLocks = []; - List enqueued = []; - List failed = []; - - try - { - using var context = ContextFactory.CreateDbContext(); - - /* - get all past downloads from this user for this filename - */ - var existingRecords = context.Transfers - .Where(t => t.Direction == TransferDirection.Download) - .Where(t => t.Username == username) - .AsNoTracking() - .ToList(); - - var existingInProgressRecords = existingRecords - .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) - .ToList(); - - /* - first, check inputs and do an _exhaustive_ check for all of the files provided, separating files out - into good/bad - - acquire locks for each, and track them so we can release them later (in the finally block) - */ - foreach (var file in files) - { - cancellationToken.ThrowIfCancellationRequested(); - - var transfer = new Transfer() - { - Id = Guid.NewGuid(), - Username = username, - Direction = TransferDirection.Download, - Filename = file.Filename, // important! use the remote filename - Size = file.Size, - StartOffset = 0, // todo: maybe implement resumeable downloads? - RequestedAt = DateTime.UtcNow, - State = TransferStates.Queued | TransferStates.Locally, - }; - - var lockName = $"{nameof(EnqueueAsync)}:{username}:{file.Filename}"; - - if (!Locks.TryAdd(lockName, true)) - { - Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName); - transfer.Exception = "A download for this file from this user is already underway"; - transfer.State = TransferStates.Aborted | TransferStates.Completed; - failed.Add(transfer); - continue; - } - - try - { - acquiredLocks.Add(lockName); - Log.Debug("Acquired lock {LockName}", lockName); - - Log.Debug("Checking whether download of {Filename} from {Username} is already in progress", file.Filename, username); - - /* - if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already - an existing transfer record covering this file, and we're already enqueued. nothing more to do! - - check the tracked download dictionary in Soulseek.NET to see if it knows about this already - it shouldn't, if the slskd database doesn't. but things could get desynced - */ - if (existingInProgressRecords.Count != 0 || Client.Downloads.Any(u => u.Username == username && u.Filename == file.Filename)) - { - Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName); - transfer.Exception = "A download for this file from this user is already underway"; - transfer.State = TransferStates.Aborted | TransferStates.Completed; - failed.Add(transfer); - continue; - } - - /* - we've passed 3 different checks to ensure that this file is not already being downloaded, so - add it to the database and remove any existing (past) records of it from the UI - */ - context.Add(transfer); - Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id); - - foreach (var record in existingRecords.Where(t => !t.Removed)) - { - record.Removed = true; - context.Update(record); - Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", file.Filename, username, record.Id); - } - - enqueued.Add(transfer); - - Log.Information("Successfully locally enqueued download of {Filename} from {Username}", file.Filename, username, transfer.Id); - } - catch (Exception ex) - { - // note: there's nothing to cancel or download yet, so any failure to execute the above is an error - Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); - transfer.Exception = ex.Message; - transfer.State = TransferStates.Errored | TransferStates.Completed; - failed.Add(transfer); - continue; - } - } - - var recordsCreated = context.SaveChanges(); - - if (enqueued.Count == 0) - { - Log.Warning("None of the {Count} requested files from {Username} could be enqueued as they are already in progress", files.Count(), username); - return (enqueued, failed); - } - - /* - the files are all now in the database in the Queued | Locally state. - - we'll proceed with downloading them, but in a separate task run in the background - */ - Log.Debug("Scheduling batch remote enqueue Task for {Count} files from {Username}", enqueued.Count, username); + we'll proceed with downloading them, but in a separate task run in the background + */ + Log.Debug("Scheduling batch remote enqueue Task for {Count} files from {Username}", enqueued.Count, username); var batchEnqueueTask = Task.Run(async () => { @@ -826,267 +518,564 @@ namespace slskd.Transfers.Downloads }; } - Update(transfer); - } - } - catch (Exception innerEx) - { - Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); - } - } - finally - { - semaphore.Release(); - Log.Debug("Released download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); - } - }); + Update(transfer); + } + } + catch (Exception innerEx) + { + Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); + } + } + finally + { + semaphore.Release(); + Log.Debug("Released download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); + } + }); + + Log.Debug("Waiting for all {Count} download Tasks for {Username} to complete", enqueued.Count, username); + await Task.WhenAll(tasks); + }, cancellationToken).ContinueWith(task => + { + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for batch enqueue of {Count} files from {Username} completed successfully", files.Count(), username); + return; + } + + Log.Error(task.Exception, "Task for batch enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); + }, cancellationToken: CancellationToken.None); + + if (batchEnqueueTask.Status == TaskStatus.Canceled) + { + throw new OperationCanceledException($"The batch enqueue Task for {enqueued.Count} files from {username} was cancelled"); + } + + if (batchEnqueueTask.Status == TaskStatus.Faulted) + { + throw new Exception($"The batch enqueue Task for {enqueued.Count} files from {username} faulted: {batchEnqueueTask.Exception}", batchEnqueueTask.Exception); + } + + Log.Debug("Batch enqueue Task status: {Status}", batchEnqueueTask.Status); + Log.Information("Successfully enqueued {Count} files from {Username}", enqueued.Count, username); + + return (enqueued, failed); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue one or more of {Count} files from {Username}: {Message}", files.Count(), username, ex.Message); + throw; + } + finally + { + Log.Debug("Finalizing enqueue of one or more files from {Username}", username); + + foreach (var lockName in acquiredLocks) + { + if (Locks.TryRemove(lockName, out _)) + { + Log.Debug("Released lock {LockName}", lockName); + } + else + { + Log.Error("Failed to release lock for {LockName}", lockName); + } + } + + Log.Debug("Finalization of enqueue of one or more files from {Username} completed", username); + } + } + + /// + /// Finds a single download matching the specified . + /// + /// The expression to use to match downloads. + /// The found transfer, or default if not found. + public Transfer Find(Expression> expression) + { + try + { + using var context = ContextFactory.CreateDbContext(); + + return context.Transfers + .AsNoTracking() + .Where(t => t.Direction == TransferDirection.Download) + .Where(expression).FirstOrDefault(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to find download: {Message}", ex.Message); + throw; + } + } + + /// + /// Retrieves the place in the remote queue for the download matching the specified . + /// + /// The unique identifier for the download. + /// The retrieved place in queue. + public async Task GetPlaceInQueueAsync(Guid id) + { + try + { + using var context = ContextFactory.CreateDbContext(); + + var transfer = context.Transfers.Find(id); + + if (transfer == default) + { + throw new NotFoundException($"No download matching id ${id}"); + } + + var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); + + transfer.PlaceInQueue = place; + context.SaveChanges(); + + return place; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to get place in queue for download {Id}: {Message}", id, ex.Message); + throw; + } + } + + /// + /// Returns a list of all downloads matching the optional . + /// + /// An optional expression used to match downloads. + /// Optionally include downloads that have been removed previously. + /// The list of downloads matching the specified expression, or all downloads if no expression is specified. + public List List(Expression> expression = null, bool includeRemoved = false) + { + expression ??= t => true; + + try + { + using var context = ContextFactory.CreateDbContext(); + + return context.Transfers + .AsNoTracking() + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => !t.Removed || includeRemoved) + .Where(expression) + .ToList(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list downloads: {Message}", ex.Message); + throw; + } + } + + /// + /// Removes downloads older than the specified . + /// + /// The age after which downloads are eligible for pruning, in hours. + /// An optional, additional state by which downloads are filtered for pruning. + /// The number of pruned downloads. + public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) + { + if (!stateHasFlag.HasFlag(TransferStates.Completed)) + { + throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); + } + + try + { + using var context = ContextFactory.CreateDbContext(); - Log.Debug("Waiting for all {Count} download Tasks for {Username} to complete", enqueued.Count, username); - await Task.WhenAll(tasks); - }, cancellationToken).ContinueWith(task => - { - if (task.IsCompletedSuccessfully) - { - Log.Information("Task for batch enqueue of {Count} files from {Username} completed successfully", files.Count(), username); - return; - } + var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age); - Log.Error(task.Exception, "Task for batch enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); - }, cancellationToken: CancellationToken.None); + var expired = context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => !t.Removed) + .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) + .Where(t => t.State == stateHasFlag) + .ToList(); - if (batchEnqueueTask.Status == TaskStatus.Canceled) + foreach (var tx in expired) { - throw new OperationCanceledException($"The batch enqueue Task for {enqueued.Count} files from {username} was cancelled"); + tx.Removed = true; } - if (batchEnqueueTask.Status == TaskStatus.Faulted) + var pruned = context.SaveChanges(); + + if (pruned > 0) { - throw new Exception($"The batch enqueue Task for {enqueued.Count} files from {username} faulted: {batchEnqueueTask.Exception}", batchEnqueueTask.Exception); + Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, stateHasFlag); } - Log.Debug("Batch enqueue Task status: {Status}", batchEnqueueTask.Status); - Log.Information("Successfully enqueued {Count} files from {Username}", enqueued.Count, username); - - return (enqueued, failed); + return pruned; } catch (Exception ex) { - Log.Error(ex, "Failed to enqueue one or more of {Count} files from {Username}: {Message}", files.Count(), username, ex.Message); + Log.Error(ex, "Failed to prune downloads: {Message}", ex.Message); throw; } - finally - { - Log.Debug("Finalizing enqueue of one or more files from {Username}", username); - - foreach (var lockName in acquiredLocks) - { - if (Locks.TryRemove(lockName, out _)) - { - Log.Debug("Released lock {LockName}", lockName); - } - else - { - Log.Error("Failed to release lock for {LockName}", lockName); - } - } - - Log.Debug("Finalization of enqueue of one or more files from {Username} completed", username); - } } /// - /// Finds a single download matching the specified . + /// Removes the download matching the specified . /// - /// The expression to use to match downloads. - /// The found transfer, or default if not found. - public Transfer Find(Expression> expression) + /// This is a soft delete; the record is retained for historical retrieval. + /// The unique identifier of the download. + public void Remove(Guid id) { try { using var context = ContextFactory.CreateDbContext(); - return context.Transfers - .AsNoTracking() + var transfer = context.Transfers .Where(t => t.Direction == TransferDirection.Download) - .Where(expression).FirstOrDefault(); + .Where(t => t.Id == id) + .FirstOrDefault(); + + if (transfer == default) + { + throw new NotFoundException($"No download matching id ${id}"); + } + + if (!transfer.State.HasFlag(TransferStates.Completed)) + { + throw new InvalidOperationException($"Invalid attempt to remove a download before it is complete"); + } + + transfer.Removed = true; + + context.SaveChanges(); } catch (Exception ex) { - Log.Error(ex, "Failed to find download: {Message}", ex.Message); + Log.Error(ex, "Failed to remove download {Id}: {Message}", id, ex.Message); throw; } } /// - /// Retrieves the place in the remote queue for the download matching the specified . + /// Cancels the download matching the specified , if it is in progress. /// /// The unique identifier for the download. - /// The retrieved place in queue. - public async Task GetPlaceInQueueAsync(Guid id) + /// A value indicating whether the download was successfully cancelled. + public bool TryCancel(Guid id) + { + if (CancellationTokens.TryRemove(id, out var cts)) + { + cts.Cancel(); + return true; + } + + return false; + } + + /// + /// Synchronously updates the specified . + /// + /// The transfer to update. + public void Update(Transfer transfer) + { + using var context = ContextFactory.CreateDbContext(); + + context.Update(transfer); + context.SaveChanges(); + } + + private async Task DownloadAsync(Transfer transfer, Action stateChanged = null, CancellationToken cancellationToken = default) { + if (transfer is null) + { + throw new ArgumentNullException(nameof(transfer), "A valid, enqueued Transfer is required"); + } + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + + var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + var syncRoot = new SemaphoreSlim(1, 1); + + var lockName = $"{nameof(DownloadAsync)}:{transfer.Username}:{transfer.Filename}"; + + if (!Locks.TryAdd(lockName, true)) + { + Log.Debug("Download attempt failed; lock {LockName} already held", lockName); + throw new DuplicateTransferException("A duplicate download of the same file to the same user is already in progress"); + } + + /* + from this point forward, any exit from this method MUST result in an update to the Transfer record + in the database that sets EndedAt and ensures that the State property includes the Completed flag + + failure to do so means records will get "stuck" in the database/on the UI + + additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot + */ try { - using var context = ContextFactory.CreateDbContext(); + 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"); + } + + using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); + + var topts = new TransferOptions( + stateChanged: (args) => + { + try + { + Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", transfer.Filename, transfer.Username, args.PreviousState, args.Transfer.State); + + // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions; + // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup + if (Application.IsShuttingDown) + { + Log.Debug("Download update of {Filename} from {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); + return; + } + + transfer = transfer.WithSoulseekTransfer(args.Transfer); + + // we don't know when the download is actually enqueued (remotely) until it switches into that state + // when it is enqueued locally is irrelevant, due to internal throttling etc + if (args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) + { + transfer.EnqueuedAt ??= DateTime.UtcNow; + } + + // todo: broadcast + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); + } + finally + { + stateChanged?.Invoke(transfer); + } + }, + progressUpdated: (args) => rateLimiter.Invoke(() => + { + // don't do anything unless the `transfer` within the outer scope is in the + // InProgress state; this will help prevent out-of-band updates that are sometimes + // being made after the transfer is completed, causing them to appear 'stuck' + if (transfer.State == TransferStates.InProgress) + { + // don't wait for the semaphore; if a previous progress update is still hanging, don't make + // the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems + // but the alternative is to continue to stack slow writes on top of one another + if (syncRoot.Wait(millisecondsTimeout: 0, cts.Token)) + { + try + { + // update only the properties that we expect to change between progress updates + // this helps prevent this update from 'stepping' on other updates + transfer.BytesTransferred = args.Transfer.BytesTransferred; + transfer.AverageSpeed = args.Transfer.AverageSpeed; + + using var context = ContextFactory.CreateDbContext(); + + context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + } + finally + { + syncRoot.Release(); + } + } + else + { + Log.Debug("Skipped progress update of {Filename} from {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size); + } + } + }), + disposeOutputStreamOnCompletion: true); - var transfer = context.Transfers.Find(id); + // register the cancellation token + CancellationTokens.TryAdd(transfer.Id, cts); - if (transfer == default) - { - throw new NotFoundException($"No download matching id ${id}"); - } + System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() + : null; - var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); + Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); - transfer.PlaceInQueue = place; - context.SaveChanges(); + var completedTransfer = await Client.DownloadAsync( + username: transfer.Username, + remoteFilename: transfer.Filename, + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + options: new CreateFileOptions + { + Access = System.IO.FileAccess.Write, + Mode = System.IO.FileMode.Create, // overwrites file if it exists + Share = System.IO.FileShare.None, // exclusive access for the duration of the download + UnixCreateMode = unixFileMode, + })), + size: transfer.Size, + startOffset: 0, + token: null, + cancellationToken: cts.Token, + options: topts); - return place; - } - catch (Exception ex) - { - Log.Error(ex, "Failed to get place in queue for download {Id}: {Message}", id, ex.Message); - throw; - } - } + Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); - /// - /// Returns a list of all downloads matching the optional . - /// - /// An optional expression used to match downloads. - /// Optionally include downloads that have been removed previously. - /// The list of downloads matching the specified expression, or all downloads if no expression is specified. - public List List(Expression> expression = null, bool includeRemoved = false) - { - expression ??= t => true; + // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we + // flushe any pending update, _probably_ pushing the state of the transfer back to InProgress + rateLimiter.Dispose(); - try - { - using var context = ContextFactory.CreateDbContext(); + // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state + // over the top of the transfer record, then persist it + transfer = transfer.WithSoulseekTransfer(completedTransfer); - return context.Transfers - .AsNoTracking() - .Where(t => t.Direction == TransferDirection.Download) - .Where(t => !t.Removed || includeRemoved) - .Where(expression) - .ToList(); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to list downloads: {Message}", ex.Message); - throw; - } - } + // todo: broadcast to signalr hub + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - /// - /// Removes downloads older than the specified . - /// - /// The age after which downloads are eligible for pruning, in hours. - /// An optional, additional state by which downloads are filtered for pruning. - /// The number of pruned downloads. - public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) - { - if (!stateHasFlag.HasFlag(TransferStates.Completed)) - { - throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); - } + Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); - try - { - using var context = ContextFactory.CreateDbContext(); + // move the file from incomplete to complete + var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); - var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age); + var finalFilename = Files.MoveFile( + sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + destinationDirectory: destinationDirectory, + unixFileMode: unixFileMode, + overwrite: false, + deleteSourceDirectoryIfEmptyAfterMove: true); - var expired = context.Transfers - .Where(t => t.Direction == TransferDirection.Download) - .Where(t => !t.Removed) - .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - .Where(t => t.State == stateHasFlag) - .ToList(); + Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); - foreach (var tx in expired) + if (OptionsMonitor.CurrentValue.Relay.Enabled) { - tx.Removed = true; + _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); } - var pruned = context.SaveChanges(); - - if (pruned > 0) + try { - Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, stateHasFlag); - } + // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, + // and the file has been moved from the incomplete directory to the downloads directory + Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username); - return pruned; - } - catch (Exception ex) - { - Log.Error(ex, "Failed to prune downloads: {Message}", ex.Message); - throw; - } - } + EventBus.Raise(new DownloadFileCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + LocalFilename = finalFilename, + RemoteFilename = transfer.Filename, + Transfer = transfer, + }); - /// - /// Removes the download matching the specified . - /// - /// This is a soft delete; the record is retained for historical retrieval. - /// The unique identifier of the download. - public void Remove(Guid id) - { - try - { - using var context = ContextFactory.CreateDbContext(); + // try to figure out if this file is the last of a directory, and if so, raise the associated + // event. this can be tricky because we want to be sure that this is the last file in this specific + // directory, excluding any pending downloads in a subdirectory. + var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); + var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); + var pendingDownloadsInDirectory = Client.Downloads + .Where(t => t.Username == transfer.Username) + .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); - var transfer = context.Transfers - .Where(t => t.Direction == TransferDirection.Download) - .Where(t => t.Id == id) - .FirstOrDefault(); + if (!pendingDownloadsInDirectory.Any()) + { + EventBus.Raise(new DownloadDirectoryCompleteEvent + { + Timestamp = transfer.EndedAt.Value, + Username = transfer.Username, + LocalDirectoryName = destinationDirectory, + RemoteDirectoryName = remoteDirectoryName, + }); + } - if (transfer == default) + if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) + { + _ = FTP.UploadAsync(finalFilename); + } + + Log.Debug("Completed post-download logic for {Filename} from {Username} successfully", transfer.Filename, transfer.Username); + } + catch (Exception ex) { - throw new NotFoundException($"No download matching id ${id}"); + // log, but don't throw. the file ended up in the download folder and is complete; if we throw it looks like it didn't complete + // todo: add a visual indicator/new state for Transfers that indicate this state. or move all of this logic out and handle it via events + Log.Error(ex, "Failed to run post-download processes for {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); } - if (!transfer.State.HasFlag(TransferStates.Completed)) + Log.Information("Download of {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); + + return transfer; + } + catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) + { + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); + + transfer.EndedAt = DateTime.UtcNow; + transfer.Exception = ex.Message; + transfer.State = TransferStates.Completed; + + transfer.State |= ex switch { - throw new InvalidOperationException($"Invalid attempt to remove a download before it is complete"); - } + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; - transfer.Removed = true; + // todo: broadcast + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); - context.SaveChanges(); + throw; } catch (Exception ex) { - Log.Error(ex, "Failed to remove download {Id}: {Message}", id, ex.Message); + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); + + transfer.EndedAt = DateTime.UtcNow; + transfer.Exception = ex.Message; + transfer.State = TransferStates.Completed | TransferStates.Errored; + + // todo: broadcast + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); + throw; } - } - - /// - /// Cancels the download matching the specified , if it is in progress. - /// - /// The unique identifier for the download. - /// A value indicating whether the download was successfully cancelled. - public bool TryCancel(Guid id) - { - if (CancellationTokens.TryRemove(id, out var cts)) + finally { - cts.Cancel(); - return true; - } + Log.Debug("Finalizing download of {Filename} from {Username}", transfer.Filename, transfer.Username); - return false; - } + try + { + Locks.TryRemove(lockName, out _); + Log.Debug("Released lock {LockName}", lockName); - /// - /// Synchronously updates the specified . - /// - /// The transfer to update. - public void Update(Transfer transfer) - { - using var context = ContextFactory.CreateDbContext(); + CancellationTokens.TryRemove(transfer.Id, out _); - context.Update(transfer); - context.SaveChanges(); + Log.Debug("Finalization of download of {Filename} from {Username} completed", transfer.Filename, transfer.Username); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to finalize download of {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); + } + } } private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default) -- cgit v1.2.3