From f3cbc0328772786c85f47ba0c7b25f2e91b1b257 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jun 2025 17:43:44 -0500 Subject: use the connection watchdog to connect via API; leverage auto retries --- src/slskd/Core/API/Controllers/ServerController.cs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/ServerController.cs b/src/slskd/Core/API/Controllers/ServerController.cs index 9b8e2764..cfc695a0 100644 --- a/src/slskd/Core/API/Controllers/ServerController.cs +++ b/src/slskd/Core/API/Controllers/ServerController.cs @@ -19,7 +19,6 @@ using Microsoft.Extensions.Options; namespace slskd.Core.API { - using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -37,15 +36,18 @@ namespace slskd.Core.API { public ServerController( ISoulseekClient soulseekClient, + IConnectionWatchdog connectionWatchdog, IOptionsSnapshot optionsSnapshot, IStateSnapshot stateSnapshot) { Client = soulseekClient; + ConnectionWatchdog = connectionWatchdog; OptionsSnapshot = optionsSnapshot; StateSnapshot = stateSnapshot; } private ISoulseekClient Client { get; } + private IConnectionWatchdog ConnectionWatchdog { get; } private IOptionsSnapshot OptionsSnapshot { get; } private IStateSnapshot StateSnapshot { get; } @@ -58,22 +60,17 @@ namespace slskd.Core.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(403)] - public async Task Connect() + public IActionResult Connect() { if (Program.IsRelayAgent) { return Forbid(); } - if (!Client.State.HasFlag(SoulseekClientStates.Connected)) + // we use the watchdog here so that we get the correct auto-reconnect behavior + if (!ConnectionWatchdog.IsEnabled) { - var opt = OptionsSnapshot.Value.Soulseek; - - await Client.ConnectAsync( - address: opt.Address, - port: opt.Port, - username: opt.Username, - password: opt.Password); + ConnectionWatchdog.Start(); } return Ok(); @@ -98,6 +95,8 @@ namespace slskd.Core.API if (Client.State.HasFlag(SoulseekClientStates.Connected)) { + // the IntentionalDisconnectException is used to indicate that the disconnect was intentional, which + // prevents the watchdog from trying to reconnect Client.Disconnect(message, new IntentionalDisconnectException(message)); } -- cgit v1.2.3 From c629f2930a30335a90e31b73fcd2bdaebf903d54 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jun 2025 17:43:58 -0500 Subject: clarify design --- src/slskd/Core/ConnectionWatchdog.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 4ffc58e0..d7c7838c 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -57,6 +57,10 @@ namespace slskd /// /// Monitors the connection to the Soulseek network and reconnects with exponential backoff, if necessary. /// + /// + /// This class is intended to be Started either at application startup or when the connection is disconnected, and + /// stopped when the application is connected again; it doesn't "run" all the time. + /// public class ConnectionWatchdog : IConnectionWatchdog { private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes -- cgit v1.2.3 From 364c2200c4bd1953077714e151b47fbc6faae9eb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 19 Jun 2025 12:26:41 -0500 Subject: add the ability to abort a reconnect when stopping --- src/slskd/Core/ConnectionWatchdog.cs | 49 +++++++++++++++++++++++++++++------- 1 file changed, 40 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index d7c7838c..494be488 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -33,6 +33,10 @@ namespace slskd /// /// Gets a value indicating whether the watchdog is monitoring the server connection. /// + /// + /// Generally true when the application *SHOULD* be connected to the server, but isn't. + /// Otherwise false (e.g. when connected). + /// bool IsEnabled { get; } /// @@ -50,8 +54,9 @@ namespace slskd /// /// Stops monitoring the server connection. /// + /// A value indicating whether to abort an ongoing reconnect attempt. /// This should be called when the application is reasonably certain that the connection is connected. - void Stop(); + void Stop(bool abortReconnect = false); } /// @@ -102,6 +107,7 @@ namespace slskd private IStateMonitor State { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private System.Timers.Timer WatchdogTimer { get; } + private CancellationTokenSource CancellationTokenSource { get; set; } /// /// Disposes this instance. @@ -135,8 +141,21 @@ namespace slskd /// /// Stops monitoring the server connection. /// + /// A value indicating whether to abort an ongoing reconnect attempt. /// This should be called when the application is reasonably certain that the connection is connected. - public void Stop() => WatchdogTimer.Enabled = false; + public void Stop(bool abortReconnect = false) + { + WatchdogTimer.Enabled = false; + + // note: the connect event fires before the connection logic is complete, so there is a chain of events + // that leads to the application being connected and then immediately disconnected if this CTS is cancelled + // when the watchdog is stopped due to sucessful connection. pass the cancelReconnect flag only when the user + // wants to abort the reconnect logic. + if (abortReconnect) + { + CancellationTokenSource?.Cancel(); + } + } /// /// Disposes this instance. @@ -149,6 +168,7 @@ namespace slskd if (disposing) { WatchdogTimer?.Dispose(); + CancellationTokenSource?.Dispose(); } Disposed = true; @@ -157,17 +177,24 @@ namespace slskd private async Task AttemptReconnect(int attempts = 1) { + // semaphore is obtained here and released only when the reconnect attempt is complete, so + // one and only one invocation of this can run at a time if (await SyncRoot.WaitAsync(0)) { try { - if (State.CurrentValue.Server.IsConnected) + // go until we connect and break, or something stops the watchdog + while (IsEnabled) { - return; - } + // bail out if we're already connected. it's possible that something else outside of the watchdog + // connects the client. highly unlikely but that might change if someone inadvertently adds some logic. + if (State.CurrentValue.Server.IsConnected) + { + return; + } + + CancellationTokenSource = new CancellationTokenSource(); - while (true) - { if (attempts > 0) { var (delay, jitter) = Compute.ExponentialBackoffDelay( @@ -176,7 +203,7 @@ namespace slskd var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before attempting to reconnect"); - await Task.Delay(delay + jitter); + await Task.Delay(delay + jitter, cancellationToken: CancellationTokenSource.Token); Log.Information("Attempting to reconnect to the Soulseek server (#{Attempts})...", attempts); } @@ -192,11 +219,14 @@ namespace slskd // the changes will take effect now. var opt = Options.CurrentValue.Soulseek; + // note: cancelling the CTS before the connect logic is fully complete (e.g. reacting to the connect event) + // will cause the client to connect, then disconnect immediately await Client.ConnectAsync( address: opt.Address, port: opt.Port, username: opt.Username, - password: opt.Password); + password: opt.Password, + cancellationToken: CancellationTokenSource.Token); break; } @@ -209,6 +239,7 @@ namespace slskd } finally { + CancellationTokenSource?.Dispose(); SyncRoot.Release(); } } -- cgit v1.2.3 From 5623053911f10b68d73fc38c9d0cc89f0ce81488 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 19 Jun 2025 12:27:07 -0500 Subject: abort reconnect when stopping via API --- src/slskd/Core/API/Controllers/ServerController.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/ServerController.cs b/src/slskd/Core/API/Controllers/ServerController.cs index cfc695a0..aceaeec9 100644 --- a/src/slskd/Core/API/Controllers/ServerController.cs +++ b/src/slskd/Core/API/Controllers/ServerController.cs @@ -93,6 +93,9 @@ namespace slskd.Core.API return Forbid(); } + // stop the watchdog so that it will exit any retry logic + ConnectionWatchdog.Stop(abortReconnect: true); + if (Client.State.HasFlag(SoulseekClientStates.Connected)) { // the IntentionalDisconnectException is used to indicate that the disconnect was intentional, which -- cgit v1.2.3 From 50f76dc8541dedac6ad9dff055cab809e2f33543 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:46:50 -0500 Subject: remove interface --- src/slskd/Core/ConnectionWatchdog.cs | 40 +++--------------------------------- 1 file changed, 3 insertions(+), 37 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 494be488..f8461033 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -25,40 +25,6 @@ namespace slskd using Serilog; using Soulseek; - /// - /// Monitors the connection to the Soulseek server and reconnects with exponential backoff, if necessary. - /// - public interface IConnectionWatchdog : IDisposable - { - /// - /// Gets a value indicating whether the watchdog is monitoring the server connection. - /// - /// - /// Generally true when the application *SHOULD* be connected to the server, but isn't. - /// Otherwise false (e.g. when connected). - /// - bool IsEnabled { get; } - - /// - /// Initializes the watchdog and makes the initial connection to the server. - /// - /// This should be called at application startup. - void Start(); - - /// - /// Starts monitoring the server connection following a disconnect. - /// - /// This should be called when the connection is disconnected. - void Restart(); - - /// - /// Stops monitoring the server connection. - /// - /// A value indicating whether to abort an ongoing reconnect attempt. - /// This should be called when the application is reasonably certain that the connection is connected. - void Stop(bool abortReconnect = false); - } - /// /// Monitors the connection to the Soulseek network and reconnects with exponential backoff, if necessary. /// @@ -66,7 +32,7 @@ namespace slskd /// This class is intended to be Started either at application startup or when the connection is disconnected, and /// stopped when the application is connected again; it doesn't "run" all the time. /// - public class ConnectionWatchdog : IConnectionWatchdog + public class ConnectionWatchdog { private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes @@ -122,7 +88,7 @@ namespace slskd /// Initializes the watchdog and makes the initial connection to the server. /// /// This should be called at application startup. - public void Start() + public virtual void Start() { WatchdogTimer.Enabled = true; _ = AttemptReconnect(attempts: 0); @@ -143,7 +109,7 @@ namespace slskd /// /// A value indicating whether to abort an ongoing reconnect attempt. /// This should be called when the application is reasonably certain that the connection is connected. - public void Stop(bool abortReconnect = false) + public virtual void Stop(bool abortReconnect = false) { WatchdogTimer.Enabled = false; -- cgit v1.2.3 From bab00cb022cc8d50e84e4e8bec40b92b7f60983a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:47:30 -0500 Subject: reset on option changes --- src/slskd/Core/ConnectionWatchdog.cs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index f8461033..a598ff7a 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -48,7 +48,7 @@ namespace slskd IStateMonitor state) { Client = soulseekClient; - Options = optionsMonitor; + OptionsMonitor = optionsMonitor; State = state; WatchdogTimer = new System.Timers.Timer() @@ -59,6 +59,8 @@ namespace slskd }; WatchdogTimer.Elapsed += (sender, args) => _ = AttemptReconnect(); + + OptionsMonitor.OnChange(options => OptionsChanged(options)); } /// @@ -69,7 +71,7 @@ namespace slskd private ISoulseekClient Client { get; } private bool Disposed { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private IOptionsMonitor Options { get; set; } + private IOptionsMonitor OptionsMonitor { get; set; } private IStateMonitor State { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); private System.Timers.Timer WatchdogTimer { get; } @@ -141,6 +143,17 @@ namespace slskd } } + private void OptionsChanged(Options options) + { + // it's possible that a user begins changing connection settings in an attempt to get the client to connect + // if they edit the options _at all_, assume this is the case and restart the retry loop from the beginning + if (IsEnabled) + { + Log.Information("Options changed, restarting (re)connection process..."); + Restart(); + } + } + private async Task AttemptReconnect(int attempts = 1) { // semaphore is obtained here and released only when the reconnect attempt is complete, so -- cgit v1.2.3 From 187510e6418a500fbf99ff0765ef2794100bf06a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:48:27 -0500 Subject: trap cancellation exceptions --- src/slskd/Core/ConnectionWatchdog.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index a598ff7a..9964514b 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -209,6 +209,12 @@ namespace slskd break; } + catch (Exception ex) when (ex is TaskCanceledException || ex is OperationCanceledException) + { + Log.Information("Reconnection attempt cancelled"); + Log.Debug(ex, "ConnectAsync() threw {Exception}", ex); + return; + } catch (Exception ex) { attempts++; @@ -216,6 +222,15 @@ namespace slskd } } } + catch (Exception ex) when (ex is TaskCanceledException || ex is OperationCanceledException) + { + Log.Information("Reconnection attempt cancelled"); + Log.Debug(ex, "Reconnect logic threw {Exception}", ex); + } + catch (Exception ex) + { + Log.Warning(ex, "Reconnect attempt failed: {Message}", ex.Message); + } finally { CancellationTokenSource?.Dispose(); -- cgit v1.2.3 From 3ccc23f23d8604674690db1996c0922e2e255180 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:48:44 -0500 Subject: prevent throwing during finalization --- src/slskd/Core/ConnectionWatchdog.cs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 9964514b..5001f024 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -233,7 +233,18 @@ namespace slskd } finally { - CancellationTokenSource?.Dispose(); + var cts = CancellationTokenSource; + CancellationTokenSource = null; + + try + { + cts?.Dispose(); + } + catch (Exception) + { + // noop. i don't think this can throw, but if we fail to release the SyncRoot we'll be in trouble. + } + SyncRoot.Release(); } } -- cgit v1.2.3 From e5aad77d9d467620d5ffa3cce041f33bb1d1af9a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:50:17 -0500 Subject: docs --- src/slskd/Core/ConnectionWatchdog.cs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 5001f024..819d9a49 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -29,8 +29,9 @@ namespace slskd /// Monitors the connection to the Soulseek network and reconnects with exponential backoff, if necessary. /// /// - /// This class is intended to be Started either at application startup or when the connection is disconnected, and - /// stopped when the application is connected again; it doesn't "run" all the time. + /// This class is intended to be Start()ed either at application startup or when the connection is disconnected, and + /// Stop()ed when the application is connected again; it doesn't "run" all the time because there are cases where + /// a user has manually disconnected, was kicked by another login somewhere, etc. where we don't want to reconnect. /// public class ConnectionWatchdog { @@ -93,6 +94,9 @@ namespace slskd public virtual void Start() { WatchdogTimer.Enabled = true; + + // note: this is synchronized so only 1 can run at a time. we're only calling it here to avoid the + // initial timer tick duration _ = AttemptReconnect(attempts: 0); } @@ -162,7 +166,17 @@ namespace slskd { try { - // go until we connect and break, or something stops the watchdog + /* + go until we connect and break, or something stops the watchdog. why don't we just use the timer here? + good question. we could, but a loop gives us more control and precision. at the expensive of needing to + break out of it if a user wants to stop or reset. reevaluate later! + + things that can cause us to exit this loop: + - the timer being disabled, which will exit whenever the while expression is evaluated. any Task.Delay or connection attempt will keep going (this is more of a backstop) + - CancellationTokenSource being tripped, which will throw TaskCanceledException or OperationCanceledException somewhere + - a successful connection + */ + while (IsEnabled) { // bail out if we're already connected. it's possible that something else outside of the watchdog -- cgit v1.2.3 From 4667de5ef249bc3de93164c988c8721410907bc2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:50:30 -0500 Subject: adjust Restart() --- src/slskd/Core/ConnectionWatchdog.cs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 819d9a49..2b4f6c21 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -101,13 +101,20 @@ namespace slskd } /// - /// Starts monitoring the server connection. + /// Stops the watchdog and aborts any active reconnection loop, then starts again. /// - /// This should be called when the connection is disconnected. - public void Restart() + /// + /// This should be called when we have a reason to restart an in-process retry loop, such as a setting change, + /// user request, etc. + /// + public virtual void Restart() { - WatchdogTimer.Enabled = true; - _ = AttemptReconnect(attempts: 1); + if (IsEnabled) + { + Log.Information("(Re)connection process restarted"); + Stop(abortReconnect: true); + Start(); + } } /// -- cgit v1.2.3 From eae27687458395a71c7fe9c4e82b3ed2608f0f9f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:51:00 -0500 Subject: prevent throwing when stopping --- src/slskd/Core/ConnectionWatchdog.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 2b4f6c21..e148024d 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -124,6 +124,7 @@ namespace slskd /// This should be called when the application is reasonably certain that the connection is connected. public virtual void Stop(bool abortReconnect = false) { + // stop the timer first to avoid having it start the connection process again when the cts is cancelled WatchdogTimer.Enabled = false; // note: the connect event fires before the connection logic is complete, so there is a chain of events @@ -132,7 +133,14 @@ namespace slskd // wants to abort the reconnect logic. if (abortReconnect) { - CancellationTokenSource?.Cancel(); + try + { + CancellationTokenSource?.Cancel(throwOnFirstException: false); + } + catch (Exception) + { + // noop. Cancel() can throw if registered callbacks throw, but we don't have any right now and we don't care anyway + } } } -- cgit v1.2.3 From a9eed8e7c0b0810c6b81de844a2afdcd192e76d1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:51:16 -0500 Subject: stop when disposing --- src/slskd/Core/ConnectionWatchdog.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index e148024d..3954d0fc 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -150,6 +150,8 @@ namespace slskd /// protected virtual void Dispose(bool disposing) { + Stop(abortReconnect: true); + if (!Disposed) { if (disposing) -- cgit v1.2.3 From 4b0b2d8336a71b8fac3da4ddbabde1f8dc6966b0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:51:34 -0500 Subject: coalesce CancellationTokenSource --- src/slskd/Core/ConnectionWatchdog.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 3954d0fc..7b4ecc62 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -213,7 +213,7 @@ namespace slskd var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before attempting to reconnect"); - await Task.Delay(delay + jitter, cancellationToken: CancellationTokenSource.Token); + await Task.Delay(delay + jitter, cancellationToken: CancellationTokenSource?.Token ?? CancellationToken.None); Log.Information("Attempting to reconnect to the Soulseek server (#{Attempts})...", attempts); } @@ -227,7 +227,7 @@ namespace slskd // reconnect with the latest configuration values we have for username and password, instead of the // options that were captured at startup. if a user has updated these values prior to the disconnect, // the changes will take effect now. - var opt = Options.CurrentValue.Soulseek; + var opt = OptionsMonitor.CurrentValue.Soulseek; // note: cancelling the CTS before the connect logic is fully complete (e.g. reacting to the connect event) // will cause the client to connect, then disconnect immediately @@ -236,7 +236,7 @@ namespace slskd port: opt.Port, username: opt.Username, password: opt.Password, - cancellationToken: CancellationTokenSource.Token); + cancellationToken: CancellationTokenSource?.Token ?? CancellationToken.None); break; } -- cgit v1.2.3 From 8cbcf622764a627d53505962e34695be2f4dbda0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:52:06 -0500 Subject: adjust ConnectionWatchdog callsites --- src/slskd/Application.cs | 6 +++--- src/slskd/Program.cs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e0570ef6..7f1b4be0 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -88,7 +88,7 @@ namespace slskd IManagedState state, ISoulseekClient soulseekClient, FileService fileService, - IConnectionWatchdog connectionWatchdog, + ConnectionWatchdog connectionWatchdog, ITransferService transferService, IBrowseTracker browseTracker, IRoomTracker roomTracker, @@ -213,7 +213,7 @@ namespace slskd private FileService Files { get; } private IRoomService RoomService { get; set; } private IBrowseTracker BrowseTracker { get; set; } - private IConnectionWatchdog ConnectionWatchdog { get; } + private ConnectionWatchdog ConnectionWatchdog { get; } private IMessagingService Messaging { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private ConcurrentDictionary Loggers { get; } = new ConcurrentDictionary(); @@ -859,7 +859,7 @@ namespace slskd else { Log.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - ConnectionWatchdog.Restart(); + ConnectionWatchdog.Start(); } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index dd85bc21..89230e2a 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -592,7 +592,7 @@ namespace slskd services.AddHostedService(p => p.GetRequiredService()); services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(); if (OptionsAtStartup.Flags.Volatile) { -- cgit v1.2.3 From 7d302ce2a65bac34f0795ce5eafb3e06b746872d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jul 2025 17:52:57 -0500 Subject: return 205/ResetContent if retry loop is restarted by API call --- src/slskd/Core/API/Controllers/ServerController.cs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/API/Controllers/ServerController.cs b/src/slskd/Core/API/Controllers/ServerController.cs index aceaeec9..da777b02 100644 --- a/src/slskd/Core/API/Controllers/ServerController.cs +++ b/src/slskd/Core/API/Controllers/ServerController.cs @@ -21,6 +21,7 @@ namespace slskd.Core.API { using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Soulseek; @@ -36,7 +37,7 @@ namespace slskd.Core.API { public ServerController( ISoulseekClient soulseekClient, - IConnectionWatchdog connectionWatchdog, + ConnectionWatchdog connectionWatchdog, IOptionsSnapshot optionsSnapshot, IStateSnapshot stateSnapshot) { @@ -47,7 +48,7 @@ namespace slskd.Core.API } private ISoulseekClient Client { get; } - private IConnectionWatchdog ConnectionWatchdog { get; } + private ConnectionWatchdog ConnectionWatchdog { get; } private IOptionsSnapshot OptionsSnapshot { get; } private IStateSnapshot StateSnapshot { get; } @@ -59,6 +60,7 @@ namespace slskd.Core.API [Route("")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] + [ProducesResponseType(StatusCodes.Status205ResetContent)] [ProducesResponseType(403)] public IActionResult Connect() { @@ -67,10 +69,19 @@ namespace slskd.Core.API return Forbid(); } - // we use the watchdog here so that we get the correct auto-reconnect behavior + // if the watchdog is already enabled, we're already attempting to connect. the user might have changed something + // or perhaps is just being impatient; either way, restart the retry loop so they can see results faster + // remember, we may be in a ~5 minute delay at this moment + if (ConnectionWatchdog.IsEnabled) + { + ConnectionWatchdog.Restart(); + return StatusCode(StatusCodes.Status205ResetContent); + } + if (!ConnectionWatchdog.IsEnabled) { ConnectionWatchdog.Start(); + return Ok(); } return Ok(); -- cgit v1.2.3 From 7f3f214a03281aea665d9ea58096ddb65a332f31 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 12 Jul 2025 14:03:47 -0500 Subject: add watchdog state --- src/slskd/Core/State.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index 9ae6df6b..86b628b5 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -35,6 +35,7 @@ namespace slskd public bool PendingReconnect { get; init; } public bool PendingRestart { get; init; } public ServerState Server { get; init; } = new ServerState(); + public ServerConnectionWatchdogState ConnectionWatchdog { get; init; } = new ServerConnectionWatchdogState(); public RelayState Relay { get; init; } = new RelayState(); public UserState User { get; init; } = new UserState(); public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); @@ -61,10 +62,19 @@ namespace slskd public IPEndPoint IPEndPoint { get; init; } public SoulseekClientStates State { get; init; } public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); + public bool IsConnecting => State.HasFlag(SoulseekClientStates.Connecting); public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); + public bool IsLoggingIn => State.HasFlag(SoulseekClientStates.LoggingIn); public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); } + public record ServerConnectionWatchdogState + { + public bool IsEnabled { get; init; } = false; + public bool IsAttemptingConnection { get; init; } = false; + public DateTime? NextAttemptAt { get; init; } + } + public record RelayState { public RelayMode Mode { get; init; } -- cgit v1.2.3 From baa10191f6b4edf5be7889a9a0c06ecbcf52bc52 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 12 Jul 2025 14:17:01 -0500 Subject: update watchdog state at various points --- src/slskd/Core/ConnectionWatchdog.cs | 56 +++++++++++++++++++++++++++++------- 1 file changed, 46 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 7b4ecc62..b7a4fa34 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -42,15 +42,15 @@ namespace slskd /// /// /// - /// + /// public ConnectionWatchdog( ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, - IStateMonitor state) + IManagedState applicationState) { Client = soulseekClient; OptionsMonitor = optionsMonitor; - State = state; + ApplicationState = applicationState; WatchdogTimer = new System.Timers.Timer() { @@ -59,7 +59,9 @@ namespace slskd Enabled = false, }; - WatchdogTimer.Elapsed += (sender, args) => _ = AttemptReconnect(); + // the timer is used here to ensure that we keep trying if the connection logic fails for some reason. i'm questioning + // this at the moment and may continue to do so + WatchdogTimer.Elapsed += (sender, args) => _ = AttemptConnection(source: nameof(WatchdogTimer)); OptionsMonitor.OnChange(options => OptionsChanged(options)); } @@ -69,12 +71,18 @@ namespace slskd /// public bool IsEnabled => WatchdogTimer.Enabled; + /// + /// Gets a value indicating whether the watchdog is actively attempting to connect. + /// + public bool IsAttemptingConnection => SyncRoot.CurrentCount == 0; + private ISoulseekClient Client { get; } private bool Disposed { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; set; } - private IStateMonitor State { get; } + private IManagedState ApplicationState { get; } private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private object StateLock { get; } = new object(); private System.Timers.Timer WatchdogTimer { get; } private CancellationTokenSource CancellationTokenSource { get; set; } @@ -94,10 +102,11 @@ namespace slskd public virtual void Start() { WatchdogTimer.Enabled = true; + UpdateApplicationState(); // note: this is synchronized so only 1 can run at a time. we're only calling it here to avoid the // initial timer tick duration - _ = AttemptReconnect(attempts: 0); + _ = AttemptConnection(source: nameof(Start)); } /// @@ -126,6 +135,7 @@ namespace slskd { // stop the timer first to avoid having it start the connection process again when the cts is cancelled WatchdogTimer.Enabled = false; + UpdateApplicationState(); // note: the connect event fires before the connection logic is complete, so there is a chain of events // that leads to the application being connected and then immediately disconnected if this CTS is cancelled @@ -164,6 +174,22 @@ namespace slskd } } + private void UpdateApplicationState(DateTime? nextAttemptAt = null) + { + lock (StateLock) + { + ApplicationState.SetValue(state => state with + { + ConnectionWatchdog = new ServerConnectionWatchdogState() + { + IsEnabled = IsEnabled, + IsAttemptingConnection = IsAttemptingConnection, + NextAttemptAt = IsAttemptingConnection ? nextAttemptAt ?? state.ConnectionWatchdog.NextAttemptAt : null, // only null this if we're not attempting, otherwise it sticks + }, + }); + } + } + private void OptionsChanged(Options options) { // it's possible that a user begins changing connection settings in an attempt to get the client to connect @@ -175,7 +201,7 @@ namespace slskd } } - private async Task AttemptReconnect(int attempts = 1) + private async Task AttemptConnection(string source) { // semaphore is obtained here and released only when the reconnect attempt is complete, so // one and only one invocation of this can run at a time @@ -183,6 +209,8 @@ namespace slskd { try { + Log.Debug("AttemptConnection initiated by {Source}", source); + /* go until we connect and break, or something stops the watchdog. why don't we just use the timer here? good question. we could, but a loop gives us more control and precision. at the expensive of needing to @@ -191,14 +219,15 @@ namespace slskd things that can cause us to exit this loop: - the timer being disabled, which will exit whenever the while expression is evaluated. any Task.Delay or connection attempt will keep going (this is more of a backstop) - CancellationTokenSource being tripped, which will throw TaskCanceledException or OperationCanceledException somewhere - - a successful connection + - a successful connection OR the server becomes connected another way */ + int attempts = 0; while (IsEnabled) { // bail out if we're already connected. it's possible that something else outside of the watchdog // connects the client. highly unlikely but that might change if someone inadvertently adds some logic. - if (State.CurrentValue.Server.IsConnected) + if (ApplicationState.CurrentValue.Server.IsConnected) { return; } @@ -213,13 +242,17 @@ namespace slskd var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before attempting to reconnect"); + + UpdateApplicationState(nextAttemptAt: DateTime.UtcNow.AddMilliseconds(delay + jitter)); + await Task.Delay(delay + jitter, cancellationToken: CancellationTokenSource?.Token ?? CancellationToken.None); - Log.Information("Attempting to reconnect to the Soulseek server (#{Attempts})...", attempts); + Log.Information("Attempting to connect to the Soulseek server (#{Attempts})...", attempts); } else { Log.Information("Attempting to connect to the Soulseek server..."); + UpdateApplicationState(nextAttemptAt: DateTime.UtcNow); } try @@ -277,6 +310,9 @@ namespace slskd } SyncRoot.Release(); + + // do this after the semaphore is released so that IsAttemptingConnection is false and the next attempt is nulled + UpdateApplicationState(); } } } -- cgit v1.2.3 From 14dd21f0ecf6b144dc78fafcc67096f386298248 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 12 Jul 2025 14:17:37 -0500 Subject: update ui to show watchdog status --- src/web/src/components/App.jsx | 92 +++++++++++++++++++++++++----------------- 1 file changed, 56 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index 5c82697a..92fe925b 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -43,6 +43,7 @@ const initialState = { }; const ModeSpecificConnectButton = ({ + connectionWatchdog, controller = {}, mode, pendingReconnect, @@ -85,45 +86,62 @@ const ModeSpecificConnectButton = ({ ); } else { - return ( - <> - {server?.isConnected && ( - disconnect()}> - - - {user?.privileges?.isPrivileged && ( - - )} - - Connected - - )} - {!server?.isConnected && ( - connect()}> - - + if (server?.isConnected) { + return ( + disconnect()}> + + + {user?.privileges?.isPrivileged && ( - - Disconnected - - )} - + )} + + Connected + + ); + } + + // the server is disconnected, and we need to give the user some information about what the client is doing + // options are: + // - nothing. the client was manually disconnected, kicked off by another login, etc., and we're not trying to connect + // - actively trying to make a connection to the server + // - still trying to connect, but waiting for the next connection attempt + let icon = 'close'; + let color = 'red'; + + if (connectionWatchdog?.isAttemptingConnection) { + icon = 'clock'; + color = 'yellow'; + } + + if (server?.isConnecting || server?.IsLoggingIn) { + icon = 'sync alternate loading'; + color = 'green'; + } + + return ( + connect()}> + + + + + Disconnected + ); } }; @@ -264,6 +282,7 @@ class App extends Component { : 'light'), } = this.state; const { + connectionWatchdog = {}, pendingReconnect, pendingRestart, relay = {}, @@ -409,6 +428,7 @@ class App extends Component { Theme Date: Sat, 12 Jul 2025 14:34:48 -0500 Subject: null server and ip when not connected --- src/slskd/Application.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 3a8f6ba4..ab666c85 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -992,8 +992,8 @@ namespace slskd { Server = state.Server with { - Address = Client.Address, - IPEndPoint = Client.IPEndPoint, + Address = Client.State.HasFlag(SoulseekClientStates.Disconnected) ? null : Client.Address, + IPEndPoint = Client.State.HasFlag(SoulseekClientStates.Disconnected) ? default : Client.IPEndPoint, State = Client.State, }, User = state.User with -- cgit v1.2.3