aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2023-01-07 19:54:38 -0600
committerGitHub <noreply@github.com>2023-01-07 19:54:38 -0600
commitacde02e5acf72e0649ef0f1fc47d377868a3c90e (patch)
tree7c12350fc0f7ecdc11da8e7c86b18a126d15776e /src
parentd74137862bdbfab63a6c1ad61b8a22f650d99332 (diff)
parent8e6e0e17edf8f958b4b5bf072491d8198d9ef64c (diff)
downloadslskd-acde02e5acf72e0649ef0f1fc47d377868a3c90e.tar.gz
Merge pull request #829 from slskd/nags
Fix a bunch of linter warnings, include share upload in agent connection retry loop
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs1
-rw-r--r--src/slskd/Common/CommonExtensions.cs4
-rw-r--r--src/slskd/Core/API/DTO/TokenResponse.cs2
-rw-r--r--src/slskd/Program.cs2
-rw-r--r--src/slskd/Relay/DummyRelayClient.cs18
-rw-r--r--src/slskd/Relay/RelayClient.cs458
-rw-r--r--src/slskd/Shares/API/Controllers/SharesController.cs2
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs2
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs1
-rw-r--r--src/slskd/Users/API/Controllers/UsersController.cs2
10 files changed, 260 insertions, 232 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 01df00a1..48406931 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -753,6 +753,7 @@ namespace slskd
private void Client_UserStatusChanged(object sender, UserStatus args)
{
+ // todo: react to watched user status changes
}
private Task<int?> PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename)
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs
index 3ccc72e9..3dddd3b4 100644
--- a/src/slskd/Common/CommonExtensions.cs
+++ b/src/slskd/Common/CommonExtensions.cs
@@ -302,7 +302,7 @@ namespace slskd
}
/// <summary>
- /// <see cref="Path.GetDirectoryName"/>, but for paths normalized to use backslashes.
+ /// <see cref="Path.GetDirectoryName(string)"/>, but for paths normalized to use backslashes.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
@@ -312,7 +312,7 @@ namespace slskd
}
/// <summary>
- /// <see cref="Path.GetFileName"/>, but for paths normalized to use backslashes.
+ /// <see cref="Path.GetFileName(string)"/>, but for paths normalized to use backslashes.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
diff --git a/src/slskd/Core/API/DTO/TokenResponse.cs b/src/slskd/Core/API/DTO/TokenResponse.cs
index 85992917..47cfd335 100644
--- a/src/slskd/Core/API/DTO/TokenResponse.cs
+++ b/src/slskd/Core/API/DTO/TokenResponse.cs
@@ -49,7 +49,7 @@ namespace slskd.Core.API
/// <summary>
/// Gets the value of the Not Before claim from the Access Token.
/// </summary>
- public long NotBefore => long.Parse(JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == "nbf").Value);
+ public long NotBefore => long.Parse(JwtSecurityToken.Claims.SingleOrDefault(c => c.Type == "nbf")?.Value ?? long.MaxValue.ToString());
/// <summary>
/// Gets the Access Token string.
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 969ff53f..66773cb5 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -687,7 +687,7 @@ namespace slskd
}
catch
{
- // the token either isn't a valid API key. use the provided value and let the
+ // the token either isn't a valid API key. use the provided value and let the
// rest of the auth middleware figure out whether it is valid
context.Token = token;
}
diff --git a/src/slskd/Relay/DummyRelayClient.cs b/src/slskd/Relay/DummyRelayClient.cs
index dca4f808..c5bd477c 100644
--- a/src/slskd/Relay/DummyRelayClient.cs
+++ b/src/slskd/Relay/DummyRelayClient.cs
@@ -24,12 +24,26 @@ namespace slskd.Relay
{
public IStateMonitor<RelayClientState> StateMonitor => new ManagedState<RelayClientState>();
- public void Dispose() { }
+ private bool Disposed { get; set; }
+
+ public void Dispose()
+ {
+ Dispose(disposing: true);
+ System.GC.SuppressFinalize(this);
+ }
public Task StartAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
public Task SynchronizeAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (!Disposed)
+ {
+ Disposed = true;
+ }
+ }
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs
index c2d396a8..052eef79 100644
--- a/src/slskd/Relay/RelayClient.cs
+++ b/src/slskd/Relay/RelayClient.cs
@@ -94,20 +94,29 @@ namespace slskd.Relay
/// </summary>
public IStateMonitor<RelayClientState> StateMonitor { get; }
- private ManagedState<RelayClientState> State { get; } = new();
- private IShareService Shares { get; }
private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1);
- private SemaphoreSlim StateSyncRoot { get; } = new SemaphoreSlim(1, 1);
- private string LastOptionsHash { get; set; }
- private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private bool Disposed { get; set; }
private IHttpClientFactory HttpClientFactory { get; }
private HubConnection HubConnection { get; set; }
- private bool StartRequested { get; set; }
- private CancellationTokenSource StartCancellationTokenSource { get; set; }
+ private string LastOptionsHash { get; set; }
private ILogger Log { get; } = Serilog.Log.ForContext<RelayClient>();
private bool LoggedIn { get; set; }
private TaskCompletionSource LoggedInTaskCompletionSource { get; set; }
- private bool Disposed { get; set; }
+ private IOptionsMonitor<Options> OptionsMonitor { get; }
+ private IShareService Shares { get; }
+ private CancellationTokenSource StartCancellationTokenSource { get; set; }
+ private bool StartRequested { get; set; }
+ private ManagedState<RelayClientState> State { get; } = new();
+ private SemaphoreSlim StateSyncRoot { get; } = new SemaphoreSlim(1, 1);
+
+ /// <summary>
+ /// Disposes this instance.
+ /// </summary>
+ public void Dispose()
+ {
+ Dispose(disposing: true);
+ GC.SuppressFinalize(this);
+ }
/// <summary>
/// Starts the client and connects to the controller.
@@ -141,7 +150,36 @@ namespace slskd.Relay
// retry indefinitely
await Retry.Do(
- task: () => HubConnection.StartAsync(StartCancellationTokenSource.Token),
+ task: async () => {
+ await HubConnection.StartAsync(StartCancellationTokenSource.Token);
+
+ State.SetValue(_ => TranslateState(HubConnection.State));
+ Log.Information("Relay controller connection established. Awaiting authentication...");
+
+ await LoggedInTaskCompletionSource.Task;
+
+ LoggedIn = true;
+
+ Log.Information("Authenticated. Uploading shares...");
+
+ 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)
+ {
+ Log.Error(ex, ex.Message);
+ Log.Error("Disconnecting from the relay controller");
+ await StopAsync();
+ throw;
+ }
+
+ Log.Information("Shares uploaded. Ready to upload files.");
+ },
isRetryable: (attempts, ex) => true,
onFailure: (attempts, ex) =>
{
@@ -151,29 +189,6 @@ namespace slskd.Relay
maxAttempts: int.MaxValue,
maxDelayInMilliseconds: 30000,
StartCancellationTokenSource.Token);
-
- State.SetValue(_ => TranslateState(HubConnection.State));
- Log.Information("Relay controller connection established. Awaiting authentication...");
-
- await LoggedInTaskCompletionSource.Task;
-
- LoggedIn = true;
-
- Log.Information("Authenticated. Uploading shares...");
-
- try
- {
- await UploadSharesAsync();
- }
- catch (Exception ex)
- {
- Log.Error(ex, ex.Message);
- Log.Error("Disconnecting from the relay controller");
- await StopAsync();
- throw;
- }
-
- Log.Information("Shares uploaded. Ready to upload files.");
}
finally
{
@@ -211,85 +226,172 @@ namespace slskd.Relay
return UploadSharesAsync(cancellationToken);
}
- private RelayClientState TranslateState(HubConnectionState hub) => hub switch
+ /// <summary>
+ /// Disposes this instance.
+ /// </summary>
+ /// <param name="disposing"></param>
+ protected virtual void Dispose(bool disposing)
{
- HubConnectionState.Disconnected => RelayClientState.Disconnected,
- HubConnectionState.Connected => RelayClientState.Connected,
- HubConnectionState.Connecting => RelayClientState.Connecting,
- HubConnectionState.Reconnecting => RelayClientState.Reconnecting,
- _ => throw new ArgumentException($"Unexpected HubConnectionState {hub}"),
- };
+ if (!Disposed)
+ {
+ if (disposing)
+ {
+ _ = HubConnection?.DisposeAsync();
+ }
- private async Task UploadSharesAsync(CancellationToken cancellationToken = default)
+ Disposed = true;
+ }
+ }
+
+ private string ComputeCredential(string token)
{
- if (!LoggedIn)
+ var options = OptionsMonitor.CurrentValue;
+
+ var key = Pbkdf2.GetKey(options.Relay.Controller.Secret, options.InstanceName, 48);
+ var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token);
+
+ return Aes.Encrypt(tokenBytes, key).ToBase62();
+ }
+
+ private string ComputeCredential(Guid token) => ComputeCredential(token.ToString());
+
+ private void Configure(Options options)
+ {
+ var mode = options.Relay.Mode.ToEnum<RelayMode>();
+
+ if (mode != RelayMode.Agent && mode != RelayMode.Debug)
{
return;
}
- var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db");
-
- Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName));
+ ConfigurationSyncRoot.Wait();
try
{
- Log.Debug("Backing up shares to {Filename}", temp);
- await Shares.DumpAsync(temp);
- Log.Debug("Share backup successful");
+ var optionsHash = Compute.Sha1Hash(options.Relay.Controller.ToJson());
- Log.Debug("Requesting share upload token...");
- var token = await HubConnection.InvokeAsync<Guid>(nameof(RelayHub.BeginShareUpload));
- Log.Debug("Share upload token {Token}", token);
+ if (optionsHash == LastOptionsHash)
+ {
+ return;
+ }
- var stream = new FileStream(temp, FileMode.Open, FileAccess.Read);
+ Log.Debug("Relay options changed. Reconfiguring...");
- using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/shares/{token}");
+ // if the client is attempting a connection, cancel it it's going to be dropped when we create a new instance, but
+ // we need the retry loop around connection to stop.
+ StartCancellationTokenSource?.Cancel();
- request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey);
- request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName);
- request.Headers.Add("X-Relay-Credential", ComputeCredential(token));
+ HubConnection = new HubConnectionBuilder()
+ .WithUrl($"{options.Relay.Controller.Address}/hub/relay", builder =>
+ {
+ builder.AccessTokenProvider = () => Task.FromResult(options.Relay.Controller.ApiKey);
+ builder.HttpMessageHandlerFactory = (message) =>
+ {
+ if (message is HttpClientHandler clientHandler && options.Relay.Controller.IgnoreCertificateErrors)
+ {
+ clientHandler.ServerCertificateCustomValidationCallback += (_, _, _, _) => true;
+ }
- using var content = new MultipartFormDataContent
- {
- { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" },
- { new StreamContent(stream), "database", "shares" },
- };
+ return message;
+ };
+ })
+ .WithAutomaticReconnect(new ControllerRetryPolicy(0, 1, 3, 10, 30, 60))
+ .Build();
- request.Content = content;
+ HubConnection.Reconnected += HubConnection_Reconnected;
+ HubConnection.Reconnecting += HubConnection_Reconnecting;
+ HubConnection.Closed += HubConnection_Closed;
- var size = ((double)stream.Length).SizeSuffix();
- var sw = new Stopwatch();
- sw.Start();
+ HubConnection.On<string, long, Guid>(nameof(IRelayHub.RequestFileUpload), HandleFileUploadRequest);
+ HubConnection.On<string, Guid>(nameof(IRelayHub.RequestFileInfo), HandleFileInfoRequest);
+ HubConnection.On<string>(nameof(IRelayHub.Challenge), HandleAuthenticationChallenge);
+ HubConnection.On<string, Guid>(nameof(IRelayHub.NotifyFileDownloadCompleted), HandleNotifyFileDownloadCompleted);
- Log.Information("Beginning upload of shares ({Size})", size);
- Log.Debug("Shares: {Shares}", Shares.LocalHost.Shares.ToJson());
- var response = await CreateHttpClient().SendAsync(request, cancellationToken);
+ LastOptionsHash = optionsHash;
- if (!response.IsSuccessStatusCode)
+ Log.Debug("Relay options reconfigured");
+
+ // if start was requested (if StartAsync() was called externally), restart after re-configuration
+ if (StartRequested)
{
- throw new RelayException($"Failed to upload shares to relay controller: {response.StatusCode}");
+ Log.Information("Reconnecting the relay controller connection...");
+ _ = StartAsync();
}
-
- sw.Stop();
- Log.Information("Upload of shares succeeded ({Size} in {Duration}ms)", size, sw.ElapsedMilliseconds);
}
finally
{
- File.Delete(temp);
+ ConfigurationSyncRoot.Release();
}
}
- private string ComputeCredential(string token)
+ private HttpClient CreateHttpClient()
{
- var options = OptionsMonitor.CurrentValue;
+ var options = OptionsMonitor.CurrentValue.Relay.Controller;
+ HttpClient client;
- var key = Pbkdf2.GetKey(options.Relay.Controller.Secret, options.InstanceName, 48);
- var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token);
+ if (options.IgnoreCertificateErrors)
+ {
+ client = new HttpClient(new HttpClientHandler()
+ {
+ ClientCertificateOptions = ClientCertificateOption.Manual,
+ ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
+ });
+ }
+ else
+ {
+ client = new HttpClient();
+ }
- return Aes.Encrypt(tokenBytes, key).ToBase62();
+ client.Timeout = TimeSpan.FromMilliseconds(int.MaxValue);
+ client.BaseAddress = new(options.Address);
+ return client;
}
- private string ComputeCredential(Guid token) => ComputeCredential(token.ToString());
+ private async Task HandleAuthenticationChallenge(string challengeToken)
+ {
+ try
+ {
+ Log.Debug("Relay controller sent an authentication challenge");
+
+ var options = OptionsMonitor.CurrentValue;
+
+ var agent = options.InstanceName;
+ var response = ComputeCredential(challengeToken);
+
+ Log.Debug("Logging in...");
+ await HubConnection.InvokeAsync(nameof(RelayHub.Login), agent, response);
+ Log.Debug("Login succeeded.");
+ LoggedInTaskCompletionSource?.TrySetResult();
+ }
+ catch (UnauthorizedAccessException)
+ {
+ await HubConnection.StopAsync();
+ Log.Error("Relay controller authentication failed. Check configuration.");
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message);
+ }
+ }
+
+ private async Task HandleFileInfoRequest(string filename, Guid id)
+ {
+ Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id);
+
+ try
+ {
+ var (_, localFilename) = await Shares.ResolveFileAsync(filename);
+
+ var localFileInfo = new FileInfo(localFilename);
+
+ await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length);
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to handle file info request: {Message}", ex.Message);
+ await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0);
+ }
+ }
private Task HandleFileUploadRequest(string filename, long startOffset, Guid token)
{
@@ -350,52 +452,6 @@ namespace slskd.Relay
return Task.CompletedTask;
}
- private async Task HandleFileInfoRequest(string filename, Guid id)
- {
- Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id);
-
- try
- {
- var (_, localFilename) = await Shares.ResolveFileAsync(filename);
-
- var localFileInfo = new FileInfo(localFilename);
-
- await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, localFileInfo.Exists, localFileInfo.Length);
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to handle file info request: {Message}", ex.Message);
- await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0);
- }
- }
-
- private async Task HandleAuthenticationChallenge(string challengeToken)
- {
- try
- {
- Log.Debug("Relay controller sent an authentication challenge");
-
- var options = OptionsMonitor.CurrentValue;
-
- var agent = options.InstanceName;
- var response = ComputeCredential(challengeToken);
-
- Log.Debug("Logging in...");
- await HubConnection.InvokeAsync(nameof(RelayHub.Login), agent, response);
- Log.Debug("Login succeeded.");
- LoggedInTaskCompletionSource?.TrySetResult();
- }
- catch (UnauthorizedAccessException)
- {
- await HubConnection.StopAsync();
- Log.Error("Relay controller authentication failed. Check configuration.");
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message);
- }
- }
-
private Task HandleNotifyFileDownloadCompleted(string filename, Guid token)
{
if (!OptionsMonitor.CurrentValue.Relay.Controller.Downloads)
@@ -411,13 +467,13 @@ namespace slskd.Relay
if (OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug)
{
- // if we're debugging, we're referencing the same file for both the controller and agent
- // which will lead to an access violation. prefix the destination file to avoid this.
+ // if we're debugging, we're referencing the same file for both the controller and agent which will lead to an
+ // access violation. prefix the destination file to avoid this.
destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed");
}
- // if the controller is Windows and the agent is Linux or vice versa, we need to translate
- // the filename to the local OS or we're going to get funny results when we go to write the file
+ // if the controller is Windows and the agent is Linux or vice versa, we need to translate the filename to the
+ // local OS or we're going to get funny results when we go to write the file
destinationFile = destinationFile.LocalizePath();
await Retry.Do(task: async () =>
@@ -459,118 +515,93 @@ namespace slskd.Relay
return Task.CompletedTask;
}
- private Task HubConnection_Reconnecting(Exception arg)
- {
- Log.Warning("Relay controller connection reconnecting: {Message}", arg.Message);
- LoggedIn = false;
- State.SetValue(_ => TranslateState(HubConnection.State));
- return Task.CompletedTask;
- }
-
private async Task HubConnection_Reconnected(string arg)
{
Log.Warning("Relay controller connection reconnected");
+
// 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 HttpClient CreateHttpClient()
+ private Task HubConnection_Reconnecting(Exception arg)
{
- var options = OptionsMonitor.CurrentValue.Relay.Controller;
- HttpClient client;
-
- if (options.IgnoreCertificateErrors)
- {
- client = new HttpClient(new HttpClientHandler()
- {
- ClientCertificateOptions = ClientCertificateOption.Manual,
- ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
- });
- }
- else
- {
- client = new HttpClient();
- }
-
- client.Timeout = TimeSpan.FromMilliseconds(int.MaxValue);
- client.BaseAddress = new(options.Address);
- return client;
+ Log.Warning("Relay controller connection reconnecting: {Message}", arg.Message);
+ LoggedIn = false;
+ State.SetValue(_ => TranslateState(HubConnection.State));
+ return Task.CompletedTask;
}
- private void Configure(Options options)
+ private RelayClientState TranslateState(HubConnectionState hub) => hub switch
{
- var mode = options.Relay.Mode.ToEnum<RelayMode>();
+ HubConnectionState.Disconnected => RelayClientState.Disconnected,
+ HubConnectionState.Connected => RelayClientState.Connected,
+ HubConnectionState.Connecting => RelayClientState.Connecting,
+ HubConnectionState.Reconnecting => RelayClientState.Reconnecting,
+ _ => throw new ArgumentException($"Unexpected HubConnectionState {hub}"),
+ };
- if (mode != RelayMode.Agent && mode != RelayMode.Debug)
+ private async Task UploadSharesAsync(CancellationToken cancellationToken = default)
+ {
+ if (!LoggedIn)
{
return;
}
- ConfigurationSyncRoot.Wait();
+ var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db");
+
+ Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName));
try
{
- var optionsHash = Compute.Sha1Hash(options.Relay.Controller.ToJson());
-
- if (optionsHash == LastOptionsHash)
- {
- return;
- }
+ Log.Debug("Backing up shares to {Filename}", temp);
+ await Shares.DumpAsync(temp);
+ Log.Debug("Share backup successful");
- Log.Debug("Relay options changed. Reconfiguring...");
+ Log.Debug("Requesting share upload token...");
+ var token = await HubConnection.InvokeAsync<Guid>(nameof(RelayHub.BeginShareUpload));
+ Log.Debug("Share upload token {Token}", token);
- // if the client is attempting a connection, cancel it
- // it's going to be dropped when we create a new instance, but we need
- // the retry loop around connection to stop.
- StartCancellationTokenSource?.Cancel();
+ var stream = new FileStream(temp, FileMode.Open, FileAccess.Read);
- HubConnection = new HubConnectionBuilder()
- .WithUrl($"{options.Relay.Controller.Address}/hub/relay", builder =>
- {
- builder.AccessTokenProvider = () => Task.FromResult(options.Relay.Controller.ApiKey);
- builder.HttpMessageHandlerFactory = (message) =>
- {
- if (message is HttpClientHandler clientHandler && options.Relay.Controller.IgnoreCertificateErrors)
- {
- clientHandler.ServerCertificateCustomValidationCallback += (_, _, _, _) => true;
- }
+ using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/relay/shares/{token}");
- return message;
- };
- })
- .WithAutomaticReconnect(new ControllerRetryPolicy(0, 1, 3, 10, 30, 60))
- .Build();
+ request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Relay.Controller.ApiKey);
+ request.Headers.Add("X-Relay-Agent", OptionsMonitor.CurrentValue.InstanceName);
+ request.Headers.Add("X-Relay-Credential", ComputeCredential(token));
- HubConnection.Reconnected += HubConnection_Reconnected;
- HubConnection.Reconnecting += HubConnection_Reconnecting;
- HubConnection.Closed += HubConnection_Closed;
+ using var content = new MultipartFormDataContent
+ {
+ { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" },
+ { new StreamContent(stream), "database", "shares" },
+ };
- HubConnection.On<string, long, Guid>(nameof(IRelayHub.RequestFileUpload), HandleFileUploadRequest);
- HubConnection.On<string, Guid>(nameof(IRelayHub.RequestFileInfo), HandleFileInfoRequest);
- HubConnection.On<string>(nameof(IRelayHub.Challenge), HandleAuthenticationChallenge);
- HubConnection.On<string, Guid>(nameof(IRelayHub.NotifyFileDownloadCompleted), HandleNotifyFileDownloadCompleted);
+ request.Content = content;
- LastOptionsHash = optionsHash;
+ var size = ((double)stream.Length).SizeSuffix();
+ var sw = new Stopwatch();
+ sw.Start();
- Log.Debug("Relay options reconfigured");
+ Log.Information("Beginning upload of shares ({Size})", size);
+ Log.Debug("Shares: {Shares}", Shares.LocalHost.Shares.ToJson());
+ var response = await CreateHttpClient().SendAsync(request, cancellationToken);
- // if start was requested (if StartAsync() was called externally), restart
- // after re-configuration
- if (StartRequested)
+ if (!response.IsSuccessStatusCode)
{
- Log.Information("Reconnecting the relay controller connection...");
- _ = StartAsync();
+ throw new RelayException($"Failed to upload shares to relay controller: {response.StatusCode}");
}
+
+ sw.Stop();
+ Log.Information("Upload of shares succeeded ({Size} in {Duration}ms)", size, sw.ElapsedMilliseconds);
}
finally
{
- ConfigurationSyncRoot.Release();
+ File.Delete(temp);
}
}
- private class ControllerRetryPolicy : IRetryPolicy
+ private sealed class ControllerRetryPolicy : IRetryPolicy
{
public ControllerRetryPolicy(params int[] intervals)
{
@@ -584,24 +615,5 @@ namespace slskd.Relay
return TimeSpan.FromSeconds(Intervals[Math.Min(retryContext.PreviousRetryCount, Intervals.Length - 1)]);
}
}
-
- protected virtual void Dispose(bool disposing)
- {
- if (!Disposed)
- {
- if (disposing)
- {
- _ = HubConnection?.DisposeAsync();
- }
-
- Disposed = true;
- }
- }
-
- public void Dispose()
- {
- Dispose(disposing: true);
- GC.SuppressFinalize(this);
- }
}
-}
+} \ No newline at end of file
diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs
index e4f82848..2144a979 100644
--- a/src/slskd/Shares/API/Controllers/SharesController.cs
+++ b/src/slskd/Shares/API/Controllers/SharesController.cs
@@ -74,7 +74,7 @@ namespace slskd.Shares.API
[Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(typeof(Share), 200)]
[ProducesResponseType(404)]
- public async Task<IActionResult> Get(string id)
+ public IActionResult Get(string id)
{
var share = Shares.Hosts.SelectMany(host => host.Shares).FirstOrDefault(share => share.Id == id);
diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index a4c4dd4c..f10b55e5 100644
--- a/src/slskd/Shares/SqliteShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -672,7 +672,7 @@ namespace slskd.Shares
var msg = "The internal share database has been corrupted or lost, and the application cannot continue to run. Please report this in a GitHub issue here: https://github.com/slskd/slskd/issues";
Log.Fatal(msg);
Environment.Exit(1);
- throw new ApplicationException(msg);
+ throw new DataMisalignedException(msg);
}
}
}
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index d664ae5d..aea815af 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -41,6 +41,7 @@ namespace slskd.Transfers.API
/// <summary>
/// Initializes a new instance of the <see cref="TransfersController"/> class.
/// </summary>
+ /// <param name="optionsSnapshot"></param>
/// <param name="transferService"></param>
public TransfersController(
ITransferService transferService,
diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs
index fc1ac415..c336dbd3 100644
--- a/src/slskd/Users/API/Controllers/UsersController.cs
+++ b/src/slskd/Users/API/Controllers/UsersController.cs
@@ -25,7 +25,6 @@ namespace slskd.Users.API
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
- using slskd.Relay;
using Soulseek;
/// <summary>
@@ -44,6 +43,7 @@ namespace slskd.Users.API
/// <param name="soulseekClient"></param>
/// <param name="browseTracker"></param>
/// <param name="userService"></param>
+ /// <param name="optionsSnapshot"></param>
public UsersController(ISoulseekClient soulseekClient, IBrowseTracker browseTracker, IUserService userService, IOptionsSnapshot<Options> optionsSnapshot)
{
Client = soulseekClient;