aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2021-06-13 14:04:29 -0500
committerGitHub <noreply@github.com>2021-06-13 14:04:29 -0500
commitbd173e1bcb8640744ac32fcfe9f114f2f0f31df0 (patch)
tree813887e28dbf9d3b36d3489401af9cafdedbbec4
parent4602c588e6bd6a607a23f35690d670837d87d4d1 (diff)
parent5e4306f3dc77515401c24bf6d5a4c6780d494c84 (diff)
downloadslskd-bd173e1bcb8640744ac32fcfe9f114f2f0f31df0.tar.gz
Merge pull request #95 from slskd/reconnect
Attempt to reconnect automatically following a disconnect
-rw-r--r--src/slskd/Common/Compute.cs39
-rw-r--r--src/slskd/Core/Service.cs69
-rw-r--r--tests/slskd.Tests.Unit/Common/ComputeTests.cs21
-rw-r--r--tests/slskd.Tests.Unit/UnitTest1.cs14
-rw-r--r--tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj6
5 files changed, 111 insertions, 38 deletions
diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs
new file mode 100644
index 00000000..172de252
--- /dev/null
+++ b/src/slskd/Common/Compute.cs
@@ -0,0 +1,39 @@
+// <copyright file="Compute.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>
+
+namespace slskd
+{
+ using System;
+
+ /// <summary>
+ /// Computational functions.
+ /// </summary>
+ public static class Compute
+ {
+ public static (int Delay, int Jitter) ExponentialBackoffDelay(int iteration, int maxDelayInMilliseconds = int.MaxValue)
+ {
+ iteration = Math.Min(100, iteration);
+
+ var computedDelay = Math.Floor((Math.Pow(2, iteration) - 1) / 2) * 1000;
+ var clampedDelay = (int)Math.Min(computedDelay, 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 6df1ddcb..5800ffa0 100644
--- a/src/slskd/Core/Service.cs
+++ b/src/slskd/Core/Service.cs
@@ -38,8 +38,8 @@ namespace slskd
public class Service : IHostedService
{
- private static readonly int MaxReconnectAttempts = 3;
- private static int currentReconnectAttempts = 0;
+ private static readonly int ReconnectMaxDelayMilliseconds = 300000; // 5 minutes
+
private static (int Directories, int Files) sharedCounts = (0, 0);
public Service(
@@ -121,6 +121,7 @@ namespace slskd
Client.RoomJoined += Client_RoomJoined;
Client.RoomLeft += Client_RoomLeft;
Client.Disconnected += Client_Disconnected;
+ Client.Connected += Client_Connected;
SoulseekClient = Client;
@@ -141,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)
@@ -207,29 +206,53 @@ 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}");
+ Logger.Information("Connected and logged in as {Username}", Options.Soulseek.Username);
+ }
- // 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)
+ {
+ 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
{
- Interlocked.Increment(ref currentReconnectAttempts);
+ Logger.Error("Disconnected from the Soulseek server: {Message}", args.Exception.Message);
- if (currentReconnectAttempts <= MaxReconnectAttempts)
- {
- var wait = (int)Math.Pow(currentReconnectAttempts, 3);
- Console.WriteLine($"Waiting {wait} second(s) before reconnect...");
- await Task.Delay(wait);
+ var attempts = 1;
- Console.WriteLine($"Attepting to reconnect...");
- await Client.ConnectAsync(Options.Soulseek.Username, Options.Soulseek.Password);
- }
- else
+ while (true)
{
- Console.WriteLine($"Unable to reconnect after {currentReconnectAttempts} tries.");
+ 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);
+ }
}
}
}
diff --git a/tests/slskd.Tests.Unit/Common/ComputeTests.cs b/tests/slskd.Tests.Unit/Common/ComputeTests.cs
new file mode 100644
index 00000000..5a7922f6
--- /dev/null
+++ b/tests/slskd.Tests.Unit/Common/ComputeTests.cs
@@ -0,0 +1,21 @@
+namespace slskd.Tests.Unit
+{
+ using Xunit;
+
+ public class ComputeTests
+ {
+ [Theory]
+ [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, maxDelayInMs);
+ Assert.Equal(expectedDelay, computedDelay);
+ }
+ }
+}
diff --git a/tests/slskd.Tests.Unit/UnitTest1.cs b/tests/slskd.Tests.Unit/UnitTest1.cs
deleted file mode 100644
index acba06cd..00000000
--- a/tests/slskd.Tests.Unit/UnitTest1.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-using System;
-using Xunit;
-
-namespace slskd.Tests.Unit
-{
- public class UnitTest1
- {
- [Fact]
- public void Test1()
- {
-
- }
- }
-}
diff --git a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj
index 89e935fa..569f124c 100644
--- a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj
+++ b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj
@@ -1,4 +1,4 @@
-<Project Sdk="Microsoft.NET.Sdk">
+<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
@@ -19,4 +19,8 @@
</PackageReference>
</ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\..\src\slskd\slskd.csproj" />
+ </ItemGroup>
+
</Project>