From b9f03ace7351da1f82608e7efab72292a613ae08 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 10 Jun 2021 17:25:56 -0500 Subject: add Compute class --- src/slskd/Common/Compute.cs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/slskd/Common/Compute.cs (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs new file mode 100644 index 00000000..dec0e661 --- /dev/null +++ b/src/slskd/Common/Compute.cs @@ -0,0 +1,34 @@ +// +// 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/. +// + +namespace slskd +{ + using System; + + /// + /// Static utility methods that don't otherwise work well as extensions. + /// + public static class Compute + { + public static int ExponentialBackoffDelay(int iteration, int delayInSeconds, int backoffRate, int maxDelayInSeconds = int.MaxValue) + { + var computedDelay = Math.Pow(delayInSeconds * backoffRate, Math.Min(50, iteration)) - delayInSeconds; + var safeDelay = (int)Math.Min(computedDelay, int.MaxValue); + return Math.Min(safeDelay, maxDelayInSeconds); + } + } +} -- cgit v1.2.3 From 94865acdf168cb11fb1e28c3a50673611ecfc369 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 10 Jun 2021 17:26:37 -0500 Subject: implement reconnects with exponential backoff --- src/slskd/Core/Service.cs | 60 +++++++++++++++++++++++++++++------------------ 1 file changed, 37 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Service.cs b/src/slskd/Core/Service.cs index 6df1ddcb..4c1d2a4f 100644 --- a/src/slskd/Core/Service.cs +++ b/src/slskd/Core/Service.cs @@ -38,8 +38,11 @@ namespace slskd public class Service : IHostedService { - private static readonly int MaxReconnectAttempts = 3; - private static int currentReconnectAttempts = 0; + private static readonly int ReconnectDelaySeconds = 1; + private static readonly int ReconnectMaxDelaySeconds = 300; // 5 minutes + private static readonly int ReconnectBackoffRate = 2; + private static int reconnectAttempts = 0; + private static (int Directories, int Files) sharedCounts = (0, 0); public Service( @@ -121,6 +124,7 @@ namespace slskd Client.RoomJoined += Client_RoomJoined; Client.RoomLeft += Client_RoomLeft; Client.Disconnected += Client_Disconnected; + Client.Connected += Client_Connected; SoulseekClient = Client; @@ -207,30 +211,40 @@ namespace slskd logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message); } - private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) + private void Client_Connected(object sender, EventArgs e) { - Console.WriteLine($"Disconnected from Soulseek server: {args.Message}"); + Interlocked.Exchange(ref reconnectAttempts, 0); + } - // don't reconnect if the disconnecting Exception is either of these types. if KickedFromServerException, another - // client was most likely signed in, and retrying will cause a connect loop. if ObjectDisposedException, the client is - // shutting down. - if (!(args.Exception is KickedFromServerException || args.Exception is ObjectDisposedException)) + private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) + { + if (args.Exception is ObjectDisposedException) + { + Logger.Debug("Disconnected from the Soulseek server: the client is shutting down"); + } + else if (args.Exception is LoginRejectedException) { - Interlocked.Increment(ref currentReconnectAttempts); - - if (currentReconnectAttempts <= MaxReconnectAttempts) - { - var wait = (int)Math.Pow(currentReconnectAttempts, 3); - Console.WriteLine($"Waiting {wait} second(s) before reconnect..."); - await Task.Delay(wait); - - Console.WriteLine($"Attepting to reconnect..."); - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); - } - else - { - Console.WriteLine($"Unable to reconnect after {currentReconnectAttempts} tries."); - } + Logger.Error("Disconnected from the Soulseek server: invalid username or password"); + } + else if (args.Exception is KickedFromServerException) + { + Logger.Error("Disconnected from the Soulseek server: another client logged in using the username {Username}", Options.Soulseek.Username); + } + else + { + var delay = Compute.ExponentialBackoffDelay( + iteration: reconnectAttempts, + backoffRate: ReconnectBackoffRate, + delayInSeconds: ReconnectDelaySeconds, + maxDelayInSeconds: ReconnectMaxDelaySeconds); + + Logger.Information($"Waiting {delay} second(s) before reconnecting..."); + await Task.Delay(delay * 1000); + + Interlocked.Increment(ref reconnectAttempts); + + Logger.Information($"Attepting to reconnect (#{reconnectAttempts})...", reconnectAttempts); + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); } } -- cgit v1.2.3 From 07331bd2d16bfba8d3d0365d1e7860e807ba6d30 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jun 2021 15:50:45 -0500 Subject: simplify exponential backoff logic --- src/slskd/Common/Compute.cs | 14 ++++++++++---- src/slskd/Core/Service.cs | 14 +++++--------- tests/slskd.Tests.Unit/Common/ComputeTests.cs | 18 +++++++++--------- 3 files changed, 24 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index dec0e661..ef1f1882 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -24,11 +24,17 @@ namespace slskd /// public static class Compute { - public static int ExponentialBackoffDelay(int iteration, int delayInSeconds, int backoffRate, int maxDelayInSeconds = int.MaxValue) + public static (int Delay, int Jitter) ExponentialBackoffDelay(int iteration, int maxDelayInMilliseconds = int.MaxValue) { - var computedDelay = Math.Pow(delayInSeconds * backoffRate, Math.Min(50, iteration)) - delayInSeconds; + iteration = Math.Min(100, iteration); + + var computedDelay = Math.Floor((Math.Pow(2, iteration) - 1) / 2) * 1000; var safeDelay = (int)Math.Min(computedDelay, int.MaxValue); - return Math.Min(safeDelay, maxDelayInSeconds); + var clampedDelay = Math.Min(safeDelay, maxDelayInMilliseconds); + + var jitter = new Random().Next(1000); + + return (clampedDelay, jitter); } } -} +} \ No newline at end of file diff --git a/src/slskd/Core/Service.cs b/src/slskd/Core/Service.cs index 4c1d2a4f..a8324a75 100644 --- a/src/slskd/Core/Service.cs +++ b/src/slskd/Core/Service.cs @@ -38,9 +38,7 @@ namespace slskd public class Service : IHostedService { - private static readonly int ReconnectDelaySeconds = 1; - private static readonly int ReconnectMaxDelaySeconds = 300; // 5 minutes - private static readonly int ReconnectBackoffRate = 2; + private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes private static int reconnectAttempts = 0; private static (int Directories, int Files) sharedCounts = (0, 0); @@ -232,14 +230,12 @@ namespace slskd } else { - var delay = Compute.ExponentialBackoffDelay( + var (delay, jitter) = Compute.ExponentialBackoffDelay( iteration: reconnectAttempts, - backoffRate: ReconnectBackoffRate, - delayInSeconds: ReconnectDelaySeconds, - maxDelayInSeconds: ReconnectMaxDelaySeconds); + maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); - Logger.Information($"Waiting {delay} second(s) before reconnecting..."); - await Task.Delay(delay * 1000); + Logger.Information($"Waiting {delay + jitter} millisecond(s) before reconnecting..."); + await Task.Delay(delay + jitter); Interlocked.Increment(ref reconnectAttempts); diff --git a/tests/slskd.Tests.Unit/Common/ComputeTests.cs b/tests/slskd.Tests.Unit/Common/ComputeTests.cs index 99b05d3f..5a7922f6 100644 --- a/tests/slskd.Tests.Unit/Common/ComputeTests.cs +++ b/tests/slskd.Tests.Unit/Common/ComputeTests.cs @@ -5,16 +5,16 @@ namespace slskd.Tests.Unit public class ComputeTests { [Theory] - [InlineData(0, 1, 2, 300, 0)] - [InlineData(1, 1, 2, 300, 1)] - [InlineData(2, 1, 2, 300, 3)] - [InlineData(3, 1, 2, 300, 7)] - [InlineData(4, 1, 2, 300, 15)] - [InlineData(5, 1, 2, 300, 31)] - [InlineData(999999, 1, 2, 300, 300)] - public void ExponentialBackoffDelay(int iteration, int delayInSeconds, int backoffRate, int maxDelayInSeconds, int expectedDelay) + [InlineData(1, 300000, 0)] + [InlineData(2, 300000, 1000)] + [InlineData(3, 300000, 3000)] + [InlineData(4, 300000, 7000)] + [InlineData(5, 300000, 15000)] + [InlineData(6, 300000, 31000)] + [InlineData(999999, 300000, 300000)] + public void ExponentialBackoffDelay(int iteration, int maxDelayInMs, int expectedDelay) { - var computedDelay = Compute.ExponentialBackoffDelay(iteration, delayInSeconds, backoffRate, maxDelayInSeconds); + var (computedDelay, _) = Compute.ExponentialBackoffDelay(iteration, maxDelayInMs); Assert.Equal(expectedDelay, computedDelay); } } -- cgit v1.2.3 From 9704a8eb12576494a283b5c44ffe4a42b29653aa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 11 Jun 2021 16:03:46 -0500 Subject: simplify --- src/slskd/Common/Compute.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index ef1f1882..0e75be0c 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -29,8 +29,7 @@ namespace slskd iteration = Math.Min(100, iteration); var computedDelay = Math.Floor((Math.Pow(2, iteration) - 1) / 2) * 1000; - var safeDelay = (int)Math.Min(computedDelay, int.MaxValue); - var clampedDelay = Math.Min(safeDelay, maxDelayInMilliseconds); + var clampedDelay = (int)Math.Min(computedDelay, maxDelayInMilliseconds); var jitter = new Random().Next(1000); -- cgit v1.2.3 From 1f5c1557da3a1dc7d5727456994ae6222f83b6b4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 12 Jun 2021 17:56:06 -0500 Subject: make it actually reconnect indefinitely --- src/slskd/Core/Service.cs | 47 ++++++++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Service.cs b/src/slskd/Core/Service.cs index a8324a75..5800ffa0 100644 --- a/src/slskd/Core/Service.cs +++ b/src/slskd/Core/Service.cs @@ -39,7 +39,6 @@ namespace slskd public class Service : IHostedService { private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes - private static int reconnectAttempts = 0; private static (int Directories, int Files) sharedCounts = (0, 0); @@ -143,16 +142,14 @@ namespace slskd public async Task StartAsync(CancellationToken cancellationToken) { - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password).ConfigureAwait(false); - if (UsingProxy) { Logger.Information($"Using Proxy {Options.Soulseek.Connection.Proxy.Address}:{Options.Soulseek.Connection.Proxy.Port}"); } - Logger.Information("Connected and logged in as {Username}", Options.Soulseek.Username); - Logger.Information("Listening on port {Port}", Options.Soulseek.ListenPort); Logger.Information("Client started"); + Logger.Information("Listening on port {Port}", Options.Soulseek.ListenPort); + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password).ConfigureAwait(false); } public Task StopAsync(CancellationToken cancellationToken) @@ -211,7 +208,7 @@ namespace slskd private void Client_Connected(object sender, EventArgs e) { - Interlocked.Exchange(ref reconnectAttempts, 0); + Logger.Information("Connected and logged in as {Username}", Options.Soulseek.Username); } private async void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args) @@ -230,17 +227,33 @@ namespace slskd } else { - var (delay, jitter) = Compute.ExponentialBackoffDelay( - iteration: reconnectAttempts, - maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); - - Logger.Information($"Waiting {delay + jitter} millisecond(s) before reconnecting..."); - await Task.Delay(delay + jitter); - - Interlocked.Increment(ref reconnectAttempts); - - Logger.Information($"Attepting to reconnect (#{reconnectAttempts})...", reconnectAttempts); - await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception.Message); + + var attempts = 1; + + while (true) + { + var (delay, jitter) = Compute.ExponentialBackoffDelay( + iteration: attempts, + maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); + + var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); + Logger.Information($"Waiting about {(approximateDelay == 1 ? "a second" : $"{approximateDelay} seconds")} before reconnecting"); + await Task.Delay(delay + jitter); + + Logger.Information($"Attempting to reconnect (#{attempts})...", attempts); + + try + { + await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password); + break; + } + catch (Exception ex) + { + attempts++; + Logger.Error("Failed to reconnect: {Message}", ex.Message); + } + } } } -- cgit v1.2.3 From 5e4306f3dc77515401c24bf6d5a4c6780d494c84 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 13 Jun 2021 13:10:12 -0500 Subject: tweak docs --- src/slskd/Common/Compute.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index 0e75be0c..172de252 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -20,7 +20,7 @@ namespace slskd using System; /// - /// Static utility methods that don't otherwise work well as extensions. + /// Computational functions. /// public static class Compute { -- cgit v1.2.3