From 55d3940da06c6e69a77ef51660cb7c00b568daf6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 Jul 2022 12:23:37 -0500 Subject: synchronize retries, retry in a loop --- src/slskd/Core/ConnectionWatchdog.cs | 140 ++++++++++++++++++++++++++--------- 1 file changed, 107 insertions(+), 33 deletions(-) (limited to 'src') 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; + /// + /// 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. + /// + bool IsEnabled { get; } + + /// + /// Starts monitoring the server connection. + /// + /// This should be called when the connection is disconnected. + void Start(); + + /// + /// Stops monitoring the server connection. + /// + /// This should be called when the application is reasonably certain that the connection is connected. + void Stop(); } + /// + /// Monitors the connection to the Soulseek network and reconnects with exponential backoff, if necessary. + /// public class ConnectionWatchdog : IConnectionWatchdog { private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes + /// + /// Initializes a new instance of the class. + /// + /// + /// + /// public ConnectionWatchdog( ISoulseekClient soulseekClient, IOptionsMonitor 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; } + /// + /// Gets a value indicating whether the watchdog is monitoring the server connection. + /// + public bool IsEnabled => WatchdogTimer.Enabled; + private ISoulseekClient Client { get; } private bool Disposed { get; set; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor Options { get; set; } private IStateMonitor State { get; } - private System.Timers.Timer WatchDogTimer { get; } + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private System.Timers.Timer WatchdogTimer { get; } + /// + /// Disposes this instance. + /// public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } + /// + /// Starts monitoring the server connection. + /// + /// This should be called when the connection is disconnected. + public void Start() + { + WatchdogTimer.Enabled = true; + _ = AttemptReconnect(); + } + + /// + /// Stops monitoring the server connection. + /// + /// This should be called when the application is reasonably certain that the connection is connected. + public void Stop() => WatchdogTimer.Enabled = false; + + /// + /// Disposes this instance. + /// + /// 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(); + } } } } -- cgit v1.2.3