aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Network/NetworkClient.cs
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-11-08 07:46:30 -0600
committerGitHub <noreply@github.com>2022-11-08 07:46:30 -0600
commit7850ce245d51c80b0b05f59523d866dae2303669 (patch)
tree7658ca859d3563c1b4f773d7bd1d707662fcd015 /src/slskd/Network/NetworkClient.cs
parentf03520a84f7ce90339f0339bb4bd7e7d0d34a856 (diff)
parent74dbb69973035a93e2eda532bd6afe7e2f89d741 (diff)
downloadslskd-7850ce245d51c80b0b05f59523d866dae2303669.tar.gz
Merge pull request #739 from slskd/network-state
Add network state to application state
Diffstat (limited to 'src/slskd/Network/NetworkClient.cs')
-rw-r--r--src/slskd/Network/NetworkClient.cs72
1 files changed, 64 insertions, 8 deletions
diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs
index bf79a790..207494ff 100644
--- a/src/slskd/Network/NetworkClient.cs
+++ b/src/slskd/Network/NetworkClient.cs
@@ -32,9 +32,14 @@ namespace slskd.Network
/// <summary>
/// Network client (agent).
/// </summary>
- public interface INetworkClient
+ public interface INetworkClient : IDisposable
{
/// <summary>
+ /// Gets the client state.
+ /// </summary>
+ IStateMonitor<NetworkClientState> StateMonitor { get; }
+
+ /// <summary>
/// Starts the client and connects to the controller.
/// </summary>
/// <param name="cancellationToken"></param>
@@ -52,7 +57,7 @@ namespace slskd.Network
/// Synchronizes state with the controller.
/// </summary>
/// <returns>The operation context.</returns>
- Task SynchronizeAsync();
+ Task SynchronizeAsync(CancellationToken cancellationToken = default);
}
/// <summary>
@@ -75,12 +80,20 @@ namespace slskd.Network
HttpClientFactory = httpClientFactory;
+ StateMonitor = State;
+
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(options => Configure(options));
Configure(OptionsMonitor.CurrentValue);
}
+ /// <summary>
+ /// Gets the client state.
+ /// </summary>
+ public IStateMonitor<NetworkClientState> StateMonitor { get; }
+
+ private ManagedState<NetworkClientState> State { get; } = new();
private IShareService Shares { get; }
private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1);
private string LastOptionsHash { get; set; }
@@ -92,6 +105,7 @@ namespace slskd.Network
private ILogger Log { get; } = Serilog.Log.ForContext<NetworkClient>();
private bool LoggedIn { get; set; }
private TaskCompletionSource LoggedInTaskCompletionSource { get; set; }
+ private bool Disposed { get; set; }
/// <summary>
/// Starts the client and connects to the controller.
@@ -100,7 +114,9 @@ namespace slskd.Network
/// <returns></returns>
public async Task StartAsync(CancellationToken cancellationToken = default)
{
- if (OptionsMonitor.CurrentValue.Network.Mode.ToEnum<OperationMode>() != OperationMode.Agent && !OptionsMonitor.CurrentValue.Flags.DualNetworkMode)
+ var mode = OptionsMonitor.CurrentValue.Network.Mode.ToEnum<OperationMode>();
+
+ if (mode != OperationMode.Agent && mode != OperationMode.Debug)
{
throw new InvalidOperationException($"Network client can only be started when operation mode is {OperationMode.Agent}");
}
@@ -111,15 +127,22 @@ namespace slskd.Network
Log.Information("Attempting to connect to the network controller {Address}", OptionsMonitor.CurrentValue.Network.Controller.Address);
+ State.SetValue(_ => TranslateState(HubConnectionState.Connecting));
+
// retry indefinitely
await Retry.Do(
task: () => HubConnection.StartAsync(StartCancellationTokenSource.Token),
isRetryable: (attempts, ex) => true,
- onFailure: (attempts, ex) => Log.Warning("Failed attempt #{Attempts} to connect to network controller: {Message}", attempts, ex.Message),
+ onFailure: (attempts, ex) =>
+ {
+ Log.Debug(ex, "Network hub connection failure");
+ Log.Warning("Failed attempt #{Attempts} to connect to network controller: {Message}", attempts, ex.Message);
+ },
maxAttempts: int.MaxValue,
maxDelayInMilliseconds: 30000,
StartCancellationTokenSource.Token);
+ State.SetValue(_ => TranslateState(HubConnection.State));
Log.Information("Network controller connection established. Awaiting authentication...");
await LoggedInTaskCompletionSource.Task;
@@ -166,12 +189,21 @@ namespace slskd.Network
/// Synchronizes state with the controller.
/// </summary>
/// <returns>The operation context.</returns>
- public Task SynchronizeAsync()
+ public Task SynchronizeAsync(CancellationToken cancellationToken = default)
{
return UploadSharesAsync();
}
- private async Task UploadSharesAsync()
+ private NetworkClientState TranslateState(HubConnectionState hub) => hub switch
+ {
+ HubConnectionState.Disconnected => NetworkClientState.Disconnected,
+ HubConnectionState.Connected => NetworkClientState.Connected,
+ HubConnectionState.Connecting => NetworkClientState.Connecting,
+ HubConnectionState.Reconnecting => NetworkClientState.Reconnecting,
+ _ => throw new ArgumentException($"Unexpected HubConnectionState {hub}"),
+ };
+
+ private async Task UploadSharesAsync(CancellationToken cancellationToken = default)
{
if (!LoggedIn)
{
@@ -207,7 +239,7 @@ namespace slskd.Network
request.Content = content;
Log.Information("Beginning upload of shares");
- var response = await CreateHttpClient().SendAsync(request);
+ var response = await CreateHttpClient().SendAsync(request, cancellationToken);
if (!response.IsSuccessStatusCode)
{
@@ -338,6 +370,7 @@ namespace slskd.Network
{
Log.Warning("Network controller connection closed: {Message}", arg.Message);
LoggedIn = false;
+ State.SetValue(_ => TranslateState(HubConnection.State));
return Task.CompletedTask;
}
@@ -345,6 +378,7 @@ namespace slskd.Network
{
Log.Warning("Network controller connection reconnecting: {Message}", arg.Message);
LoggedIn = false;
+ State.SetValue(_ => TranslateState(HubConnection.State));
return Task.CompletedTask;
}
@@ -353,6 +387,7 @@ namespace slskd.Network
Log.Warning("Network 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();
}
@@ -381,7 +416,9 @@ namespace slskd.Network
private void Configure(Options options)
{
- if (options.Network.Mode.ToEnum<OperationMode>() != OperationMode.Agent && !options.Flags.DualNetworkMode)
+ var mode = options.Network.Mode.ToEnum<OperationMode>();
+
+ if (mode != OperationMode.Agent && mode != OperationMode.Debug)
{
return;
}
@@ -461,5 +498,24 @@ namespace slskd.Network
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);
+ }
}
}