diff options
| author | JP Dillingham <jpdillingham@gmail.com> | 2022-07-10 12:23:37 -0500 |
|---|---|---|
| committer | JP Dillingham <jpdillingham@gmail.com> | 2022-07-10 12:23:37 -0500 |
| commit | 55d3940da06c6e69a77ef51660cb7c00b568daf6 (patch) | |
| tree | 36e1b4a7f1c40e7a4c8df66a52da88812344f45a /src | |
| parent | 623702e58199131afe8ad58c19d0feabb066c211 (diff) | |
| download | slskd-55d3940da06c6e69a77ef51660cb7c00b568daf6.tar.gz | |
synchronize retries, retry in a loop
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Core/ConnectionWatchdog.cs | 140 |
1 files changed, 107 insertions, 33 deletions
diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 633b1f70..931155cf 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -20,18 +20,47 @@ using Microsoft.Extensions.Options; namespace slskd { using System; + using System.Threading; using System.Threading.Tasks; using Serilog; using Soulseek; + /// <summary> + /// Monitors the connection to the Soulseek server and reconnects with exponential backoff, if necessary. + /// </summary> public interface IConnectionWatchdog : IDisposable { + /// <summary> + /// Gets a value indicating whether the watchdog is monitoring the server connection. + /// </summary> + bool IsEnabled { get; } + + /// <summary> + /// Starts monitoring the server connection. + /// </summary> + /// <remarks>This should be called when the connection is disconnected.</remarks> + void Start(); + + /// <summary> + /// Stops monitoring the server connection. + /// </summary> + /// <remarks>This should be called when the application is reasonably certain that the connection is connected.</remarks> + void Stop(); } + /// <summary> + /// Monitors the connection to the Soulseek network and reconnects with exponential backoff, if necessary. + /// </summary> public class ConnectionWatchdog : IConnectionWatchdog { private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes + /// <summary> + /// Initializes a new instance of the <see cref="ConnectionWatchdog"/> class. + /// </summary> + /// <param name="soulseekClient"></param> + /// <param name="optionsMonitor"></param> + /// <param name="state"></param> public ConnectionWatchdog( ISoulseekClient soulseekClient, IOptionsMonitor<Options> optionsMonitor, @@ -41,37 +70,65 @@ namespace slskd Options = optionsMonitor; State = state; - WatchDogTimer = new System.Timers.Timer() + WatchdogTimer = new System.Timers.Timer() { - Interval = 250, + Interval = 100, AutoReset = true, - Enabled = true, + Enabled = false, }; - WatchDogTimer.Elapsed += (sender, args) => _ = AttemptReconnect(); + WatchdogTimer.Elapsed += (sender, args) => _ = AttemptReconnect(); } - private int Attempts { get; set; } + /// <summary> + /// Gets a value indicating whether the watchdog is monitoring the server connection. + /// </summary> + public bool IsEnabled => WatchdogTimer.Enabled; + private ISoulseekClient Client { get; } private bool Disposed { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext<Application>(); private IOptionsMonitor<Options> Options { get; set; } private IStateMonitor<State> State { get; } - private System.Timers.Timer WatchDogTimer { get; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private System.Timers.Timer WatchdogTimer { get; } + /// <summary> + /// Disposes this instance. + /// </summary> public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } + /// <summary> + /// Starts monitoring the server connection. + /// </summary> + /// <remarks>This should be called when the connection is disconnected.</remarks> + public void Start() + { + WatchdogTimer.Enabled = true; + _ = AttemptReconnect(); + } + + /// <summary> + /// Stops monitoring the server connection. + /// </summary> + /// <remarks>This should be called when the application is reasonably certain that the connection is connected.</remarks> + public void Stop() => WatchdogTimer.Enabled = false; + + /// <summary> + /// Disposes this instance. + /// </summary> + /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (!Disposed) { if (disposing) { - WatchDogTimer?.Dispose(); + WatchdogTimer?.Dispose(); } Disposed = true; @@ -80,33 +137,50 @@ namespace slskd private async Task AttemptReconnect() { - if (State.CurrentValue.Server.IsConnected || !State.CurrentValue.Server.AttemptingReconnect) - { - return; - } - - var (delay, jitter) = Compute.ExponentialBackoffDelay( - iteration: Attempts, - maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); - - var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); - Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); - - await Task.Delay(delay + jitter); - - Log.Information("Attempting to reconnect (#{Attempts})...", Attempts); - - try - { - // 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. - await Client.ConnectAsync(Options.CurrentValue.Soulseek.Username, Options.CurrentValue.Soulseek.Password); - } - catch (Exception ex) + if (await SyncRoot.WaitAsync(0)) { - Attempts++; - Log.Error("Failed to reconnect: {Message}", ex.Message); + try + { + if (State.CurrentValue.Server.IsConnected) + { + return; + } + + var attempts = 1; + + while (true) + { + var (delay, jitter) = Compute.ExponentialBackoffDelay( + iteration: attempts, + maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); + + var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); + Log.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); + await Task.Delay(delay + jitter); + + Log.Information("Attempting to reconnect (#{Attempts})...", attempts); + + try + { + // 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. + await Client.ConnectAsync(Options.CurrentValue.Soulseek.Username, Options.CurrentValue.Soulseek.Password); + + Log.Information("Successfully reconnected after #{Attempts}", attempts); + break; + } + catch (Exception ex) + { + attempts++; + Log.Error("Failed to reconnect: {Message}", ex.Message); + } + } + } + finally + { + SyncRoot.Release(); + } } } } |
