From dc90af169b47d0e869ba08064f3f8f0f70fd9a0d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 14:32:26 -0600 Subject: only log on reconnect --- src/slskd/Relay/RelayClient.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 4809df62..578a311e 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -516,10 +516,12 @@ namespace slskd.Relay return Task.CompletedTask; } - private async Task HubConnection_Reconnected(string arg) + private Task HubConnection_Reconnected(string arg) { + // upon reconnection, the authentication flow is started again. + // there's nothing that needs to be done upon reconnection, only log. Log.Warning("Relay controller connection reconnected"); - + return Task.CompletedTask; // todo: does this need to log in again? does it retain the same connection id? LoggedIn = true; State.SetValue(_ => TranslateState(HubConnection.State)); -- cgit v1.2.3 From 2e221feed97ad095d177e10850df9c606a26eca6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 14:47:00 -0600 Subject: don't wait before attempting uploading --- src/slskd/Relay/RelayClient.cs | 4 ---- 1 file changed, 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 578a311e..9f11bfe9 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -165,10 +165,6 @@ namespace slskd.Relay try { - // give the controller time to register the login; there's a race condition here - // that should be extremely unlikely, but i've seen it when debugging. - await Task.Delay(500); - await UploadSharesAsync(); } catch (Exception ex) -- cgit v1.2.3 From 8943bd3cecd25897cd68188975b79b7d4d765e36 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 14:47:15 -0600 Subject: don't upload on reconnect --- src/slskd/Relay/RelayClient.cs | 4 ---- 1 file changed, 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 9f11bfe9..eb3e5363 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -518,10 +518,6 @@ namespace slskd.Relay // there's nothing that needs to be done upon reconnection, only log. Log.Warning("Relay controller connection reconnected"); return Task.CompletedTask; - // todo: does this need to log in again? does it retain the same connection id? - LoggedIn = true; - State.SetValue(_ => TranslateState(HubConnection.State)); - await UploadSharesAsync(); } private Task HubConnection_Reconnecting(Exception arg) -- cgit v1.2.3 From 146928eed2375cb8b8f8175d1957e0ceb1e3128e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 15:56:25 -0600 Subject: add TimeoutAfter() extensions --- src/slskd/Common/CommonExtensions.cs | 53 ++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 3dddd3b4..d18a88e1 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -23,12 +23,12 @@ namespace slskd using System.IdentityModel.Tokens.Jwt; using System.IO; using System.Linq; - using System.Numerics; using System.Reflection; - using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; @@ -37,6 +37,55 @@ namespace slskd /// public static class CommonExtensions { + /// + /// Times this Task out after the specified TimeSpan. + /// + /// The result type. + /// The task. + /// The timeout. + /// The operation context. + /// Thrown when the task times out. + public static async Task TimeoutAfter(this Task task, TimeSpan timeout) + { + using var timeoutCancellationTokenSource = new CancellationTokenSource(); + + var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); + + if (completedTask == task) + { + timeoutCancellationTokenSource.Cancel(); + return await task; + } + else + { + throw new TimeoutException("The operation has timed out."); + } + } + + /// + /// Times this Task out after the specified TimeSpan. + /// + /// The result type. + /// The task. + /// The timeout. + /// Thrown when the task times out. + public static async Task TimeoutAfter(this Task task, TimeSpan timeout) + { + using var timeoutCancellationTokenSource = new CancellationTokenSource(); + + var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token)); + + if (completedTask == task) + { + timeoutCancellationTokenSource.Cancel(); + await task; + } + else + { + throw new TimeoutException("The operation has timed out."); + } + } + /// /// Deeply compares this object with the specified object and returns a list of properties that are different. /// -- cgit v1.2.3 From 0733f863b1fbd0c1e06f72de21b0370caee4923f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 15:58:51 -0600 Subject: set LoggedIn during auth --- src/slskd/Relay/RelayClient.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index eb3e5363..6f6f5428 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -356,9 +356,13 @@ namespace slskd.Relay var response = ComputeCredential(challengeToken); Log.Information("Logging in..."); + await HubConnection.InvokeAsync(nameof(RelayHub.Login), agent, response); + + LoggedIn = true; + LoggedInTaskCompletionSource.TrySetResult(); + Log.Information("Login succeeded."); - LoggedInTaskCompletionSource?.TrySetResult(); } catch (UnauthorizedAccessException) { -- cgit v1.2.3 From 520482de72f2844c09c4b18e7d9790d549257fa6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 16:00:17 -0600 Subject: make upload more resilient to auth timing --- src/slskd/Relay/RelayClient.cs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 6f6f5428..dabde123 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -550,16 +550,32 @@ namespace slskd.Relay var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db"); - Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName)); - try { Log.Debug("Backing up shares to {Filename}", temp); + + Directory.CreateDirectory(Path.GetDirectoryName(temp)); + await Shares.DumpAsync(temp); - Log.Debug("Share backup successful"); + Log.Debug("Share backup successful"); Log.Debug("Requesting share upload token..."); - var token = await HubConnection.InvokeAsync(nameof(RelayHub.BeginShareUpload)); + + Guid token = Guid.Empty; + + // retry this a few times. it can throw if a race condition materializes + // between this logic and the authentication flow, and it'll almost certainly be + // worked out properly if we just wait a second and try again + await Retry.Do(task: async () => + { + token = await HubConnection.InvokeAsync(nameof(RelayHub.BeginShareUpload)); + }, + isRetryable: (_, _) => true, + onFailure: (count, ex) => Log.Warning("Failed attempt #{Attempts} to obtain share upload token: {Message}", count, ex.Message), + maxAttempts: 3, + maxDelayInMilliseconds: 5000, + cancellationToken); + Log.Debug("Share upload token {Token}", token); var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); -- cgit v1.2.3 From b61f219bf9e96721fe2df038af7e276e75ebe1e8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 16:00:48 -0600 Subject: add ResetLoggedInState --- src/slskd/Relay/RelayClient.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index dabde123..9d648b80 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -527,9 +527,18 @@ namespace slskd.Relay private Task HubConnection_Reconnecting(Exception arg) { Log.Warning("Relay controller connection reconnecting: {Message}", arg.Message); + private void ResetLoggedInState() + { LoggedIn = false; State.SetValue(_ => TranslateState(HubConnection.State)); - return Task.CompletedTask; + + var old = LoggedInTaskCompletionSource; + + LoggedInTaskCompletionSource = new TaskCompletionSource(); + + // in case someone was waiting on this, cancel it + // _very important_ to avoid deadlocks + old.TrySetCanceled(); } private RelayClientState TranslateState(HubConnectionState hub) => hub switch -- cgit v1.2.3 From a37b61767410fea15aa8cf57c944ea23c495f6d4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 16:02:33 -0600 Subject: reset logged in state in various places --- src/slskd/Relay/RelayClient.cs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 9d648b80..58bda800 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -206,8 +206,7 @@ namespace slskd.Relay { await HubConnection.StopAsync(cancellationToken); - LoggedIn = false; - + ResetLoggedInState(); State.SetValue(_ => TranslateState(HubConnectionState.Disconnected)); Log.Information("Relay controller connection disconnected"); @@ -511,15 +510,18 @@ namespace slskd.Relay private Task HubConnection_Closed(Exception arg) { Log.Warning("Relay controller connection closed: {Message}", arg.Message); - LoggedIn = false; - State.SetValue(_ => TranslateState(HubConnection.State)); + ResetLoggedInState(); + return Task.CompletedTask; } private Task HubConnection_Reconnected(string arg) { - // upon reconnection, the authentication flow is started again. - // there's nothing that needs to be done upon reconnection, only log. + // upon reconnection, the authentication flow is started again. this may happen before the client + // realizes the connection has been closed, so reset everything as though we're just learning that + // there has been a disconnect + ResetLoggedInState(); + Log.Warning("Relay controller connection reconnected"); return Task.CompletedTask; } @@ -527,6 +529,11 @@ namespace slskd.Relay private Task HubConnection_Reconnecting(Exception arg) { Log.Warning("Relay controller connection reconnecting: {Message}", arg.Message); + ResetLoggedInState(); + + return Task.CompletedTask; + } + private void ResetLoggedInState() { LoggedIn = false; -- cgit v1.2.3 From 5a5621a74daa99cd3b98815924f5bb8c24fd9db0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 16:02:58 -0600 Subject: add back upload of shares on reconnect --- src/slskd/Relay/RelayClient.cs | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 58bda800..38d8446a 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -515,7 +515,7 @@ namespace slskd.Relay return Task.CompletedTask; } - private Task HubConnection_Reconnected(string arg) + private async Task HubConnection_Reconnected(string arg) { // upon reconnection, the authentication flow is started again. this may happen before the client // realizes the connection has been closed, so reset everything as though we're just learning that @@ -523,7 +523,28 @@ namespace slskd.Relay ResetLoggedInState(); Log.Warning("Relay controller connection reconnected"); - return Task.CompletedTask; + + try + { + // wait for the authentication flow to complete + // time out after 5 seconds in case we get stuck waiting on a dead Task + await LoggedInTaskCompletionSource.Task; + + Log.Information("Uploading shares..."); + + await UploadSharesAsync(); + } + catch (Exception ex) + { + Log.Error(ex, ex.Message); + Log.Error("Disconnecting from the relay controller"); + + // stop, then fire and forget StartAsync() to re-enter the connection retry loop + await StopAsync(); + _ = StartAsync(); + } + + Log.Information("Shares uploaded. Ready to relay files."); } private Task HubConnection_Reconnecting(Exception arg) -- cgit v1.2.3 From 9d255b4d93560758bf4c90d31d36ceed59867161 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 16:04:22 -0600 Subject: refactor share upload logic when connecting --- src/slskd/Relay/RelayClient.cs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 38d8446a..a1ca2325 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -141,27 +141,27 @@ namespace slskd.Relay } StartCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - LoggedInTaskCompletionSource = new TaskCompletionSource(); StartRequested = true; - Log.Information("Attempting to connect to the relay controller {Address}", OptionsMonitor.CurrentValue.Relay.Controller.Address); - - State.SetValue(_ => TranslateState(HubConnectionState.Connecting)); - // retry indefinitely await Retry.Do( task: async () => { + Log.Information("Attempting to connect to the relay controller {Address}", OptionsMonitor.CurrentValue.Relay.Controller.Address); + + ResetLoggedInState(); + State.SetValue(_ => TranslateState(HubConnectionState.Connecting)); + await HubConnection.StartAsync(StartCancellationTokenSource.Token); State.SetValue(_ => TranslateState(HubConnection.State)); Log.Information("Relay controller connection established. Awaiting authentication..."); + // the controller will send an authentication challenge immediately after connection + // wait for the auth handler to log in before proceeding with the initial share upload await LoggedInTaskCompletionSource.Task; - LoggedIn = true; - - Log.Information("Authenticated. Uploading shares..."); + Log.Information("Uploading shares..."); try { @@ -171,15 +171,20 @@ namespace slskd.Relay { Log.Error(ex, ex.Message); Log.Error("Disconnecting from the relay controller"); + + // stop, so we can start again when the retry loop comes back around await StopAsync(); + + // throw, to trigger a retry throw; } - Log.Information("Shares uploaded. Ready to upload files."); + Log.Information("Shares uploaded. Ready to relay files."); }, isRetryable: (attempts, ex) => true, onFailure: (attempts, ex) => { + Console.Log(ex); Log.Debug(ex, "Relay hub connection failure"); Log.Warning("Failed attempt #{Attempts} to connect to relay controller: {Message}", attempts, ex.Message); }, -- cgit v1.2.3 From 9fccf0a17393d1c29203739cc663c110c6054450 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 16:18:27 -0600 Subject: this isn't javascript --- src/slskd/Relay/RelayClient.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index a1ca2325..92d09a17 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -184,7 +184,7 @@ namespace slskd.Relay isRetryable: (attempts, ex) => true, onFailure: (attempts, ex) => { - Console.Log(ex); + Console.WriteLine(ex); Log.Debug(ex, "Relay hub connection failure"); Log.Warning("Failed attempt #{Attempts} to connect to relay controller: {Message}", attempts, ex.Message); }, -- cgit v1.2.3 From fba17ebb02ae0fafe028c4cf88bb988d437bf44a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 16:20:58 -0600 Subject: warnings --- src/slskd/Common/CommonExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index d18a88e1..6a472b9b 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -65,9 +65,9 @@ namespace slskd /// /// Times this Task out after the specified TimeSpan. /// - /// The result type. /// The task. /// The timeout. + /// The operation context. /// Thrown when the task times out. public static async Task TimeoutAfter(this Task task, TimeSpan timeout) { -- cgit v1.2.3 From 05e5e91c221f55a1cf967c106ef9cfc00e646932 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 16:21:05 -0600 Subject: fix null ref --- src/slskd/Relay/RelayClient.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 92d09a17..caef2c6f 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -184,7 +184,6 @@ namespace slskd.Relay isRetryable: (attempts, ex) => true, onFailure: (attempts, ex) => { - Console.WriteLine(ex); Log.Debug(ex, "Relay hub connection failure"); Log.Warning("Failed attempt #{Attempts} to connect to relay controller: {Message}", attempts, ex.Message); }, @@ -571,7 +570,7 @@ namespace slskd.Relay // in case someone was waiting on this, cancel it // _very important_ to avoid deadlocks - old.TrySetCanceled(); + old?.TrySetCanceled(); } private RelayClientState TranslateState(HubConnectionState hub) => hub switch -- cgit v1.2.3 From 6e787074c427773acb40f7191c68bf2afaaf7635 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Jan 2023 16:26:21 -0600 Subject: set TCS result after logging --- src/slskd/Relay/RelayClient.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index caef2c6f..dae89f78 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -363,9 +363,9 @@ namespace slskd.Relay await HubConnection.InvokeAsync(nameof(RelayHub.Login), agent, response); LoggedIn = true; - LoggedInTaskCompletionSource.TrySetResult(); - Log.Information("Login succeeded."); + + LoggedInTaskCompletionSource.TrySetResult(); } catch (UnauthorizedAccessException) { -- cgit v1.2.3