diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-11-22 18:36:31 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-11-22 18:36:31 -0600 |
| commit | 47490e366b5bc4b2a1679fba50655697afbe7137 (patch) | |
| tree | ae98bb4fb66d20e5fecd69267bcbb17d80c4986b /src/slskd/Transfers | |
| parent | 2e073014a003fc4e972a9a2677fccd3d30074cd2 (diff) | |
| parent | 6ba7311d48b95ca75f49b3b28c1a8db810f87fe1 (diff) | |
| download | slskd-47490e366b5bc4b2a1679fba50655697afbe7137.tar.gz | |
Merge branch 'master' into dependabot/npm_and_yarn/src/web/axios-0.30.2
Diffstat (limited to 'src/slskd/Transfers')
| -rw-r--r-- | src/slskd/Transfers/API/Controllers/TransfersController.cs | 25 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 884 | ||||
| -rw-r--r-- | src/slskd/Transfers/TransfersDbContext.cs | 1 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 230 |
4 files changed, 813 insertions, 327 deletions
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index fdbca1dc..6be11b2d 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -23,10 +23,12 @@ namespace slskd.Transfers.API using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; + using System.Threading; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using Serilog; /// <summary> /// Transfers. @@ -51,8 +53,10 @@ namespace slskd.Transfers.API OptionsSnapshot = optionsSnapshot; } + private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(2, 2); private ITransferService Transfers { get; } private IOptionsSnapshot<Options> OptionsSnapshot { get; } + private ILogger Log { get; set; } = Serilog.Log.ForContext<TransfersController>(); /// <summary> /// Cancels the specified download. @@ -204,22 +208,37 @@ namespace slskd.Transfers.API [ProducesResponseType(201)] [ProducesResponseType(typeof(string), 403)] [ProducesResponseType(typeof(string), 500)] - public async Task<IActionResult> EnqueueAsync([FromRoute, Required] string username, [FromBody] IEnumerable<QueueDownloadRequest> requests) +#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) +#pragma warning disable SA1611 // Element parameters should be documented + public async Task<IActionResult> EnqueueAsync([FromRoute, Required] string username, [FromBody] IEnumerable<QueueDownloadRequest> requests, CancellationToken cancellationToken = default) +#pragma warning restore SA1611 // Element parameters should be documented +#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) { if (Program.IsRelayAgent) { return Forbid(); } + if (!DownloadRequestLimiter.Wait(0)) + { + return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); + } + try { - await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size))); - return StatusCode(201); + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)), cancellationToken); + + return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); } catch (Exception ex) { + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message); return StatusCode(500, ex.Message); } + finally + { + DownloadRequestLimiter.Release(); + } } /// <summary> diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index ef8e84bf..9d0a8ed9 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -25,6 +25,7 @@ namespace slskd.Transfers.Downloads using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; + using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; @@ -55,11 +56,12 @@ namespace slskd.Transfers.Downloads /// </remarks> /// <param name="username">The username of remote user.</param> /// <param name="files">The list of files to enqueue.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</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> - Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + Task<(List<Transfer> Enqueued, List<string> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default); /// <summary> /// Finds a single download matching the specified <paramref name="expression"/>. @@ -133,8 +135,28 @@ namespace slskd.Transfers.Downloads FTP = ftpClient; Relay = relayService; EventBus = eventBus; + + Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); } + /// <summary> + /// These tokens give users the ability to cancel transfers via the UI (or API). + /// + /// The lifecycle is: + /// + /// 1. in EnqueueAsync(), just before transfer records are added to the database, these CTS are created and + /// added to the dictionary + /// 2. in EnqueueAsync(), if there was an error or any condition which caused the transfer to not proceed was met, + /// the CTS is removed from the dictionary and disposed + /// 3. in DownloadAsync(), in the finally block after all post-download logic has been executed, the CTS + /// is removed and disposed. + /// + /// The CTS should be in the dictionary the entire time the transfer is "in flight", from the first moment it + /// comes into being (via database insert) until the eventual download process has completed or failed. + /// + /// Every cancellable operation in this flow needs to use this CTS token either directly or by linking it with another, + /// or we risk transfers getting stuck with no way for users to get rid of them. + /// </summary> private ConcurrentDictionary<Guid, CancellationTokenSource> CancellationTokens { get; } = new ConcurrentDictionary<Guid, CancellationTokenSource>(); private ISoulseekClient Client { get; } private IDbContextFactory<TransfersDbContext> ContextFactory { get; } @@ -146,6 +168,19 @@ namespace slskd.Transfers.Downloads private EventBus EventBus { get; } /// <summary> + /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they + /// don't already exist, and a timer asynchronously cleans the dictionary up. + /// </summary> + private ConcurrentDictionary<string, SemaphoreSlim> EnqueueSemaphores { get; } = []; + + /// <summary> + /// Synchronizes the cleanup process; after gaining exclusive access over the dictionary, checks each entry + /// to see if the containing semaphore can be obtained immediately. If so, it's not in use and is therefore + /// removed from the dictionary and discarded. + /// </summary> + private SemaphoreSlim EnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(initialCount: 1, maxCount: 1); + + /// <summary> /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username. /// </summary> /// <remarks>This should generally not be called; use EnqueueAsync() instead.</remarks> @@ -174,298 +209,356 @@ namespace slskd.Transfers.Downloads /// <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> + /// <param name="cancellationToken">The token to monitor for cancellation.</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) + public async Task<(List<Transfer> Enqueued, List<string> 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()) + var fileList = files.ToList(); + + if (fileList.Count == 0) { - throw new ArgumentException("At least one file is require", nameof(files)); + throw new ArgumentException("At least one file is required", nameof(files)); } - return EnqueueAsyncInternal(username, files); + if (fileList.Count != fileList.Distinct().Count()) + { + throw new ArgumentException("Two or more files in request are duplicated", nameof(files)); + } + + IPEndPoint endpoint; + + Log.Information("Requested enqueue of {Count} files from user {Username}", fileList.Count, username); - async Task EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files) + // get the user's ip and port. this will throw if they are offline. + try { - try + endpoint = await Client.GetUserEndPointAsync(username, cancellationToken); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue {Count} files from {Username}: {Message}", fileList.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<Transfer> enqueued = []; + List<string> failed = []; + + SemaphoreSlim userSemaphore; + Task userSemaphoreWaitTask; + + Log.Debug("Awaiting enqueue semaphore sync root"); + await EnqueueSemaphoreSyncRoot.WaitAsync(cancellationToken); + + try + { + Log.Debug("Acquired enqueue semaphore sync root"); + userSemaphore = EnqueueSemaphores.GetOrAdd(username, (username) => new SemaphoreSlim(initialCount: 1, maxCount: 1)); + userSemaphoreWaitTask = userSemaphore.WaitAsync(cancellationToken); + } + finally + { + EnqueueSemaphoreSyncRoot.Release(); + Log.Debug("Released enqueue semaphore sync root"); + } + + Log.Debug("Awaiting enqueue semaphore for user {Username}", username); + await userSemaphoreWaitTask; + + try + { + Log.Debug("Acquired enqueue semaphore for user {Username}", username); + + using var context = ContextFactory.CreateDbContext(); + + /* + get all past downloads from this user. this list will remain stable throughout this process because + we have exclusive access for this user. we'll be adding new records, but we've already deduplicated + them so we don't have to worry about duplicate records being created in the critical section + */ + var existingRecords = context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => t.Username == username) + .AsNoTracking() + .ToList(); + + var existingInProgressRecords = existingRecords + .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) + .ToDictionary(t => t.Filename, t => t); + + /* + determine how many concurrent enqueue requests we want to send to the remote client. + + sending a ton of them can bog the client down and fail transfers due to resource contention on both sides, + but both clients should be able to handle momentary 'bursts'. + + if the request contains 30 files or fewer, send all of the requests at the same time. the average number + of tracks in a single album is 15, so this is 2x as many as most enqueue requests will need. + + if that number is more than 30, send only 5 at a time; transfers will be starting as we are still + enqueueing files, and this raises the risk of errors considerably. + */ + var concurrentEnqueueRequests = 5; + + if (fileList.Count <= 30) { - Log.Information("Downloading {Count} files from user {Username}", files.Count(), username); + concurrentEnqueueRequests = fileList.Count; + } - Log.Debug("Priming connection for user {Username}", username); - await Client.ConnectToUserAsync(username, invalidateCache: false); - Log.Debug("Connection for user '{Username}' primed", username); + var maxTimeToWaitForEnqueueRequestAck = TimeSpan.FromMinutes(3); + var enqueueSemaphore = new SemaphoreSlim(initialCount: concurrentEnqueueRequests, maxCount: concurrentEnqueueRequests); - var thrownExceptions = new List<Exception>(); + /* + iterate over each of the files in the request. each file must be dispositioned as one of the following: - foreach (var file in files) + 1. enqueued: passed duplicate checks and successfully kicked off a Task to enqueue the download + 2. failed: download is already in progress, or something went wrong kicking off the Task + + if we fail to enqueue a file, we must call TryFail() to ensure that if a record was inserted, it is + given a final disposition that will keep it from getting 'stuck' + */ + foreach (var file in fileList) + { + cancellationToken.ThrowIfCancellationRequested(); + Guid transferId = Guid.NewGuid(); + + try { - Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username); + 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! - var id = Guid.NewGuid(); + 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 + */ + existingInProgressRecords.TryGetValue(file.Filename, out var existingInProgressRecord); + if (existingInProgressRecord is not null || Client.Downloads.Any(u => u.Username == username && u.Filename == file.Filename)) + { + Log.Debug("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} already in progress (id: {Id})", file.Filename, username, existingInProgressRecord.Id); + failed.Add(file.Filename); + continue; + } + + /* + add the transfer record to the database in the Queued | Locally state, and set the 'Removed' + property of any existing transfer to 'true', allowing the new record to supersede any old record(s) + on the UI + + we have to persist these changes to the database at this time so the record shows up on the UI, + otherwise the transfers only show up as they are enqueued. + */ var transfer = new Transfer() { - Id = id, + Id = transferId, Username = username, Direction = TransferDirection.Download, - Filename = file.Filename, + Filename = file.Filename, // important! use the remote filename Size = file.Size, - StartOffset = 0, + StartOffset = 0, // todo: maybe implement resumeable downloads? RequestedAt = DateTime.UtcNow, + State = TransferStates.Queued | TransferStates.Locally, }; - // persist the transfer to the database so we have a record that it was attempted - AddOrSupersede(transfer); + 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.Filename == file.Filename && !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); + } - var cts = new CancellationTokenSource(); - CancellationTokens.TryAdd(id, cts); + /* + create a TaskCompletionSource that we can await for one of the following: - var waitUntilEnqueue = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); + 1. the transfer enters the Queued | Remotely state + 2. the transfer enters a state containing Completed + 3. the linked CancellationTokenSource we add to CancellationTokens is cancelled + 4. the 'max wait time' CancellationTokenSource is cancelled - // 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 () => + add this to the dictionary before inserting the record, so we are guaranteed to have it + in the right place once the transfer hits the UI + */ + var enqueuedTcs = new TaskCompletionSource<Transfer>(); + + // satisfies condition #3; CancellationTokenSource set cancelled by the user (via API call) + var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + CancellationTokens.TryAdd(transfer.Id, cts); + cts.Token.Register(() => enqueuedTcs.TrySetCanceled()); + + /* + DANGER ZONE! this record is in the database now; we're on the hook for making sure it ends up + with a State that includes the Completed flag, else it remain "stuck" on the UI + */ + context.SaveChanges(); + + Log.Debug("Scheduling Task for enqueue of {Filename} from {Username}", file.Filename, username); + + var downloadEnqueueTask = Task.Run(async () => { - using var rateLimiter = new RateLimiter(250, flushOnDispose: true); - var syncRoot = new SemaphoreSlim(1, 1); + Log.Debug("Awaiting download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); + await enqueueSemaphore.WaitAsync(cts.Token); - void SynchronizedUpdate(Transfer transfer, bool cancellable = true) + try { - syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); + Log.Debug("Acquired download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); - try + List<string> transitions = []; + TransferStates state = TransferStates.None; + + // satisfies condition #4; remote user doesn't respond after a really long time + using var timeoutCts = new CancellationTokenSource(maxTimeToWaitForEnqueueRequestAck); + timeoutCts.Token.Register(() => { - Update(transfer); - } - finally + Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit of {Duration} seconds. State transition history: {History}", transfer.Filename, username, maxTimeToWaitForEnqueueRequestAck.TotalSeconds, string.Join(", ", transitions)); + enqueuedTcs.TrySetException(new TimeoutException($"Download failed to enqueue remotely after hard time limit of {maxTimeToWaitForEnqueueRequestAck.TotalSeconds} secs")); + }); + + // satisfies conditions #1 and #2 + void stateChanged(Transfer transfer) { - syncRoot.Release(); - } - } + state = transfer.State; + transitions.Add(transfer.State.ToString()); - try - { - var topts = new TransferOptions( - disposeOutputStreamOnCompletion: true, - stateChanged: (args) => + if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely)) { - 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; - } + // satisfies condition #1; transfer is now remotely queued + enqueuedTcs.TrySetResult(transfer); + } - transfer = transfer.WithSoulseekTransfer(args.Transfer); - - if ((args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely)) || args.Transfer.State == TransferStates.Initializing) + // satisfies condition #2; transfer advanced to a terminal state before being enqueued remotely (probably failed) + if (transfer.State.HasFlag(TransferStates.Completed)) + { + if (transfer.State.HasFlag(TransferStates.Succeeded)) { - transfer.EnqueuedAt = DateTime.UtcNow; - waitUntilEnqueue.TrySetResult(true); + enqueuedTcs.TrySetResult(transfer); } - - 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) + else { - 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(); - } + enqueuedTcs.TrySetException(new TransferException(transfer.Exception)); } - })); - - var completedTransfer = await Client.DownloadAsync( - username: username, - remoteFilename: file.Filename, - outputStreamFactory: () => Task.FromResult( - Files.CreateFile( - filename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - options: new CreateFileOptions - { - Access = System.IO.FileAccess.Write, - Mode = System.IO.FileMode.Create, // overwrites file if it exists - Share = System.IO.FileShare.None, // exclusive access for the duration of the download - UnixCreateMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) - ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() - : null, - })), - size: file.Size, - startOffset: 0, - token: null, - cancellationToken: cts.Token, - options: topts); - - // explicitly dispose the rate limiter to prevent updates from it - // beyond this point, which may overwrite the final state - rateLimiter.Dispose(); - - transfer = transfer.WithSoulseekTransfer(completedTransfer); - - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); - - var destinationDirectory = System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); - - var finalFilename = Files.MoveFile( - sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - destinationDirectory: destinationDirectory, - overwrite: false, - deleteSourceDirectoryIfEmptyAfterMove: true); - - Log.Debug("Moved file to {Destination}", finalFilename); - - // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, - // and the file has been moved from the incomplete directory to the downloads directory - if (OptionsMonitor.CurrentValue.Relay.Enabled) - { - _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); + } } - EventBus.Raise(new DownloadFileCompleteEvent + Log.Debug("Scheduling Task for download of {Filename} from {Username}", transfer.Filename, transfer.Username); + + var downloadTask = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken: cts.Token)).ContinueWith(task => { - Timestamp = transfer.EndedAt.Value, - LocalFilename = finalFilename, - RemoteFilename = transfer.Filename, - Transfer = transfer, - }); + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); + return; + } - // 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); + Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, task.Exception.InnerException?.Message ?? task.Exception.Message); - if (!pendingDownloadsInDirectory.Any()) - { - EventBus.Raise(new DownloadDirectoryCompleteEvent + if (!TryFail(transferId, exception: task.Exception)) { - Timestamp = transfer.EndedAt.Value, - Username = transfer.Username, - LocalDirectoryName = destinationDirectory, - RemoteDirectoryName = remoteDirectoryName, - }); - } + Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, task.Exception.Message); + } + }, cancellationToken: CancellationToken.None); // end downloadTask.Run(); - if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) - { - _ = FTP.UploadAsync(finalFilename); - } - } - catch (OperationCanceledException ex) - { - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Cancelled; + Log.Debug("Download Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadTask.Status); + + Log.Debug("Waiting for download of {Filename} from {Username} to transition into {State}", transfer.Filename, transfer.Username, TransferStates.Queued | TransferStates.Remotely); - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); + /* + wait for one of the four conditions to be true: - throw; + 1. the transfer enters the Queued | Remotely state + 2. the transfer enters a state containing Completed + 3. the linked CancellationTokenSource we add to CancellationTokens is cancelled + 4. the 'max wait time' CancellationTokenSource is cancelled + */ + await enqueuedTcs.Task; + + Log.Debug("Download of {Filename} from {Username} successfully entered state {State}", transfer.Filename, transfer.Username, state); } catch (Exception ex) { - Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", file.Filename, username, ex.Message); - - transfer.EndedAt = DateTime.UtcNow; - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Errored; - - // todo: broadcast to signalr hub - SynchronizedUpdate(transfer, cancellable: false); - - throw; + Log.Error(ex, "Download of {File} from {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); + if (!TryFail(transferId, exception: ex)) + { + Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message); + } } finally { - CancellationTokens.TryRemove(id, out _); + enqueueSemaphore.Release(); } - }); - - // 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); - - // 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) + }, cancellationToken: cts.Token).ContinueWith(task => { - Exception ex = downloadTask.Exception; + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for enqueue of {Filename} from {Username} completed successfully", file.Filename, username); + return; + } - // todo: figure out why this needs to be unwrapped just for this one case. is this always an aggregate? - if (ex is AggregateException aggEx) + Log.Error(task.Exception, "Task for enqueue of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, task.Exception.InnerException?.Message ?? task.Exception.Message); + + if (!TryFail(transferId, exception: task.Exception)) { - var rejected = aggEx.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty<Exception>(); - if (rejected.Any()) - { - ex = rejected.First(); - } + Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, task.Exception.Message); } + }, cancellationToken: CancellationToken.None); // end downloadEnqueueTask.Run(); - Log.Error("Failed to download {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); - thrownExceptions.Add(ex); - } - else + Log.Debug("Download enqueue Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadEnqueueTask.Status); + Log.Information("Successfully locally enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transfer.Id); + enqueued.Add(transfer); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); + TryFail(transferId, exception: ex); + failed.Add(file.Filename); + + if (CancellationTokens.TryRemove(transferId, out var cts)) { - Log.Debug("Successfully enqueued {Filename} from user {Username}", file.Filename, username); + cts.Dispose(); } - } - if (thrownExceptions.Any()) - { - throw new AggregateException(thrownExceptions); + continue; } + } // end foreach() - Log.Information("Successfully enqueued {Count} file(s) from user {Username}", files.Count(), username); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to download one or more files from user {Username}: {Message}", username, ex.Message); - throw; - } + 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}", fileList.Count, username, ex.Message); + throw; + } + finally + { + userSemaphore.Release(); + Log.Debug("Released enqueue semaphore for user {Username}", username); } } @@ -643,12 +736,74 @@ namespace slskd.Transfers.Downloads /// <returns>A value indicating whether the download was successfully cancelled.</returns> public bool TryCancel(Guid id) { + // if the cancellation token is still in the dictionary, calling Cancel() on it _should_ + // cause the transfer operation to fail with an OperationCancelled exception and set the state + // of the transfer to Cancelled. _should_! if (CancellationTokens.TryRemove(id, out var cts)) { cts.Cancel(); return true; } + /* + if the cancellation token couldn't be found in the dictionary, either: + + 1. the transfer completed already + 2. something went wrong and the record is 'stuck' + + see if we can find the record, and if it's *NOT* completed, cancel it. otherwise, + leave it alone. + */ + var t = Find(t => t.Id == id); + + if (t is not null && !t.State.HasFlag(TransferStates.Completed)) + { + t.EndedAt = DateTime.UtcNow; + t.State = TransferStates.Completed | TransferStates.Cancelled; + t.Exception = new OperationCanceledException().Message; + Update(t); + return true; + } + + // this transfer id didn't have a cancellation token registered, and we couldn't find it in the dictionary + return false; + } + + /// <summary> + /// Fails the download matching the specified <paramref name="id"/> with the specified <paramref name="exception"/>, + /// and sets the final state accordingly. + /// </summary> + /// <remarks> + /// This method is designed to be idempotent, meaning subsequent calls for a given transfer shouldn't change + /// the EndedAt or Exception properties if they have already been set. If the transfer State already includes + /// the terminal Completed flag, it is unchanged. + /// </remarks> + /// <param name="id">The unique identifier for the download.</param> + /// <param name="exception">The exception that caused the failure.</param> + /// <returns>A value indicating whether the download was successfully failed.</returns> + public bool TryFail(Guid id, Exception exception) + { + var t = Find(t => t.Id == id); + + if (t is not null) + { + t.EndedAt ??= DateTime.UtcNow; + t.Exception ??= exception.Message; + + if (!t.State.HasFlag(TransferStates.Completed)) + { + t.State = TransferStates.Completed | exception switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; + } + + Update(t); + return true; + } + return false; } @@ -663,5 +818,296 @@ namespace slskd.Transfers.Downloads context.Update(transfer); context.SaveChanges(); } + + /// <summary> + /// Downloads the specified enqueued <paramref name="transfer"/> from the remote user. + /// </summary> + /// <param name="transfer">The Transfer to download.</param> + /// <param name="stateChanged">An optional delegate to invoke the transfer state changes.</param> + /// <param name="cancellationToken">The token to monitor for cancellation.</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> + private async Task<Transfer> DownloadAsync(Transfer transfer, Action<Transfer> stateChanged = null, CancellationToken cancellationToken = default) + { + if (transfer is null) + { + throw new ArgumentNullException(nameof(transfer), "A valid, enqueued Transfer is required"); + } + + // grab the latest from the database; this may have been sitting behind a semaphore or something + transfer = Find(t => t.Id == transfer.Id) + ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) + { + throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); + } + + 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"); + } + + // there _should_ be a cancellation token for this transfer in the dictionary; if so link it with the one we are given + // (which is probably the same one, harmless if so) to make sure we don't get any wires crossed + CancellationTokens.TryGetValue(transfer.Id, out var cancellationTokenSource); + using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cancellationTokenSource?.Token ?? CancellationToken.None); + cancellationToken = cts.Token; + + var updateSyncRoot = new SemaphoreSlim(1, 1); + + try + { + 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: updateSyncRoot, cancellationToken: cancellationToken); + } + 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 (updateSyncRoot.Wait(millisecondsTimeout: 0, cancellationToken: cancellationToken)) + { + 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 + { + updateSyncRoot.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); + + System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() + : null; + + Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); + + var completedTransfer = await Client.DownloadAsync( + username: transfer.Username, + remoteFilename: transfer.Filename, + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + options: new CreateFileOptions + { + Access = System.IO.FileAccess.Write, + Mode = System.IO.FileMode.Create, // overwrites file if it exists + Share = System.IO.FileShare.None, // exclusive access for the duration of the download + UnixCreateMode = unixFileMode, + })), + size: transfer.Size, + startOffset: 0, + token: null, + cancellationToken: cancellationToken, + options: topts); + + Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); + + // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we + // flush any pending update, _probably_ pushing the state of the transfer back to InProgress + rateLimiter.Dispose(); + + // copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state + // over the top of the transfer record, then persist it + transfer = transfer.WithSoulseekTransfer(completedTransfer); + + // todo: broadcast to signalr hub + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + + Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); + + // 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); + + TryFail(transfer.Id, exception: ex); + + // todo: broadcast + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + + throw; + } + catch (Exception ex) + { + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); + + TryFail(transfer.Id, exception: ex); + + // todo: broadcast + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); + + throw; + } + finally + { + if (CancellationTokens.TryRemove(transfer.Id, out var storedCancellationTokenSource)) + { + storedCancellationTokenSource?.Dispose(); + } + } + } + + private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default) + { + semaphore.Wait(cancellationToken); + + try + { + Update(transfer); + } + finally + { + semaphore.Release(); + } + } + + private async Task CleanupEnqueueSemaphoresAsync() + { + if (await EnqueueSemaphoreSyncRoot.WaitAsync(0).ConfigureAwait(false)) + { + try + { + foreach (var kvp in EnqueueSemaphores) + { + if (await kvp.Value.WaitAsync(0).ConfigureAwait(false)) + { + EnqueueSemaphores.TryRemove(kvp.Key, out var removed); + removed.Dispose(); + Log.Debug("Cleaned up enqueue semaphore for {Key}", kvp.Key); + } + } + } + finally + { + EnqueueSemaphoreSyncRoot.Release(); + } + } + } } }
\ No newline at end of file diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index ea138bcd..eac4935b 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -26,7 +26,6 @@ namespace slskd.Transfers public TransfersDbContext(DbContextOptions<TransfersDbContext> options) : base(options) { - Database.EnsureCreated(); } public DbSet<Transfer> Transfers { get; set; } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 6db9f6a5..4b35bffb 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,6 +220,13 @@ 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 cts = new CancellationTokenSource(); + var syncRoot = new SemaphoreSlim(1, 1); + + string host = default; + string localFilename = default; + long localFileLength = default; + var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}"; if (!Locks.TryAdd(lockName, true)) @@ -228,104 +235,82 @@ namespace slskd.Transfers.Uploads 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"); + 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 - if (t.State != (TransferStates.Queued | TransferStates.Locally)) - { - throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {t.State}"); - } + failure to do so means records will get "stuck" in the database/on the UI - /* - 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 + additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot */ - 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)) + Log.Debug("Acquired lock {LockName}", lockName); + + /* + fetch an updated copy of the transfer record from the database; now that we are locked, we *should* + have exclusive access to this record + + we're not using DbContext and tracked changes here because we don't want to hold a connection + open for the duration of the upload + */ + transfer = Find(t => t.Id == transfer.Id) + ?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found"); + + if (transfer.State != (TransferStates.Queued | TransferStates.Locally)) { - await Users.WatchAsync(t.Username); + throw new InvalidOperationException($"Invalid starting state for upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); } - } - catch (Exception ex) - { - Log.Warning(ex, "Failed to watch user {Username}", t.Username); - } - - var cts = new CancellationTokenSource(); - var syncRoot = new SemaphoreSlim(1, 1); - void SynchronizedUpdate(Transfer transfer, bool cancellable = true) - { - syncRoot.Wait(cancellable ? cts.Token : CancellationToken.None); + /* + 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 { - Update(transfer); + if (!Users.IsWatched(transfer.Username)) + { + await Users.WatchAsync(transfer.Username); + } } - finally + catch (Exception ex) { - syncRoot.Release(); + Log.Warning(ex, "Failed to watch user {Username}", transfer.Username); } - } - - string host = default; - string localFilename = default; - long localFileLength = default; - - /* - from this point forward, any exit from this method MUST result in an update to the Transfer record - in the database that sets EndedAt and ensures that the State property includes the Completed flag - - failure to do so means records will get "stuck" in the database/on the UI - additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot - */ - try - { - Log.Debug("Acquired lock {LockName}", lockName); - Log.Information("Initializing upload {Filename} to {Username}", t.Filename, t.Username); + Log.Information("Initializing upload of {Filename} to {Username}", transfer.Filename, transfer.Username); // locate the file on disk. we checked this once already when enqueueing, but it may have moved since // can throw NotFoundException - (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: t.Filename); + (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: transfer.Filename); - using var rateLimiter = new RateLimiter(250, flushOnDispose: true); + using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, 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; } transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast - SynchronizedUpdate(transfer); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); }, progressUpdated: (args) => rateLimiter.Invoke(() => { @@ -334,28 +319,32 @@ namespace slskd.Transfers.Uploads // being made after the transfer is completed, causing them to appear 'stuck' if (transfer.State == TransferStates.InProgress) { - syncRoot.Wait(cts.Token); - - try + // 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)) { - // 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; - - // check again to see if the state changed while we were waiting to obtain the lock - if (transfer.State == TransferStates.InProgress) + 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, args.Transfer.BytesTransferred) - .SetProperty(t => t.AverageSpeed, args.Transfer.AverageSpeed)); + .SetProperty(t => t.BytesTransferred, transfer.BytesTransferred) + .SetProperty(t => t.AverageSpeed, transfer.AverageSpeed)); + } + finally + { + syncRoot.Release(); } } - finally + else { - syncRoot.Release(); + Log.Debug("Skipped progress update of {Filename} to {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size); } } }), @@ -367,20 +356,20 @@ 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); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); Soulseek.Transfer completedTransfer; 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 +387,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 @@ -417,13 +406,13 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(completedTransfer); // todo: broadcast - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); EventBus.Raise(new UploadFileCompleteEvent { Timestamp = transfer.EndedAt.Value, LocalFilename = localFilename, - RemoteFilename = t.Filename, + RemoteFilename = transfer.Filename, Transfer = transfer, }); @@ -435,31 +424,38 @@ namespace slskd.Transfers.Uploads transfer.Exception = "File could not be found"; transfer.State = TransferStates.Completed | TransferStates.Aborted; - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); 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); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); throw; } 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; transfer.State = TransferStates.Completed | TransferStates.Errored; // todo: broadcast - SynchronizedUpdate(transfer, cancellable: false); + SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); throw; } @@ -469,7 +465,7 @@ namespace slskd.Transfers.Uploads { try { - Relay.TryCloseFileStream(host, id: t.Id); + Relay.TryCloseFileStream(host, id: transfer.Id); } catch { @@ -482,16 +478,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 +501,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 +606,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 +700,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); + } } } @@ -979,5 +987,19 @@ namespace slskd.Transfers.Uploads return (host, filename, length); } + + private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default) + { + semaphore.Wait(cancellationToken); + + try + { + Update(transfer); + } + finally + { + semaphore.Release(); + } + } } }
\ No newline at end of file |
