diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-07-11 20:13:09 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-07-11 20:13:09 -0500 |
| commit | 9d2ad97f48f773c72a15fbd0e18cff17fa86860e (patch) | |
| tree | 7b807681f8ba77a898bfc0b79ddb80d4a47012ea /src | |
| parent | e494253d3a40c38a15ac97a428bfdaba7f6a279d (diff) | |
| parent | 2c327ec95b55721959d9e521a1205e8deedf15bb (diff) | |
| download | slskd-9d2ad97f48f773c72a15fbd0e18cff17fa86860e.tar.gz | |
Merge pull request #544 from slskd/reconnect
Move reconnect logic to ConnectionWatchdog
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Application.cs | 45 | ||||
| -rw-r--r-- | src/slskd/Core/ConnectionWatchdog.cs | 185 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 2 |
3 files changed, 195 insertions, 37 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 598c0c5e..af553475 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -76,6 +76,7 @@ namespace slskd IOptionsMonitor<Options> optionsMonitor, IManagedState<State> state, ISoulseekClient soulseekClient, + IConnectionWatchdog connectionWatchdog, ITransferTracker transferTracker, ITransferService transferService, IBrowseTracker browseTracker, @@ -139,11 +140,14 @@ namespace slskd Client.DistributedNetworkStateChanged += Client_DistributedNetworkStateChanged; Client.DownloadDenied += (e, args) => Log.Information("Download of {Filename} from {Username} was denied: {Message}", args.Filename, args.Username, args.Message); Client.DownloadFailed += (e, args) => Log.Information("Download of {Filename} from {Username} failed", args.Filename, args.Username); + + ConnectionWatchdog = connectionWatchdog; } private ISoulseekClient Client { get; set; } private IRoomService RoomService { get; set; } private IBrowseTracker BrowseTracker { get; set; } + private IConnectionWatchdog ConnectionWatchdog { get; } private IConversationTracker ConversationTracker { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext<Application>(); private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>(); @@ -355,6 +359,7 @@ namespace slskd private void Client_Connected(object sender, EventArgs e) { + ConnectionWatchdog.Stop(); Log.Information("Connected to the Soulseek server"); } @@ -381,7 +386,7 @@ namespace slskd logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); } - private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) + private void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) { if (State.CurrentValue.PendingReconnect) { @@ -402,46 +407,12 @@ namespace slskd } else if (args.Exception is KickedFromServerException) { - Log.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Client.Username); + Log.Error("Disconnected from the Soulseek server: another client logged in using the same username"); } else { Log.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message); - - if (string.IsNullOrEmpty(Options.Soulseek.Username) || string.IsNullOrEmpty(Options.Soulseek.Password)) - { - Log.Warning($"Not reconnecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); - 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.Soulseek.Username, Options.Soulseek.Password); - break; - } - catch (Exception ex) - { - attempts++; - Log.Error("Failed to reconnect: {Message}", ex.Message); - } - } + ConnectionWatchdog.Start(); } } diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs new file mode 100644 index 00000000..6a48c0e4 --- /dev/null +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -0,0 +1,185 @@ +// <copyright file="ConnectionWatchdog.cs" company="slskd Team"> +// 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/. +// </copyright> + +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, + IStateMonitor<State> state) + { + Client = soulseekClient; + Options = optionsMonitor; + State = state; + + WatchdogTimer = new System.Timers.Timer() + { + Interval = 100, + AutoReset = true, + Enabled = false, + }; + + WatchdogTimer.Elapsed += (sender, args) => _ = AttemptReconnect(); + } + + /// <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 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(); + } + + Disposed = true; + } + } + + private async Task AttemptReconnect() + { + if (await SyncRoot.WaitAsync(0)) + { + 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); + break; + } + catch (Exception ex) + { + attempts++; + Log.Error("Failed to reconnect: {Message}", ex.Message); + } + } + } + finally + { + SyncRoot.Release(); + } + } + } + } +}
\ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index df1fb55c..ae4f2015 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -446,6 +446,8 @@ namespace slskd services.AddSingleton<IApplication, Application>(); services.AddHostedService(p => p.GetRequiredService<IApplication>()); + services.AddSingleton<IConnectionWatchdog, ConnectionWatchdog>(); + services.AddDbContext<SearchDbContext>("search.db"); services.AddSingleton<ITransferTracker, TransferTracker>(); |
