From d51563a445a264800e54af1857b2db776a982c1e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 21 Oct 2022 09:41:20 -0500 Subject: refactor handling of file info --- src/slskd/Network/NetworkService.cs | 101 ++++++++++++++++++++---------------- 1 file changed, 56 insertions(+), 45 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 7719421f..4809ea50 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -32,11 +32,6 @@ namespace slskd.Network public interface INetworkService { - /// - /// Gets the collection of pending Agent file inquiries. - /// - ReadOnlyDictionary> PendingFileInquiries { get; } - /// /// Gets the collection of pending Agent file uploads. /// @@ -53,7 +48,7 @@ namespace slskd.Network /// The token is cached internally, and is only valid while it remains in the cache. /// The ID of the agent connection. /// The generated token. - string GenerateAuthenticationChallengeToken(ConnectionId connectionId); + string GenerateAuthenticationChallengeToken(string connectionId); /// /// Retrieves a new share upload token for the specified . @@ -86,7 +81,15 @@ namespace slskd.Network /// /// The ID of the connection. /// The agent. - void RegisterAgent(ConnectionId connectionId, Agent agent); + void RegisterAgent(string connectionId, Agent agent); + + /// + /// Handles the client response for a request. + /// + /// The agent that provided the response. + /// The ID of the request. + /// The client response to the request. + void HandleGetFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response); /// /// Attempts to remove the registration for the specified . @@ -94,7 +97,7 @@ namespace slskd.Network /// The connection ID associated with the registration. /// The registration record, if removed. /// A value indicating whether a registration was removed. - bool TryDeregisterAgent(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record); + bool TryDeregisterAgent(string connectionId, out (string ConnectionId, Agent Agent) record); /// /// Attempts to retrieve the registration for the specified . @@ -102,7 +105,7 @@ namespace slskd.Network /// The connection ID associated with the registration. /// The registration record, if found. /// A value indicating whether the registration exists. - bool TryGetAgentRegistration(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record); + bool TryGetAgentRegistration(string connectionId, out (string ConnectionId, Agent Agent) record); /// /// Validates an authentication challenge response. @@ -111,33 +114,30 @@ namespace slskd.Network /// The agent name. /// The challenge response provided by the agent. /// A value indicating whether the response is valid. - bool TryValidateAuthenticationChallengeResponse(ConnectionId connectionId, string agent, string challengeResponse); + bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse); /// /// Attempts to retrieve the specified share upload . /// /// The token. - /// The name of the agent attempting to use the token. + /// The name of the agent associated with the token. /// A value indicating whether the specified token exists. - bool TryValidateShareUploadToken(Guid token, string agentName); + bool TryValidateShareUploadToken(Guid token, out string agentName); } public class NetworkService : INetworkService { public NetworkService( + IWaiter waiter, IOptionsMonitor optionsMonitor, IHubContext networkHub) { + Waiter = waiter; NetworkHub = networkHub; OptionsMonitor = optionsMonitor; } - /// - /// Gets the collection of pending Agent file inquiries. - /// - public ReadOnlyDictionary> PendingFileInquiries => new(PendingFileInquiryDictionary); - /// /// Gets the collection of pending Agent uploads. /// @@ -148,14 +148,14 @@ namespace slskd.Network /// public ReadOnlyCollection RegisteredAgents => RegisteredAgentDictionary.Values.Select(v => v.Agent).ToList().AsReadOnly(); - private SemaphoreSlim AgentSyncRoot { get; } = new SemaphoreSlim(1, 1); + private IWaiter Waiter { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IHubContext NetworkHub { get; set; } private IOptionsMonitor OptionsMonitor { get; } private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary Stream, TaskCompletionSource Completion)> PendingFileUploadDictionary { get; } = new(); - private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); + private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); /// /// Generates a random authentication challenge token for the specified . @@ -163,7 +163,7 @@ namespace slskd.Network /// The token is cached internally, and is only valid while it remains in the cache. /// The ID of the agent connection. /// The generated token. - public string GenerateAuthenticationChallengeToken(ConnectionId connectionId) + public string GenerateAuthenticationChallengeToken(string connectionId) { var token = Cryptography.Random.GetBytes(32).ToBase62(); @@ -198,36 +198,47 @@ namespace slskd.Network /// A value indicating whether the file exists, and the length in bytes. public async Task<(bool Exists, long Length)> GetFileInfo(string agentName, string filename, int timeout = 3000) { - var id = Guid.NewGuid(); - var tcs = new TaskCompletionSource<(bool Exists, long Length)>(); - if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record)) { throw new NotFoundException($"Agent {agentName} is not registered"); } - PendingFileInquiryDictionary.TryAdd(id, tcs); + var id = Guid.NewGuid(); + var key = new WaitKey(nameof(GetFileInfo), agentName, id); + var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout); try { - await NetworkHub.Clients.Client(record.ConnectionId).RequestFileInfoAsync(filename, id); + await NetworkHub.Clients.Client(record.ConnectionId).RequestFileInfo(filename, id); Log.Information("Requested file information for {Filename} from Agent {Agent} with ID {Id}. Waiting for response.", filename, agentName, id); - var task = await Task.WhenAny(tcs.Task, Task.Delay(timeout)); - - if (task == tcs.Task) - { - return await tcs.Task; - } - else - { - throw new TimeoutException($"Timed out attempting to retrieve file information for {filename} from Agent {agentName}"); - } + return await wait; } - finally + catch (Exception ex) + { + Log.Error("Failed to fetch file information for {Filename} from Agent {Agent}: {Message}", filename, agentName, ex.Message); + throw; + } + } + + /// + /// Handles the client response for a request. + /// + /// The agent that provided the response. + /// The ID of the request. + /// The client response to the request. + public void HandleGetFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response) + { + var key = new WaitKey(nameof(GetFileInfo), agentName, id); + + if (!Waiter.ContainsKey(key)) { - PendingFileInquiryDictionary.TryRemove(id, out _); + Log.Warning("Agent {Agent} responded to a file info request with Id {Id}, but a response was not expected", agentName, id); + return; } + + Waiter.Complete(key, response); + Log.Information("Agent {Agent} responded to a file info request with Id {Id}: Exists: {Exists}, Length: {Length}", agentName, id, response.Exists, response.Length); } /// @@ -285,7 +296,7 @@ namespace slskd.Network /// /// The ID of the connection. /// The agent. - public void RegisterAgent(ConnectionId connectionId, Agent agent) + public void RegisterAgent(string connectionId, Agent agent) => RegisteredAgentDictionary.AddOrUpdate(agent.Name, addValue: (connectionId, agent), updateValueFactory: (k, v) => (connectionId, agent)); /// @@ -294,7 +305,7 @@ namespace slskd.Network /// The ID of the connection. /// The registration record, if one was removed. /// A value indicating whether a registration was removed. - public bool TryDeregisterAgent(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record) + public bool TryDeregisterAgent(string connectionId, out (string ConnectionId, Agent Agent) record) { if (TryGetAgentRegistration(connectionId, out var found)) { @@ -311,7 +322,7 @@ namespace slskd.Network /// The ID of the agent connection. /// The registration record, if one exists. /// A value indicating whether the registration exists. - public bool TryGetAgentRegistration(ConnectionId connectionId, out (ConnectionId ConnectionId, Agent Agent) record) + public bool TryGetAgentRegistration(string connectionId, out (string ConnectionId, Agent Agent) record) { var found = RegisteredAgentDictionary.Values.FirstOrDefault(v => v.ConnectionId == connectionId); record = found; @@ -326,7 +337,7 @@ namespace slskd.Network /// The agent name. /// The challenge response provided by the agent. /// A value indicating whether the response is valid. - public bool TryValidateAuthenticationChallengeResponse(ConnectionId connectionId, string agentName, string challengeResponse) + public bool TryValidateAuthenticationChallengeResponse(string connectionId, string agentName, string challengeResponse) { if (!MemoryCache.TryGetValue(GetAuthTokenCacheKey(connectionId), out var challengeToken)) { @@ -351,11 +362,11 @@ namespace slskd.Network /// Attempts to retrieve the specified share upload . /// /// The token. - /// The name of the agent attempting to use the token. + /// The name of the agent associated with the token. /// A value indicating whether the specified token exists. - public bool TryValidateShareUploadToken(Guid token, string agentName) + public bool TryValidateShareUploadToken(Guid token, out string agentName) { - if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out var cachedAgentName) && (string)cachedAgentName == agentName) + if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out agentName)) { return true; } -- cgit v1.2.3