From dd6c371ba4a5011d853a355ea6081a9bde92307b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Nov 2022 17:16:36 -0600 Subject: handle Network state changes --- src/slskd/Application.cs | 2 + src/slskd/Network/NetworkService.cs | 102 ++++++++++++++++++++++++++++++++++-- 2 files changed, 99 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 5e4faad4..33ed2f29 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -134,7 +134,9 @@ namespace slskd RoomService = roomService; Users = userService; ApplicationHub = applicationHub; + Network = networkService; + Network.StateMonitor.OnChange(networkState => State.SetValue(state => state with { Network = networkState.Current })); LogHub = logHub; Program.LogEmitted += (_, log) => LogHub.EmitLogAsync(log); diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 56777f61..a0bbe85f 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -25,6 +25,7 @@ namespace slskd.Network using System.Collections.ObjectModel; using System.IO; using System.Linq; + using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; @@ -38,11 +39,21 @@ namespace slskd.Network /// public interface INetworkService { + /// + /// Gets the network client (agent). + /// + INetworkClient Client { get; } + /// /// Gets the collection of registered Agents. /// ReadOnlyCollection RegisteredAgents { get; } + /// + /// Gets the state monitor for the service. + /// + IStateMonitor StateMonitor { get; } + /// /// Generates a random authentication challenge token for the specified . /// @@ -243,21 +254,41 @@ namespace slskd.Network IShareService shareService, IShareRepositoryFactory shareRepositoryFactory, IOptionsMonitor optionsMonitor, - IHubContext networkHub) + IHubContext networkHub, + IHttpClientFactory httpClientFactory, + INetworkClient networkClient = null) { Shares = shareService; ShareRepositoryFactory = shareRepositoryFactory; Waiter = waiter; NetworkHub = networkHub; + // wire up a dummy client so callers don't need to handle nulls + Client = networkClient ?? new DummyNetworkClient(); + + StateMonitor = State; + OptionsMonitor = optionsMonitor; + OptionsMonitor.OnChange(options => Configure(options)); + Configure(OptionsMonitor.CurrentValue); } + /// + /// Gets the network client (agent). + /// + public INetworkClient Client { get; private set; } + /// /// Gets the collection of registered Agents. /// public ReadOnlyCollection RegisteredAgents => RegisteredAgentDictionary.Values.Select(v => v.Agent).ToList().AsReadOnly(); + /// + /// Gets the state monitor for the service. + /// + public IStateMonitor StateMonitor { get; } + + private IHttpClientFactory HttpClientFactory { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IHubContext NetworkHub { get; set; } @@ -267,7 +298,11 @@ namespace slskd.Network private IShareRepositoryFactory ShareRepositoryFactory { get; } private IShareService Shares { get; } private IWaiter Waiter { get; } + private IManagedState State { get; } = new ManagedState(); private ConcurrentDictionary WaitIdDictionary { get; } = new(); + private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private string LastOptionsHash { get; set; } + private string LastControllerOptionsHash { get; set; } /// /// Generates a random authentication challenge token for the specified . @@ -553,7 +588,10 @@ namespace slskd.Network /// The ID of the connection. /// The agent. public void RegisterAgent(string connectionId, Agent agent) - => RegisteredAgentDictionary.AddOrUpdate(agent.Name, addValue: (connectionId, agent), updateValueFactory: (k, v) => (connectionId, agent)); + { + RegisteredAgentDictionary.AddOrUpdate(agent.Name, addValue: (connectionId, agent), updateValueFactory: (k, v) => (connectionId, agent)); + State.SetValue(state => state with { Agents = RegisteredAgents }); + } /// /// Safely attempts to close a stream obtained with . @@ -582,14 +620,17 @@ namespace slskd.Network /// A value indicating whether a registration was removed. public bool TryDeregisterAgent(string connectionId, out (string ConnectionId, Agent Agent) record) { + record = default; + var removed = false; + if (TryGetAgentRegistration(connectionId, out var found)) { Shares.TryRemoveHost(found.Agent.Name); - return RegisteredAgentDictionary.TryRemove(found.Agent.Name, out record); + removed = RegisteredAgentDictionary.TryRemove(found.Agent.Name, out record); } - record = default; - return false; + State.SetValue(state => state with { Agents = RegisteredAgents }); + return removed; } /// @@ -659,6 +700,57 @@ namespace slskd.Network return TryValidateCredential(token.ToString(), agentName, credential, GetShareTokenCacheKey(token)); } + private void Configure(Options options) + { + SyncRoot.Wait(); + + try + { + var optionsHash = Compute.Sha1Hash(options.Network.ToJson()); + var controllerOptionsHash = Compute.Sha1Hash(options.Network.Controller.ToJson()); + + if (optionsHash == LastOptionsHash || controllerOptionsHash == LastControllerOptionsHash) + { + return; + } + + var mode = options.Network.Mode.ToEnum(); + + if (mode == OperationMode.Controller) + { + State.SetValue(state => state with + { + Mode = mode, + Agents = RegisteredAgents, + }); + } + else + { + // the controller changed. disconnect and throw away the client and create a new one + Client = new NetworkClient(Shares, OptionsMonitor, HttpClientFactory); + Client.StateMonitor.OnChange(clientState + => State.SetValue(state => state with { Controller = state.Controller with { State = clientState.Current } })); + + State.SetValue(state => state with + { + Mode = mode, + Controller = new NetworkControllerState() + { + Address = options.Network.Controller.Address, + State = Client.StateMonitor.CurrentValue, + }, + }); + } + + LastOptionsHash = optionsHash; + LastControllerOptionsHash = controllerOptionsHash; + } + finally + { + SyncRoot.Release(); + } + } + private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth"; private string GetFileTokenCacheKey(string filename, Guid token) => $"{filename}.{token}.file"; -- cgit v1.2.3