diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-10-20 09:08:56 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2025-10-20 09:08:56 -0500 |
| commit | 6bcc23c1856f9878509c940cc37b5d4fdb90e2d4 (patch) | |
| tree | 0574d0032b475f1e0204c724ecdc5f46fac11a55 /src | |
| parent | 75ad65dbed0333fd6bd0441a5599527c539366e0 (diff) | |
| parent | 0a15a71028c2a12795023550f28d416dd050763d (diff) | |
| download | slskd-6bcc23c1856f9878509c940cc37b5d4fdb90e2d4.tar.gz | |
Merge remote-tracking branch 'origin' into download-records
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Files/FileService.cs | 19 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 29 | ||||
| -rw-r--r-- | src/slskd/Search/API/Controllers/SearchesController.cs | 50 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/Controllers/TransfersController.cs | 22 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 381 |
5 files changed, 335 insertions, 166 deletions
diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index a07bd051..e4adc7e7 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -379,6 +379,7 @@ namespace slskd.Files /// </remarks> /// <param name="sourceFilename">The fully qualified filename of the file to move.</param> /// <param name="destinationDirectory">The fully qualified directory to which to move the source file.</param> + /// <param name="unixFileMode">An optional Unix file mode to apply to the destination file.</param> /// <param name="overwrite">An optional value indicating whether the destination file should be overwritten if it already exists.</param> /// <param name="deleteSourceDirectoryIfEmptyAfterMove"> /// An optional value indicating whether the parent directory of the source file should be deleted if it is empty after the move. @@ -387,7 +388,7 @@ namespace slskd.Files /// <exception cref="ArgumentNullException">Thrown if either of the specified file or directories are null or contain only whitespace.</exception> /// <exception cref="FileNotFoundException">Thrown if the specified <paramref name="sourceFilename"/> does not exist.</exception> /// <exception cref="IOException">Thrown if the file can't be moved, or the <paramref name="deleteSourceDirectoryIfEmptyAfterMove"/> option is set and the operation fails.</exception> - public virtual string MoveFile(string sourceFilename, string destinationDirectory, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false) + public virtual string MoveFile(string sourceFilename, string destinationDirectory, UnixFileMode? unixFileMode = null, bool overwrite = false, bool deleteSourceDirectoryIfEmptyAfterMove = false) { ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); @@ -425,6 +426,22 @@ namespace slskd.Files Log.Debug("Successfully moved {Source} to {Destination}", sourceFilename, destinationFilename); + // attempting to use UnixCreateMode on Windows raises an Exception + // we *MUST* check the OS and skip this on Windows + if (!OperatingSystem.IsWindows()) + { + var appOption = OptionsMonitor.CurrentValue.Permissions.File.Mode; + var mode = unixFileMode ?? appOption?.ToUnixFileMode(); + + // if options haven't been passed in and none have been set in app config, omit this + // so that the application's umask will be applied, saving users the hassle of setting it twice. + if (mode.HasValue) + { + File.SetUnixFileMode(destinationFilename, mode.Value); + Log.Debug("Successfully set Unix file mode to {Mode}", mode); + } + } + // if the parent directory is empty after the move, delete it if (deleteSourceDirectoryIfEmptyAfterMove && !Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) { diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 350f1354..bf0428d7 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -23,6 +23,8 @@ namespace slskd using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; + using System.Diagnostics; + using System.IO; using System.Linq; using System.Net; @@ -236,6 +238,7 @@ namespace slskd private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); private static ILogger Log { get; set; } = new ConsoleWriteLineLogger(); private static Mutex Mutex { get; } = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName)); + private static IDisposable DotNetRuntimeStats { get; set; } [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } @@ -591,6 +594,7 @@ namespace slskd maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots, minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(), + maximumConcurrentSearches: 2, raiseEventsAsynchronously: true))); // add the core application service to DI as well as a hosted service so that other services can @@ -703,8 +707,10 @@ namespace slskd .AllowCredentials() .WithExposedHeaders("X-URL-Base", "X-Total-Count"))); + // note: don't dispose this (or let it be disposed) or some of the stats, like those related + // to the thread pool won't work + DotNetRuntimeStats = DotNetRuntimeStatsBuilder.Default().StartCollecting(); services.AddSystemMetrics(); - using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); @@ -1133,6 +1139,27 @@ namespace slskd } })) .CreateLogger(); + + // // occurs when a faulted task's unobserved exception is about to trigger exception escalation policy, which, by default, would terminate the process. + // TaskScheduler.UnobservedTaskException += (sender, e) => + // { + // Serilog.Log.Logger.Error(e.Exception, "Unobserved exception: {Message}", e.Exception.Message); + // e.SetObserved(); + // }; + + AppDomain.CurrentDomain.UnhandledException += (sender, e) => + { + var exception = e.ExceptionObject as Exception; + + if (e.IsTerminating) + { + Serilog.Log.Logger.Fatal(exception, "Unhandled fatal exception: {Message}", e.IsTerminating); + } + else + { + Serilog.Log.Logger.Error(exception, "Unhandled exception: {Message}", exception.Message); + } + }; } private static IConfigurationBuilder AddConfigurationProviders(this IConfigurationBuilder builder, string environmentVariablePrefix, string configurationFile, bool reloadOnChange) diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index 1d00b482..c51d537e 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -20,6 +20,7 @@ using Microsoft.Extensions.Options; namespace slskd.Search.API { using System; + using System.Threading; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -49,6 +50,7 @@ namespace slskd.Search.API OptionsSnapshot = optionsSnapshot; } + private static SemaphoreSlim SearchRequestLimiter { get; } = new SemaphoreSlim(1, 1); private ISearchService Searches { get; } private IOptionsSnapshot<Options> OptionsSnapshot { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext<SearchesController>(); @@ -75,29 +77,41 @@ namespace slskd.Search.API return BadRequest("SearchText may not be null or empty"); } - var id = request.Id ?? Guid.NewGuid(); - - Search search; - - try + if (!SearchRequestLimiter.Wait(0)) { - search = await Searches.StartAsync(id, SearchQuery.FromText(request.SearchText), SearchScope.Network, request.ToSearchOptions()); - return Ok(search); + return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); } - catch (Exception ex) when (ex is ArgumentException || ex is Soulseek.DuplicateTokenException) - { - Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); - return BadRequest(ex.Message); - } - catch (InvalidOperationException ex) + + try { - Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); - return Conflict(ex.Message); + var id = request.Id ?? Guid.NewGuid(); + + Search search; + + try + { + search = await Searches.StartAsync(id, SearchQuery.FromText(request.SearchText), SearchScope.Network, request.ToSearchOptions()); + return Ok(search); + } + catch (Exception ex) when (ex is ArgumentException || ex is Soulseek.DuplicateTokenException) + { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); + return BadRequest(ex.Message); + } + catch (InvalidOperationException ex) + { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); + return Conflict(ex.Message); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); + return StatusCode(500, ex.Message); + } } - catch (Exception ex) + finally { - Log.Error(ex, "Failed to execute search {Search}: {Message}", request, ex.Message); - return StatusCode(500, ex.Message); + SearchRequestLimiter.Release(); } } diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index fdbca1dc..f38c4b87 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(1, 1); 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,36 @@ 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))); + await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)), cancellationToken); return StatusCode(201); } 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 57a6ff37..015ec384 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -200,6 +200,16 @@ namespace slskd.Transfers.Downloads /// <exception cref="DuplicateTransferException">Thrown if a download matching the username and filename is already tracked by Soulseek.NET.</exception> public async Task<Transfer> DownloadAsync(Transfer transfer, Action<Transfer> 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); @@ -207,8 +217,8 @@ namespace slskd.Transfers.Downloads if (!Locks.TryAdd(lockName, true)) { - Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); - return null; + 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"); } /* @@ -248,8 +258,6 @@ namespace slskd.Transfers.Downloads throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered"); } - Log.Information("Initializing download of {Filename} from {Username}", transfer.Filename, transfer.Username); - using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); var topts = new TransferOptions( @@ -325,6 +333,12 @@ namespace slskd.Transfers.Downloads // 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; + + Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); + var completedTransfer = await Client.DownloadAsync( username: transfer.Username, remoteFilename: transfer.Filename, @@ -336,9 +350,7 @@ namespace slskd.Transfers.Downloads 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, + UnixCreateMode = unixFileMode, })), size: transfer.Size, startOffset: 0, @@ -346,6 +358,8 @@ namespace slskd.Transfers.Downloads cancellationToken: cts.Token, 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 // flushe any pending update, _probably_ pushing the state of the transfer back to InProgress rateLimiter.Dispose(); @@ -357,61 +371,81 @@ namespace slskd.Transfers.Downloads // 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 to {Destination}", finalFilename); + Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); - // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, - // and the file has been moved from the incomplete directory to the downloads directory if (OptionsMonitor.CurrentValue.Relay.Enabled) { _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); } - EventBus.Raise(new DownloadFileCompleteEvent - { - Timestamp = transfer.EndedAt.Value, - LocalFilename = finalFilename, - RemoteFilename = transfer.Filename, - Transfer = transfer, - }); - - // try to figure out if this file is the last of a directory, and if so, raise the associated - // event. this can be tricky because we want to be sure that this is the last file in this specific - // directory, excluding any pending downloads in a subdirectory. - var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); - var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); - var pendingDownloadsInDirectory = Client.Downloads - .Where(t => t.Username == transfer.Username) - .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); - - if (!pendingDownloadsInDirectory.Any()) + try { - EventBus.Raise(new DownloadDirectoryCompleteEvent + // 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, - Username = transfer.Username, - LocalDirectoryName = destinationDirectory, - RemoteDirectoryName = remoteDirectoryName, + LocalFilename = finalFilename, + RemoteFilename = transfer.Filename, + Transfer = transfer, }); - } - if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) + // 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) { - _ = FTP.UploadAsync(finalFilename); + // 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; @@ -443,17 +477,20 @@ namespace slskd.Transfers.Downloads } 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); - throw; } } } @@ -487,6 +524,8 @@ namespace slskd.Transfers.Downloads 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. @@ -498,6 +537,18 @@ namespace slskd.Transfers.Downloads 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<string> acquiredLocks = []; List<Transfer> enqueued = []; List<Transfer> failed = []; @@ -527,6 +578,8 @@ namespace slskd.Transfers.Downloads */ foreach (var file in files) { + cancellationToken.ThrowIfCancellationRequested(); + var transfer = new Transfer() { Id = Guid.NewGuid(), @@ -555,7 +608,7 @@ namespace slskd.Transfers.Downloads acquiredLocks.Add(lockName); Log.Debug("Acquired lock {LockName}", lockName); - Log.Information("Download of {Filename} from {Username} requested", 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 @@ -578,6 +631,7 @@ namespace slskd.Transfers.Downloads 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)) { @@ -588,7 +642,7 @@ namespace slskd.Transfers.Downloads enqueued.Add(transfer); - Log.Information("Successfully enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transfer.Id); + Log.Information("Successfully locally enqueued download of {Filename} from {Username}", file.Filename, username, transfer.Id); } catch (Exception ex) { @@ -605,26 +659,18 @@ namespace slskd.Transfers.Downloads 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); } - // 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 - { - await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message); - throw; - } - /* 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 */ - _ = Task.Run(async () => + Log.Debug("Scheduling batch remote enqueue Task for {Count} files from {Username}", enqueued.Count, username); + + var batchEnqueueTask = Task.Run(async () => { /* enqueue each of the specified files, waiting to ensure that the remote client has responded to our @@ -646,125 +692,94 @@ namespace slskd.Transfers.Downloads var semaphore = new SemaphoreSlim(initialCount: concurrentRequests, maxCount: concurrentRequests); + Log.Debug("Scheduling Tasks to download {Count} files from {Username}", enqueued.Count, username); + var tasks = enqueued.Select(async transfer => { + Log.Debug("Awaiting download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); await semaphore.WaitAsync(); try { Log.Debug("Acquired download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username); - try - { - var enqueuedTcs = new TaskCompletionSource<Transfer>(); - List<string> transitions = []; + var enqueuedTcs = new TaskCompletionSource<Transfer>(); + List<string> transitions = []; + TransferStates state = TransferStates.None; - // set a hard limit on the time we are willing to wait for the remote client to confirm or reject - // the enqueue of the file. we have to do this so that we don't get stuck indefinitely - using var timeoutCts = new CancellationTokenSource(maxTimeToWaitForTransferAck); - timeoutCts.Token.Register(() => + // set a hard limit on the time we are willing to wait for the remote client to confirm or reject + // the enqueue of the file. we have to do this so that we don't get stuck indefinitely + using var timeoutCts = new CancellationTokenSource(maxTimeToWaitForTransferAck); + timeoutCts.Token.Register(() => + { + if (!enqueuedTcs.Task.IsCompleted) { - if (!enqueuedTcs.Task.IsCompleted) - { - Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit. State transition history: {History}", transfer.Filename, username, string.Join(", ", transitions)); - enqueuedTcs.TrySetException(new TimeoutException("Download failed to enqueue remotely after hard time limit")); - } - }); + Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit. State transition history: {History}", transfer.Filename, username, string.Join(", ", transitions)); + enqueuedTcs.TrySetException(new TimeoutException("Download failed to enqueue remotely after hard time limit")); + } + }); - void stateChanged(Transfer transfer) + void stateChanged(Transfer transfer) + { + state = transfer.State; + transitions.Add(transfer.State.ToString()); + + // _contractually_ (covered by unit tests!) all downloads will at some point enter the Queued | Remotely state + // there _should be_ no way we can get hung up here, but if we do, also check for Completed as a backstop + if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely)) { - transitions.Add(transfer.State.ToString()); + enqueuedTcs.TrySetResult(transfer); + } - // _contractually_ (covered by unit tests!) all downloads will at some point enter the Queued | Remotely state - // there _should be_ no way we can get hung up here, but if we do, also check for Completed as a backstop - if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely)) + // if something goes wrong and we never get to enqueued, trip the result when we transition into + // completed, so we don't get stuck. we shouldn't take this to mean we were successful, we're just + // trying to ensure we don't get stuck + if (transfer.State.HasFlag(TransferStates.Completed)) + { + if (transfer.State.HasFlag(TransferStates.Succeeded)) { enqueuedTcs.TrySetResult(transfer); } - - // if something goes wrong and we never get to enqueued, trip the result when we transition into - // completed, so we don't get stuck. we shouldn't take this to mean we were successful, we're just - // trying to ensure we don't get stuck - if (transfer.State.HasFlag(TransferStates.Completed)) + else { - if (transfer.State.HasFlag(TransferStates.Succeeded)) - { - enqueuedTcs.TrySetResult(transfer); - } - else - { - enqueuedTcs.TrySetException(new TransferException(transfer.Exception)); - } + enqueuedTcs.TrySetException(new TransferException(transfer.Exception)); } } + } - // enqueue the file. this call will return when the record has been inserted and the download task - // kicked off. the stateChanged delegate will be passed down to the download task, which will eventually trip it - _ = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken)).ContinueWith(task => - { - if (task.IsCompletedSuccessfully) - { - Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); - return; - } - - /* - things that can cause us to arrive here: + Log.Debug("Scheduling Task for download of {Filename} from {Username}", transfer.Filename, transfer.Username); - * transfer record deleted somehow - * transfer record updated so that it's no longer in Queued | Locally - * Soulseek.NET already tracking an identical download (slskd <> Soulseek.NET desync) - */ - Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", transfer.Filename, transfer.Username, task.Exception.Message); + // enqueue the file. this call will return when the record has been inserted and the download task + // kicked off. the stateChanged delegate will be passed down to the download task, which will eventually trip it + var downloadTask = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken)).ContinueWith(task => + { + if (task.IsCompletedSuccessfully) + { + Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username); + return; + } - try - { - var foundTransfer = Find(t => t.Id == transfer.Id); + /* + things that can cause us to arrive here: - if (transfer is not null) - { - transfer.EndedAt ??= DateTime.UtcNow; - transfer.Exception ??= task.Exception.InnerException.Message; - - if (!transfer.State.HasFlag(TransferStates.Completed)) - { - transfer.State = TransferStates.Completed | task.Exception.InnerException switch - { - OperationCanceledException => TransferStates.Cancelled, - TimeoutException => TransferStates.TimedOut, - _ => TransferStates.Errored, - }; - } - - Update(transfer); - } - } - catch (Exception ex) - { - Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message); - } - }, cancellationToken); - - // wait for the download to either enter the Queued | Remotely or Completed states, or for the hard limit - // timeout to trip and set an exception - await enqueuedTcs.Task; - } - catch (Exception ex) - { - Log.Error(ex, "Failed to download {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); + * transfer record deleted somehow + * transfer record updated so that it's no longer in Queued | Locally + * Soulseek.NET already tracking an identical download (slskd <> Soulseek.NET desync) + */ + Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", transfer.Filename, transfer.Username, task.Exception.Message); try { - var transferRecord = Find(t => t.Id == transfer.Id); + var foundTransfer = Find(t => t.Id == transfer.Id); - if (transfer is not null) + if (foundTransfer is not null) { - transfer.EndedAt ??= DateTime.UtcNow; - transfer.Exception ??= ex.Message; + foundTransfer.EndedAt ??= DateTime.UtcNow; + foundTransfer.Exception ??= task.Exception.InnerException.Message; - if (!transfer.State.HasFlag(TransferStates.Completed)) + if (!foundTransfer.State.HasFlag(TransferStates.Completed)) { - transfer.State = TransferStates.Completed | ex switch + foundTransfer.State = TransferStates.Completed | task.Exception.InnerException switch { OperationCanceledException => TransferStates.Cancelled, TimeoutException => TransferStates.TimedOut, @@ -772,13 +787,64 @@ namespace slskd.Transfers.Downloads }; } - Update(transfer); + Update(foundTransfer); } } - catch (Exception innerEx) + catch (Exception ex) { - Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); + Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message); } + }, cancellationToken); + + if (downloadTask.Status == TaskStatus.Canceled) + { + throw new OperationCanceledException($"The download Task for {transfer.Filename} from {transfer.Username} was cancelled"); + } + + if (downloadTask.Status == TaskStatus.Faulted) + { + throw new Exception($"The download Task for {transfer.Filename} from {transfer.Username} faulted: {downloadTask.Exception}", downloadTask.Exception); + } + + Log.Debug("Download Task status: {Status}", downloadTask.Status); + + Log.Debug("Waiting for download of {Filename} from {Username} to transition into {State}", transfer.Filename, transfer.Username, TransferStates.Queued | TransferStates.Remotely); + + // wait for the download to either enter the Queued | Remotely or Completed states, or for the hard limit + // timeout to trip and set an exception + 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, "Failed to download {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); + + try + { + var foundTransfer = Find(t => t.Id == transfer.Id); + + if (foundTransfer is not null) + { + foundTransfer.EndedAt ??= DateTime.UtcNow; + foundTransfer.Exception ??= ex.Message; + + if (!foundTransfer.State.HasFlag(TransferStates.Completed)) + { + foundTransfer.State = TransferStates.Completed | ex switch + { + OperationCanceledException => TransferStates.Cancelled, + TimeoutException => TransferStates.TimedOut, + _ => TransferStates.Errored, + }; + } + + Update(transfer); + } + } + catch (Exception innerEx) + { + Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message); } } finally @@ -788,29 +854,56 @@ namespace slskd.Transfers.Downloads } }); + 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.Warning("Task for enqueue of {Count} files from {Username} completed successfully", files.Count(), username); + Log.Information("Task for batch enqueue of {Count} files from {Username} completed successfully", files.Count(), username); return; } - Log.Error(task.Exception, "Task for enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message); + 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); } } |
