From 5a94ec0d6960210d9a8f8301308a56d59095bf70 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 Jul 2022 21:14:19 -0500 Subject: add ConnectionWatchdog --- src/slskd/Core/ConnectionWatchdog.cs | 113 +++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 src/slskd/Core/ConnectionWatchdog.cs (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs new file mode 100644 index 00000000..633b1f70 --- /dev/null +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -0,0 +1,113 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd +{ + using System; + using System.Threading.Tasks; + using Serilog; + using Soulseek; + + public interface IConnectionWatchdog : IDisposable + { + } + + public class ConnectionWatchdog : IConnectionWatchdog + { + private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes + + public ConnectionWatchdog( + ISoulseekClient soulseekClient, + IOptionsMonitor optionsMonitor, + IStateMonitor state) + { + Client = soulseekClient; + Options = optionsMonitor; + State = state; + + WatchDogTimer = new System.Timers.Timer() + { + Interval = 250, + AutoReset = true, + Enabled = true, + }; + + WatchDogTimer.Elapsed += (sender, args) => _ = AttemptReconnect(); + } + + private int Attempts { get; set; } + 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; } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + WatchDogTimer?.Dispose(); + } + + Disposed = true; + } + } + + 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) + { + Attempts++; + Log.Error("Failed to reconnect: {Message}", ex.Message); + } + } + } +} \ No newline at end of file -- cgit v1.2.3 From d95c02b1f086ba17811e7ef08d45a89e069f7e31 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 Jul 2022 21:14:32 -0500 Subject: add AttemptingReconnect --- src/slskd/Core/State.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index e009805a..7492a096 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -61,6 +61,7 @@ namespace slskd public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); + public bool AttemptingReconnect { get; init; } } public record UserState -- cgit v1.2.3 From 47f25751f42b75c156e82f84b67385291c3d7ef7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 Jul 2022 12:21:46 -0500 Subject: remove AttemptingReconnect --- src/slskd/Core/State.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index 7492a096..e009805a 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -61,7 +61,6 @@ namespace slskd public bool IsConnected => State.HasFlag(SoulseekClientStates.Connected); public bool IsLoggedIn => State.HasFlag(SoulseekClientStates.LoggedIn); public bool IsTransitioning => State.HasFlag(SoulseekClientStates.Connecting) || State.HasFlag(SoulseekClientStates.Disconnecting) || State.HasFlag(SoulseekClientStates.LoggingIn); - public bool AttemptingReconnect { get; init; } } public record UserState -- cgit v1.2.3 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/slskd/Core') 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 From 2c327ec95b55721959d9e521a1205e8deedf15bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 11 Jul 2022 10:14:30 -0500 Subject: remove log after reconnect --- src/slskd/Core/ConnectionWatchdog.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index 931155cf..6a48c0e4 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -166,8 +166,6 @@ namespace slskd // 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) -- cgit v1.2.3