diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Common/CommonExtensions.cs | 19 | ||||
| -rw-r--r-- | src/slskd/Core/API/Controllers/ApplicationController.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Relay/RelayClient.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Search/SearchService.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Shares/ShareScanner.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 23 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadService.cs | 2 |
8 files changed, 43 insertions, 15 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 461a5fef..208de9e1 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -128,7 +128,7 @@ namespace slskd Console.CancelKeyPress += (_, args) => { ShuttingDown = true; - Program.MasterCancellationTokenSource.Cancel(); + Program.MasterCancellationTokenSource.Cancel(swallowObjectDisposedException: true); Log.Warning("Received SIGINT"); }; @@ -137,7 +137,7 @@ namespace slskd PosixSignals.Add(PosixSignalRegistration.Create(signal, context => { ShuttingDown = true; - Program.MasterCancellationTokenSource.Cancel(); + Program.MasterCancellationTokenSource.Cancel(swallowObjectDisposedException: true); Log.Fatal("Received {Signal}", signal); Environment.Exit(1); })); diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 47e4aee1..5affdf5c 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -231,6 +231,25 @@ namespace slskd } /// <summary> + /// Safely cancels this <see cref="CancellationTokenSource"/> without throwing if it is disposed. + /// </summary> + /// <param name="cts">The CancellationTokenSource instance.</param> + /// <param name="swallowObjectDisposedException">A value indicating whether to swallow ObjectDisposedException, if it occurs.</param> + /// <returns>A value indicating whether the cancellation completed successfully.</returns> + public static bool Cancel(this CancellationTokenSource cts, bool swallowObjectDisposedException) + { + try + { + cts.Cancel(); + return true; + } + catch (ObjectDisposedException) when (swallowObjectDisposedException) + { + return false; + } + } + + /// <summary> /// Recursively retrieves all properties. /// </summary> /// <param name="type">The type from which to retrieve properties.</param> diff --git a/src/slskd/Core/API/Controllers/ApplicationController.cs b/src/slskd/Core/API/Controllers/ApplicationController.cs index e015e612..09d9eda2 100644 --- a/src/slskd/Core/API/Controllers/ApplicationController.cs +++ b/src/slskd/Core/API/Controllers/ApplicationController.cs @@ -94,7 +94,7 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.JwtOnly, Roles = AuthRole.AdministratorOnly)] public IActionResult Shutdown() { - Program.MasterCancellationTokenSource.Cancel(); + Program.MasterCancellationTokenSource.Cancel(swallowObjectDisposedException: true); Lifetime.StopApplication(); Task.Run(async () => @@ -114,7 +114,7 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.JwtOnly, Roles = AuthRole.AdministratorOnly)] public IActionResult Restart() { - Program.MasterCancellationTokenSource.Cancel(); + Program.MasterCancellationTokenSource.Cancel(swallowObjectDisposedException: true); Process.Start(Process.GetCurrentProcess().MainModule.FileName, Environment.CommandLine); Lifetime.StopApplication(); diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index cbcde3c4..49935b4c 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -279,7 +279,7 @@ namespace slskd.Relay // if the client is attempting a connection, cancel it it's going to be dropped when we create a new instance, but // we need the retry loop around connection to stop. - StartCancellationTokenSource?.Cancel(); + StartCancellationTokenSource?.Cancel(swallowObjectDisposedException: true); HubConnection = new HubConnectionBuilder() .WithUrl($"{options.Relay.Controller.Address.TrimEnd('/')}/hub/relay", builder => diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 8b107084..ec45bb5c 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -416,7 +416,7 @@ namespace slskd.Search { if (CancellationTokens.TryGetValue(id, out var cts)) { - cts.Cancel(); + cts.Cancel(swallowObjectDisposedException: true); return true; } diff --git a/src/slskd/Shares/ShareScanner.cs b/src/slskd/Shares/ShareScanner.cs index 98a3f092..7ae1aa4e 100644 --- a/src/slskd/Shares/ShareScanner.cs +++ b/src/slskd/Shares/ShareScanner.cs @@ -457,7 +457,7 @@ namespace slskd.Shares { if (CancellationTokenSource != null) { - CancellationTokenSource.Cancel(); + CancellationTokenSource.Cancel(swallowObjectDisposedException: true); return true; } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 5a5fe699..43a9d17c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -195,7 +195,8 @@ namespace slskd.Transfers.Downloads FileService fileService, IRelayService relayService, IFTPService ftpClient, - EventBus eventBus) + EventBus eventBus, + TimeProvider timeProvider = null) { Batches = batchService; Searches = searchService; @@ -207,6 +208,8 @@ namespace slskd.Transfers.Downloads Relay = relayService; EventBus = eventBus; + TimeProvider = timeProvider ?? TimeProvider.System; + Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics()); } @@ -245,6 +248,7 @@ namespace slskd.Transfers.Downloads private IOptionsMonitor<Options> OptionsMonitor { get; } private EventBus EventBus { get; } private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\$\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private TimeProvider TimeProvider { get; } /// <summary> /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they @@ -505,6 +509,7 @@ namespace slskd.Transfers.Downloads 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 + 5. the DownloadAsync() method throws 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 @@ -545,17 +550,16 @@ namespace slskd.Transfers.Downloads TransferStates state = TransferStates.None; // satisfies condition #4; remote user doesn't respond after a really long time - using var timeoutCts = new CancellationTokenSource(maxTimeToWaitForEnqueueRequestAck); + using var timeoutCts = new CancellationTokenSource(delay: maxTimeToWaitForEnqueueRequestAck, timeProvider: TimeProvider); timeoutCts.Token.Register(() => { + // note: disposed once we leave the try block, so registration doesn't fire unless it actually times out 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")); - // cancel the download attempt so that it doesn't keep running and cause the internal + // cancel the download attempt so that it doesn't keep running (within Soulseek.NET) and cause the internal // state of slskd to diverge from the internal state of Soulseek.NET. - // the transfer record is recorded as being cancelled when this happens and there's not - // an easy/good way to stop it. - cts.Cancel(); + cts.Cancel(swallowObjectDisposedException: true); }); // satisfies conditions #1 and #2 @@ -599,6 +603,10 @@ namespace slskd.Transfers.Downloads Log.Error(ex, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, ex.Message); + // trip the TCS if DownloadAsync() throws before any of the other conditions trip it + // this is harmless if it has already been tripped + enqueuedTcs.TrySetException(ex); + if (!TryFail(transferId, exception: ex)) { Log.Error(ex, "Failed to clean up transfer {Id} after failed download", transferId); @@ -616,6 +624,7 @@ namespace slskd.Transfers.Downloads 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 + 5. the DownloadAsync() method throws */ await enqueuedTcs.Task; @@ -1008,7 +1017,7 @@ namespace slskd.Transfers.Downloads // of the transfer to Cancelled. _should_! if (CancellationTokens.TryRemove(id, out var cts)) { - cts.Cancel(); + cts.Cancel(swallowObjectDisposedException: true); return true; } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 05251ecf..246f4b31 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -970,7 +970,7 @@ namespace slskd.Transfers.Uploads { if (CancellationTokens.TryRemove(id, out var cts)) { - cts.Cancel(); + cts.Cancel(swallowObjectDisposedException: true); return true; } |
